dsh-tg-bridge 1.20.3 → 1.20.5

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.
package/README.md CHANGED
@@ -109,7 +109,7 @@ Optional provider settings live in `config.json`:
109
109
  | Key | Meaning |
110
110
  |---|---|
111
111
  | `providerKeys` | extra env var names to pass to a turn, read from `~/.dsh/.credentials.yaml`; default `[]` |
112
- | `pricesUrl` | public model page for `/prices`; default `""` uses models.dev only |
112
+ | `pricesUrl` | retired: `/prices` always reads OpenRouter's public list and labels the number as a reference for the model |
113
113
  | `vision.patch` | opt-in overlay profile for photo turns; default `""` — the turn's own model reads images |
114
114
  | `vision.enabled` | set `true` to run photo turns on `vision.patch` instead of the topic profile |
115
115
  | `fallbackModels` | free-model fallbacks; default `[]` |
@@ -24,7 +24,7 @@ import { MAX_PARALLEL, lastPrompt, queues } from './queue.mjs';
24
24
  import { token } from './secrets.mjs';
25
25
  import { config, done, log, saveState, state } from './state.mjs';
26
26
  import { send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
27
- import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
27
+ import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, startTopicFromMessage, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
28
28
  import { activeTurns, killTurn, liveSessions, profileOf, runTurnLive, turnStartedAt, typingLoop } from './turn.mjs';
29
29
  import { existsSync } from 'node:fs';
30
30
  import { join } from 'node:path';
@@ -58,16 +58,32 @@ export async function handleMessage(msg, album = null) {
58
58
  threadId = twin;
59
59
  }
60
60
 
61
- // 4. Lobby rule (Hermes' topic mode): the General thread is where topics are
62
- // started, not where work runs. A message with no thread id goes to the
63
- // most recently active topic instead of forking a root session — that is
64
- // exactly how a prompt typed in General used to be answered in General
65
- // while its topic stayed empty.
61
+ // 4. Lobby rule: the General thread is where topics are started, not where
62
+ // work runs. A prompt written there used to be moved into the most
63
+ // recently active topic, which silently dropped it into another project's
64
+ // conversation — the owner hit that twice. Now the prompt opens a topic of
65
+ // its own, named from its first words, with the person's message copied in
66
+ // as the first message and pinned.
67
+ //
68
+ // Commands are not prompts: `/status` typed in General asks about the
69
+ // bridge, it does not start a project. They keep the old recovery, and the
70
+ // guard below still refuses a state-changing one.
66
71
  if (threadId === 0 && config.generalLobby !== false) {
67
- const recovered = newestBoundTopic(chatId);
68
- if (recovered > 0) {
69
- log(`General message recovered into topic ${recovered}`);
70
- threadId = recovered;
72
+ const raw = (msg.text || msg.caption || '').trim();
73
+ const looksLikeCommand = raw.startsWith('/');
74
+ if (!looksLikeCommand && raw) {
75
+ const started = await startTopicFromMessage(chatId, msg, raw);
76
+ if (started > 0) {
77
+ threadId = started;
78
+ log(`General prompt started topic ${threadId}`);
79
+ }
80
+ }
81
+ if (threadId === 0) {
82
+ const recovered = newestBoundTopic(chatId);
83
+ if (recovered > 0) {
84
+ log(`General message recovered into topic ${recovered}`);
85
+ threadId = recovered;
86
+ }
71
87
  }
72
88
  }
73
89
  // The topic a General message was moved into, or 0 when it stayed where it was.
@@ -226,12 +242,12 @@ ${t(lang, 'help.body')}`,
226
242
  profile: profileOf(key),
227
243
  prices: (filter) => {
228
244
  const route = modelOf(profileOf(key));
229
- // A provider page is optional: without `pricesUrl` the answer comes from
230
- // the public models.dev catalog, so no install is tied to one vendor.
245
+ // One source, always the same one: OpenRouter's public list. The card
246
+ // says in words that the number is a reference for the model, not the
247
+ // bill of the route this install runs on.
231
248
  return renderPrices(filter, {
232
249
  model: route.model,
233
250
  provider: route.provider,
234
- pageUrl: config.pricesUrl || '',
235
251
  lang,
236
252
  });
237
253
  },
package/i18n/en/core.mjs CHANGED
@@ -73,6 +73,7 @@ export default {
73
73
  'status.speed': 'tok/s',
74
74
  'status.cacheLine': '🧠 cache: {pct}% ({k}k from cache)',
75
75
  'msg.topicLog': '📌 New topic: {preview}\n→ work happens in the topic, this is the log.',
76
+ 'topic.untitled': 'New topic',
76
77
  'msg.transcribing': '🎤 Transcribing…',
77
78
  'status.steps': 'steps',
78
79
  'status.thinking': 'waiting for the model',
@@ -165,14 +166,14 @@ export default {
165
166
  'msg.voiceNotRecognized': 'Could not make out the voice message{detail}',
166
167
  'prompt.photo': 'Look at the image at {path} and describe it in detail: text (verbatim, keeping its language), interface elements, objects.',
167
168
  'prompt.file': 'The user sent a file: {path} ({type}, {size} bytes).',
168
- 'prompt.voice': '🎤 This is a transcript of a voice message, produced by speech recognition. Names, Latin words, file names and rare terms may be misheard. If a word makes no sense, ask what was meant instead of guessing — the text below is what was heard, not what was said.\n\n{text}',
169
+ 'prompt.voice': '🎤 This is a transcript of a voice message, produced by speech recognition. Names, Latin words, file names and rare terms may be misheard. If a word makes no sense, ask what was meant instead of guessing — the text below is what was heard, not what was said.\n\n{text}',
169
170
  'prompt.note': 'The request: {note}',
170
171
  'prompt.fileText': 'The user sent a text file: {path} ({type}, {size} bytes). Its content is between the markers:\n<file>\n{body}\n</file>',
171
172
  'prompt.photoMidTurn': 'The image arrived mid-turn, so only its path is attached: if you cannot open images, say so in one line.',
172
173
  'bridge.progress.text': 'text: {text}',
173
174
  'bridge.progress.empty': '(empty)',
174
175
  'bridge.progress.emptyReply': '(empty reply)',
175
- 'bridge.progress.reasoningOnly': 'The turn ended without an answer. What I was thinking stayed in the notes above, so say it again in one line and I will answer.',
176
+ 'bridge.progress.reasoningOnly': 'The turn ended without an answer. What I was thinking stayed in the notes above, so say it again in one line and I will answer.',
176
177
  'bridge.error.inline': 'error: {msg}',
177
178
  'bridge.error.cliDied': 'the CLI exited with code {code} and printed nothing',
178
179
  'bridge.error.noApp': 'DeepSeek Harness is not at {path} — the bridge cannot start a turn. Install the app or point `dshApp` in config.json at it.',
package/i18n/ru/core.mjs CHANGED
@@ -73,6 +73,7 @@ export default {
73
73
  'status.speed': 'т/с',
74
74
  'status.cacheLine': '🧠 кэш: {pct}% ({k}k из кэша)',
75
75
  'msg.topicLog': '📌 Новая тема: {preview}\n→ работа идёт в теме, здесь — лог.',
76
+ 'topic.untitled': 'Новая тема',
76
77
  'msg.transcribing': '🎤 Расшифровываю…',
77
78
  'status.steps': 'шагов',
78
79
  'status.thinking': 'жду модель',
@@ -165,14 +166,14 @@ export default {
165
166
  'msg.voiceNotRecognized': 'Не распознал голосовое{detail}',
166
167
  'prompt.photo': 'Посмотри изображение по пути {path} и подробно опиши, что на нём: текст (дословно, с сохранением языка), элементы интерфейса, объекты.',
167
168
  'prompt.file': 'Пользователь прислал файл: {path} ({type}, {size} байт).',
168
- 'prompt.voice': '🎤 Это расшифровка голосового сообщения, сделанная распознаванием речи. Имена, латиница, имена файлов и редкие слова могут быть перевраны. Если слово выглядит бессмысленно, спроси, что имелось в виду, вместо того чтобы додумывать: ниже — то, что услышано, а не то, что сказано.\n\n{text}',
169
+ 'prompt.voice': '🎤 Это расшифровка голосового сообщения, сделанная распознаванием речи. Имена, латиница, имена файлов и редкие слова могут быть перевраны. Если слово выглядит бессмысленно, спроси, что имелось в виду, вместо того чтобы додумывать: ниже — то, что услышано, а не то, что сказано.\n\n{text}',
169
170
  'prompt.note': 'Просьба: {note}',
170
171
  'prompt.fileText': 'Пользователь прислал текстовый файл: {path} ({type}, {size} байт). Содержимое между маркерами:\n<file>\n{body}\n</file>',
171
172
  'prompt.photoMidTurn': 'Картинка пришла во время хода, поэтому приложен только путь: если не можешь открыть изображение, скажи это одной строкой.',
172
173
  'bridge.progress.text': 'текст: {text}',
173
174
  'bridge.progress.empty': '(пусто)',
174
175
  'bridge.progress.emptyReply': '(пустой ответ)',
175
- 'bridge.progress.reasoningOnly': 'Ход закончился без ответа: размышление выше — не ответ. Повтори мысль одной строкой, и я отвечу.',
176
+ 'bridge.progress.reasoningOnly': 'Ход закончился без ответа: размышление выше — не ответ. Повтори мысль одной строкой, и я отвечу.',
176
177
  'bridge.error.inline': 'ошибка: {msg}',
177
178
  'bridge.error.cliDied': 'CLI завершился с кодом {code} без вывода',
178
179
  'bridge.error.noApp': 'DeepSeek Harness не найден по пути {path} — ход запустить нечем. Установите приложение или укажите путь в `dshApp` в config.json.',
package/i18n/zh/core.mjs CHANGED
@@ -73,6 +73,7 @@ export default {
73
73
  'status.speed': 'tok/s',
74
74
  'status.cacheLine': '🧠 缓存:{pct}%({k}k 来自缓存)',
75
75
  'msg.topicLog': '📌 新主题:{preview}\n→ 工作在主题里进行,这里是日志。',
76
+ 'topic.untitled': '新主题',
76
77
  'msg.transcribing': '🎤 正在转写…',
77
78
  'status.steps': '步',
78
79
  'status.thinking': '等待模型',
@@ -165,14 +166,14 @@ export default {
165
166
  'msg.voiceNotRecognized': '没能识别这条语音{detail}',
166
167
  'prompt.photo': '查看路径 {path} 的图片并详细描述:文字(逐字,保留原语言)、界面元素、物体。',
167
168
  'prompt.file': '用户发来文件:{path}({type},{size} 字节)。',
168
- 'prompt.voice': '🎤 这是语音消息的转写文本,由语音识别生成。人名、拉丁字母、文件名和生僻词可能听错。如果某个词看起来没有意义,请询问本意,不要自行猜测:下面是被听到的内容,不一定是原话。\n\n{text}',
169
+ 'prompt.voice': '🎤 这是语音消息的转写文本,由语音识别生成。人名、拉丁字母、文件名和生僻词可能听错。如果某个词看起来没有意义,请询问本意,不要自行猜测:下面是被听到的内容,不一定是原话。\n\n{text}',
169
170
  'prompt.note': '请求:{note}',
170
171
  'prompt.fileText': '用户发来文本文件:{path}({type},{size} 字节)。内容在标记之间:\n<file>\n{body}\n</file>',
171
172
  'prompt.photoMidTurn': '图片是在本轮进行中发来的,只附上了路径:如果无法打开图片,请用一句话说明。',
172
173
  'bridge.progress.text': '文本:{text}',
173
174
  'bridge.progress.empty': '(空)',
174
175
  'bridge.progress.emptyReply': '(空回复)',
175
- 'bridge.progress.reasoningOnly': '这一轮没有生成回答,上面的笔记只是思考过程。请再把问题说一句,我来回答。',
176
+ 'bridge.progress.reasoningOnly': '这一轮没有生成回答,上面的笔记只是思考过程。请再把问题说一句,我来回答。',
176
177
  'bridge.error.inline': '错误:{msg}',
177
178
  'bridge.error.cliDied': 'CLI 以代码 {code} 退出且没有输出',
178
179
  'bridge.error.noApp': '未在 {path} 找到 DeepSeek Harness,无法启动回合。请安装应用,或在 config.json 中用 `dshApp` 指定路径。',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.20.3",
3
+ "version": "1.20.5",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
package/prices.mjs CHANGED
@@ -1,87 +1,45 @@
1
1
  // prices.mjs — model prices without a provider-specific plugin.
2
2
  //
3
- // `/prices` reads the public models.dev catalog by default. An install that
4
- // wants live prices from its own provider can point `pricesUrl` at that
5
- // provider's public model page; the parser is generic, so no vendor is baked
6
- // into the code.
3
+ // The one source is OpenRouter's public model list: it is JSON, it carries a
4
+ // price for every model it serves, and it is the market rate a person can check
5
+ // in one click. A private route (unorouter, wikivibe, any reseller) rarely
6
+ // publishes its own numbers, so a card built from the route's own page is empty
7
+ // or wrong. Every card therefore says whose price it shows: OpenRouter's rate
8
+ // for the same model, as a reference — not the invoice.
7
9
 
8
- const MODELS_DEV = 'https://models.dev/api.json';
10
+ const OPENROUTER = 'https://openrouter.ai/api/v1/models';
9
11
  const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
10
12
 
11
- /** "1.0M", "262K", "1,048,576" -> tokens. */
12
- export function parseCount(raw) {
13
- const text = String(raw ?? '').replace(/[,\s]/g, '').trim().toLowerCase();
14
- const match = /^([0-9]*\.?[0-9]+)([kmbt])?$/.exec(text);
15
- if (!match) return null;
16
- const scale = { k: 1e3, m: 1e6, b: 1e9, t: 1e12 }[match[2]] ?? 1;
17
- const value = Number(match[1]) * scale;
18
- return Number.isFinite(value) && value > 0 ? value : null;
19
- }
20
-
21
- /** "$0.30" -> 0.3 (USD per 1M tokens). */
22
- export function parsePrice(raw) {
23
- const match = /\$\s*([0-9]+(?:\.[0-9]+)?)/.exec(String(raw ?? ''));
24
- if (!match) return null;
25
- const value = Number(match[1]);
26
- return Number.isFinite(value) ? value : null;
27
- }
28
-
29
13
  /**
30
- * Parse the server-rendered models table.
14
+ * OpenRouter's model list -> the shape the card wants.
31
15
  *
32
- * The page is a table of cards; each row carries a model id and one or more
33
- * price cells. Rather than depend on the exact DOM, this scans for rows that
34
- * contain both a model-ish token and a `$` price, which survives markup churn.
16
+ * OpenRouter quotes dollars per token as strings ("0.00000015"); the card speaks
17
+ * per million, which is how every other price in the world is written. A model
18
+ * with no `pricing.prompt` is skipped: a missing price is not a free model.
35
19
  */
36
- export function parseModelsPage(html) {
20
+ export function parseOpenRouter(json) {
21
+ const list = Array.isArray(json?.data) ? json.data : Array.isArray(json) ? json : [];
22
+ const perMillion = (raw) => {
23
+ const value = Number(raw);
24
+ return Number.isFinite(value) && value >= 0 ? value * 1e6 : null;
25
+ };
37
26
  const models = [];
38
- // Tokens that are markup artefacts, not model ids.
39
- const junk = new Set(['data-slot', 'data-value', 'data-size', 'class', 'style', 'href', 'span', 'div', 'table', 'tbody', 'transition-colors', 'text-sm', 'text-xs', 'flex-col']);
40
- const cssLike = /(color|colou?rs|text-(?:sm|xs|lg|xl)|flex-|grid-|bg-|border-|rounded-|font-|hover:|px-|py-|mt-|mb-)/i;
41
- const rows = String(html ?? '').split(/<tr[\s>]/i).slice(1);
42
- for (const row of rows) {
43
- const text = row.replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
44
- const prices = [...text.matchAll(/\$\s*([0-9]+(?:\.[0-9]+)?)/g)].map((m) => Number(m[1]));
45
- if (prices.length === 0) continue;
46
- // A model id: a long token with a dash or a slash, never an attribute name.
47
- const candidates = [...text.matchAll(/\b([a-z][a-z0-9]*(?:[./\-][a-z0-9]+){1,4})\b/gi)]
48
- .map((m) => m[1])
49
- .filter((token) => token.length >= 6 && !junk.has(token.toLowerCase()) && !/^data-/i.test(token) && !cssLike.test(token) && /[a-z]/i.test(token) && /\d/.test(token) && /-|\./.test(token));
50
- const id = candidates.sort((a, b) => b.length - a.length)[0];
51
- if (!id) continue;
52
- // Context must be labelled; a bare number is a price or an uptime figure.
53
- const contextMatch = /(\d+(?:[.,]\d+)?)\s*([KMB])\b\s*(?:tokens|токен|context|контекст|ctx)?/i.exec(text);
54
- const parsedContext = contextMatch ? parseCount(`${contextMatch[1]}${contextMatch[2]}`) : null;
55
- // A context window above 4M is a mis-parse of some other number on the row.
56
- const context = parsedContext && parsedContext <= 4000000 ? parsedContext : null;
27
+ for (const entry of list) {
28
+ const id = String(entry?.id ?? '').trim();
29
+ const inputPrice = perMillion(entry?.pricing?.prompt);
30
+ if (!id || inputPrice === null) continue;
31
+ const outputPrice = perMillion(entry?.pricing?.completion);
57
32
  models.push({
58
- id: id.replace(/^www\./i, ''),
59
- inputPrice: prices[0],
60
- outputPrice: prices[1] ?? prices[0],
61
- context,
33
+ id,
34
+ inputPrice,
35
+ outputPrice: outputPrice === null ? inputPrice : outputPrice,
36
+ cacheReadPrice: perMillion(entry?.pricing?.input_cache_read),
37
+ context: Number(entry?.context_length) > 0 ? Number(entry.context_length) : null,
62
38
  });
63
39
  }
64
40
  return models;
65
41
  }
66
42
 
67
- /** models.dev catalog -> the same shape. */
68
- export function parseModelsDev(catalog) {
69
- const models = [];
70
- for (const [provider, entry] of Object.entries(catalog ?? {})) {
71
- for (const [id, model] of Object.entries(entry?.models ?? {})) {
72
- const cost = model.cost ?? {};
73
- if (typeof cost.input !== 'number') continue;
74
- models.push({
75
- id: `${provider}/${id}`,
76
- inputPrice: cost.input,
77
- outputPrice: typeof cost.output === 'number' ? cost.output : cost.input,
78
- context: model.limit?.context ?? null,
79
- });
80
- }
81
- }
82
- return models;
83
- }
84
-
85
43
  async function fetchText(url, timeoutMs = 20000) {
86
44
  const res = await fetch(url, {
87
45
  headers: { 'user-agent': UA },
@@ -105,11 +63,13 @@ export const WORDS = {
105
63
  cheap: 'Cheapest with context >= 128k:',
106
64
  none: 'No models matched the filter.',
107
65
  fail: 'Could not fetch prices',
108
- notPublic: 'no public price — this route does not publish one',
109
- retail: 'Gateways that do publish it: {list}',
66
+ notPublic: 'OpenRouter has no price for this model',
67
+ retail: 'Models it does price: {list}',
110
68
  yourProvider: 'price published for your provider',
111
69
  exact: 'same model on another gateway',
112
70
  similar: 'a similar model, not the same id',
71
+ reference: 'reference: OpenRouter price for the same model, not your route',
72
+ perMillion: 'per 1M tokens',
113
73
  },
114
74
  ru: {
115
75
  prices: 'Цены',
@@ -117,11 +77,13 @@ export const WORDS = {
117
77
  cheap: 'Дешёвые модели с контекстом ≥128k:',
118
78
  none: 'Ничего не нашлось по фильтру.',
119
79
  fail: 'Не смог получить цены',
120
- notPublic: 'публичной цены нет — этот маршрут её не публикует',
121
- retail: 'Публикуют цену: {list}',
80
+ notPublic: 'у OpenRouter этой модели нет',
81
+ retail: 'Есть цена у: {list}',
122
82
  yourProvider: 'цена опубликована для вашего провайдера',
123
83
  exact: 'та же модель на другом шлюзе',
124
84
  similar: 'похожая модель, не тот же id',
85
+ reference: 'ориентир: цена OpenRouter для той же модели, не вашего маршрута',
86
+ perMillion: 'за 1М токенов',
125
87
  },
126
88
  zh: {
127
89
  prices: '价格',
@@ -129,11 +91,13 @@ export const WORDS = {
129
91
  cheap: '上下文 ≥128k 的最便宜模型:',
130
92
  none: '没有符合筛选条件的模型。',
131
93
  fail: '无法获取价格',
132
- notPublic: '没有公开价格——这条线路不发布价格',
133
- retail: '公开发布价格的网关:{list}',
94
+ notPublic: 'OpenRouter 没有这个模型的价格',
95
+ retail: '有价格:{list}',
134
96
  yourProvider: '你的服务商公布的价格',
135
97
  exact: '同一模型,另一家网关',
136
98
  similar: '相似的模型,不是同一个 id',
99
+ reference: '参考:同一模型在 OpenRouter 的价格,不是你的线路',
100
+ perMillion: '每百万 token',
137
101
  },
138
102
  };
139
103
 
@@ -198,6 +162,10 @@ function claims(modelId, provider) {
198
162
  * The two lines that say what the current model costs, and whose price it is.
199
163
  * Kept apart from the fetch so the wording can be tested offline: the failure
200
164
  * this replaces was a confident "$0.0000", and a wrong price is worse than none.
165
+ *
166
+ * Every number here is OpenRouter's, and the card says so. A private route
167
+ * publishes nothing, so its own number would be either missing or invented; the
168
+ * market rate for the same model is the honest reference, and it is checkable.
201
169
  */
202
170
  export function describeCurrent(models, { model, provider } = {}, words) {
203
171
  const name = provider ? `${provider}/${model}` : model;
@@ -215,60 +183,52 @@ export function describeCurrent(models, { model, provider } = {}, words) {
215
183
  ];
216
184
  }
217
185
  const price = current.inputPrice > 0
218
- ? `${usd(current.inputPrice)} / ${usd(current.outputPrice)} per 1M`
186
+ ? `${usd(current.inputPrice)} / ${usd(current.outputPrice)} ${words.perMillion}`
219
187
  : words.notPublic;
188
+ // Whose price this is, on the same line as the id it came from: a reader must
189
+ // be able to check the number in one click, and must not think it is their
190
+ // own bill. A private route publishes nothing, so it never claims one.
220
191
  const where = claims(current.id, provider)
221
- ? words.yourProvider
222
- : `${current.id} (${current.exact ? words.exact : words.similar})`;
192
+ ? `${current.id} — ${words.yourProvider}`
193
+ : `${current.id} — ${words.reference}`;
223
194
  return [`${words.now}: ${name} — ${price}`, ` ${where}`];
224
195
  }
225
196
 
226
197
  /**
227
- * Render `/prices [filter]` from the public market catalog, plus an optional
228
- * provider page configured as `pricesUrl`. Neither source is required: if one
229
- * is down the other still answers, and with no `pricesUrl` only models.dev is
230
- * queried.
198
+ * Render `/prices [filter]`.
199
+ *
200
+ * OpenRouter is the only source: one JSON list, a published price for every
201
+ * model it serves, and a page a person can check. A second catalog would only
202
+ * reintroduce the bug this replaces — two numbers for one model, and a guess
203
+ * about which is the reader's.
204
+ *
231
205
  * @param {string} filter optional text to match model ids
232
- * @param {{ model?: string, provider?: string, pageUrl?: string, lang?: string }} options
206
+ * @param {{ model?: string, provider?: string, lang?: string }} options
233
207
  */
234
208
  export async function renderPrices(filter = '', options = {}) {
235
209
  const lang = WORDS[options.lang] ? options.lang : 'en';
236
210
  const words = WORDS[lang];
237
- const pageUrl = String(options.pageUrl || '').trim();
238
- const jobs = [fetchText(MODELS_DEV, 30000)];
239
- if (pageUrl) jobs.unshift(fetchText(pageUrl));
240
- const results = await Promise.allSettled(jobs);
241
- const page = pageUrl ? results[0] : null;
242
- const dev = pageUrl ? results[1] : results[0];
211
+ const [openrouter] = await Promise.allSettled([fetchText(OPENROUTER, 30000)]);
243
212
 
244
213
  let models = [];
245
214
  const sources = [];
246
- if (page?.status === 'fulfilled') {
247
- const parsed = parseModelsPage(page.value);
248
- if (parsed.length > 0) {
249
- models.push(...parsed);
250
- try { sources.push(new URL(pageUrl).hostname.replace(/^www\./i, '')); } catch { sources.push('provider'); }
251
- }
252
- }
253
- if (dev?.status === 'fulfilled') {
215
+ if (openrouter?.status === 'fulfilled') {
254
216
  try {
255
- const parsed = parseModelsDev(JSON.parse(dev.value));
217
+ const parsed = parseOpenRouter(JSON.parse(openrouter.value));
256
218
  if (parsed.length > 0) {
257
219
  models.push(...parsed);
258
- sources.push('models.dev');
220
+ sources.push('OpenRouter');
259
221
  }
260
222
  } catch {}
261
223
  }
262
224
  if (models.length === 0) {
263
- const reason = dev?.status === 'rejected'
264
- ? dev.reason?.message
265
- : page?.status === 'rejected'
266
- ? page.reason?.message
267
- : 'catalogs parsed to 0 models';
225
+ const reason = openrouter?.status === 'rejected'
226
+ ? openrouter.reason?.message
227
+ : 'the OpenRouter list parsed to 0 models';
268
228
  return `${words.fail}: ${reason}`;
269
229
  }
270
230
 
271
- // The live page wins on duplicate ids; models.dev fills the rest.
231
+ // One catalog, so duplicate ids cannot disagree about a price.
272
232
  const seen = new Set();
273
233
  models = models.filter((model) => {
274
234
  const id = model.id.toLowerCase();
package/topics.mjs CHANGED
@@ -136,6 +136,83 @@ export async function ensureTopicSeed(chatId, threadId, text) {
136
136
  return messageId;
137
137
  }
138
138
 
139
+ /**
140
+ * A topic title made from the first words of a prompt.
141
+ *
142
+ * Telegram caps topic names at 128 characters, but the useful limit is much
143
+ * shorter: the name is a handle in a sidebar, not a summary. Six words or forty
144
+ * characters, whichever comes first — a long first sentence would otherwise
145
+ * push every other topic out of view.
146
+ */
147
+ export function topicTitleFrom(text, max = 40) {
148
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
149
+ if (!flat) return '';
150
+ const words = flat.split(' ').slice(0, 6).join(' ');
151
+ if (words.length <= max) return words;
152
+ return `${words.slice(0, max - 1).trimEnd()}…`;
153
+ }
154
+
155
+ /**
156
+ * Open a new topic for a message written in General, and make it start with
157
+ * that message.
158
+ *
159
+ * General ("Все") is the stream a person types into when they do not want to
160
+ * pick a topic first. The old rule moved such a message into the most recently
161
+ * active topic, which silently dropped it into another project's conversation —
162
+ * the owner hit this twice. Starting a topic instead keeps every prompt in a
163
+ * place of its own, named after what was asked.
164
+ *
165
+ * `copyMessage` is used rather than `sendMessage` so the topic opens with the
166
+ * person's own message, media included, and without a "forwarded from" header.
167
+ * The copy is pinned, which is the behaviour the owner asked for.
168
+ *
169
+ * Returns the new thread id, or 0 when Telegram refused to create the topic
170
+ * (a group without topic permissions, or a rate limit) — the caller then falls
171
+ * back to the old recovery so the message is not lost.
172
+ */
173
+ export async function startTopicFromMessage(chatId, msg, text) {
174
+ const name = topicTitleFrom(text) || t(config.lang || 'en', 'topic.untitled');
175
+ let threadId = 0;
176
+ try {
177
+ const created = await tg('createForumTopic', { chat_id: chatId, name });
178
+ threadId = Number(created?.message_thread_id || 0);
179
+ } catch (error) {
180
+ log(`General message could not start a topic: ${error.message}`);
181
+ return 0;
182
+ }
183
+ if (!(threadId > 0)) return 0;
184
+ log(`General message started topic ${threadId} "${name}"`);
185
+
186
+ let messageId = 0;
187
+ try {
188
+ const copied = await tg('copyMessage', {
189
+ chat_id: chatId,
190
+ from_chat_id: chatId,
191
+ message_id: msg.message_id,
192
+ message_thread_id: threadId,
193
+ });
194
+ messageId = Number(copied?.message_id || 0);
195
+ } catch (error) {
196
+ // Media Telegram will not copy (a poll, a protected file) still deserves a
197
+ // seed, otherwise the topic is a title over an empty page.
198
+ log(`topic ${threadId} copy failed: ${error.message}`);
199
+ }
200
+ if (!messageId) return threadId;
201
+
202
+ state.seededTopics = state.seededTopics ?? {};
203
+ state.seededTopics[String(threadId)] = messageId;
204
+ saveState();
205
+ noteSeed(text, threadId);
206
+ if (config.pinTopicSeed !== false) {
207
+ try {
208
+ await tg('pinChatMessage', { chat_id: chatId, message_id: messageId, disable_notification: false });
209
+ } catch (error) {
210
+ log(`topic ${threadId} pin failed: ${error.message}`);
211
+ }
212
+ }
213
+ return threadId;
214
+ }
215
+
139
216
  /**
140
217
  * Write one line about a new topic into the General chat, so the main stream
141
218
  * reads as a log of what was started instead of a wall of prompts. The full