dsh-tg-bridge 1.39.0 → 1.40.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.
package/README.md CHANGED
@@ -311,14 +311,15 @@ Send the bot:
311
311
  | `/thoughts [file\|all\|off]` | the last turn's reasoning as a message; `file`/`all` send the full log as a Markdown document, `off` hides the block |
312
312
  | `/help` | commands grouped by category |
313
313
  | `/cd my-app` | topic bound to the project, and the sandbox narrowed to it |
314
- | `/diff [stat]` | what the turn changed, one hunk at a time: every hunk has "explain" and "revert this hunk"; a stale button is refused |
314
+ | `/diff [stat]` | what the turn changed, one hunk at a time: every hunk has "explain" and "revert this hunk"; a stale button is refused |
315
+ | `/find <text> [path]` | where a literal string lives in the topic's folder: matches as buttons that open the file at the matched line; binary and oversized files are skipped and counted |
315
316
  | `/report` | a redacted bundle (version, profile, preset, model, cwd, last failure, log tail) sent to the owner as a document; in a group, the path only |
316
317
  | `/prices` | what the current model costs, and whose price that is: your provider's, the same model on another gateway, or "no public price" when nobody publishes one |
317
318
 
318
319
  ## Commands
319
320
 
320
321
  ```
321
- Work: /cd · /new · /stop · /send · /seed · /diff
322
+ Work: /cd · /new · /stop · /send · /seed · /diff · /find <text> [path]
322
323
  Goals: /goal (plan + checklist) · /goal reopen · /tasks (checklist only) · /tasks done|rm|edit <n>
323
324
  Sessions: /status · /sessions · /sessions <id> · /rewind [n|undo|fork [n]|branches]
324
325
  Agents: /agents · /agents <id> · /agents set model|depth|filter
@@ -18,6 +18,7 @@ import { handleModelPress, MODEL_PREFIX, modelPressRouter } from '../control/mod
18
18
  import { runCommandFromButton } from '../core/run-command.mjs';
19
19
  import { handleCardPress } from '../profile/settings-press.mjs';
20
20
  import { cardBlocks, cardKeyboard, renderCardSettings, toggleCardBlock } from '../turn/card.mjs';
21
+ import { handleFilePress } from './file-press.mjs';
21
22
  import { config, done, log, saveState, state } from '../core/state.mjs';
22
23
  import { inlineKeyboard, send, sendFile, tg, tgFast } from './telegram.mjs';
23
24
  import { sessionFile } from './thoughts.mjs';
@@ -344,6 +345,8 @@ export async function handleCallback(query) {
344
345
  if (await modelPressRouter({ chatId, threadId, messageId, key, lang, answer, log })(data)) return;
345
346
  }
346
347
 
348
+ if (await handleFilePress({ data, key, lang, chatId, threadId, messageId, answer })) return;
349
+
347
350
  if (data.startsWith('tc:')) {
348
351
  // The turn card's own switches. Redrawn from state like the task card, so a
349
352
  // double tap settles on one truth; an id this build does not know answers
@@ -12,7 +12,7 @@ export const CONTROL_COMMANDS = [
12
12
  'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
13
13
  'prices', 'cost', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
14
14
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
15
- 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card',
15
+ 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find',
16
16
  ];
17
17
 
18
18
  /**
package/chat/control.mjs CHANGED
@@ -40,6 +40,7 @@ import { handleTaskCommands } from '../control/cmd-task.mjs';
40
40
  import { handleViewCommands } from '../control/cmd-views.mjs';
41
41
  import { handleEndpointCommands } from '../control/cmd-endpoint.mjs';
42
42
  import { handleEveryCommands } from '../control/cmd-every.mjs';
43
+ import { handleFindCommands } from '../control/cmd-find.mjs';
43
44
  import { handleDshCommands } from '../control/cmd-dsh.mjs';
44
45
  import { handleCompactCommands } from '../control/cmd-compact.mjs';
45
46
  import { APP, CLI_JS, DSH_CMD, DSH_HOME, EXE, HOME, PROFILES, THOUGHT_DIR } from '../core/paths.mjs';
@@ -113,7 +114,7 @@ export async function handleControl(ctx) {
113
114
  // that is not its job. The order is alphabetical, not meaningful: no two
114
115
  // groups claim the same command, so a miss falls through to `default` below.
115
116
  const child = { ...ctx, effective, command, arg: effectiveArgText, send, reply, log, profile, state, key, config, lang };
116
- for (const handler of [handleAgentCommands, handleBridgeCommands, handleCardCommands, handleCompactCommands, handleDiffCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
117
+ for (const handler of [handleAgentCommands, handleBridgeCommands, handleCardCommands, handleCompactCommands, handleDiffCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleFindCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
117
118
  if (await handler(child)) return true;
118
119
  }
119
120
  // Nothing claimed it: the bridge answers an unknown `/` command itself, with
@@ -0,0 +1,67 @@
1
+ // A `/find` result pressed: open the file at the matched line, and page through it.
2
+ //
3
+ // Kept out of the callback router because the router was already at the size
4
+ // ceiling, and because this is the one place a press reads a file from disk: the
5
+ // fence, the preview and the "more" button belong together.
6
+ import { previewWindow } from './file-preview.mjs';
7
+ import { t } from '../core/i18n.mjs';
8
+ import { saveState, state } from '../core/state.mjs';
9
+ import { inlineKeyboard, tg } from './telegram.mjs';
10
+
11
+ /**
12
+ * Handle one `fs:` press.
13
+ *
14
+ * @returns {Promise<boolean>} true when the press was this module's to answer.
15
+ */
16
+ export async function handleFilePress({ data, key, lang, chatId, threadId, messageId, answer }) {
17
+ if (!String(data || '').startsWith('fs:')) return false;
18
+ const body = String(data).slice(3);
19
+ if (body.startsWith('more:')) {
20
+ const cur = state.preview?.[key];
21
+ if (!cur) {
22
+ await answer(t(lang, 'ctrl.find.stale'));
23
+ return true;
24
+ }
25
+ const start = Number(body.slice(5)) || 0;
26
+ const view = previewWindow({ root: cur.root, file: cur.file, line: cur.line, start, lang });
27
+ if (view.refusal) {
28
+ await answer(t(lang, `ctrl.find.file.${view.refusal}`));
29
+ return true;
30
+ }
31
+ state.preview[key] = { ...cur, start };
32
+ saveState();
33
+ await tg('editMessageText', {
34
+ chat_id: chatId,
35
+ message_id: messageId,
36
+ text: view.text,
37
+ reply_markup: { inline_keyboard: inlineKeyboard(view.keyboard) },
38
+ }).catch(() => {});
39
+ await answer(t(lang, 'ctrl.find.moreDone'));
40
+ return true;
41
+ }
42
+
43
+ const found = state.find?.[key];
44
+ const hit = found?.hits?.[Number(body)];
45
+ if (!hit) {
46
+ // A card older than the last search: its rows are gone, so naming that is
47
+ // kinder than opening whatever now sits at that number.
48
+ await answer(t(lang, 'ctrl.find.stale'));
49
+ return true;
50
+ }
51
+ const view = previewWindow({ root: found.root, file: hit.file, line: hit.line, lang });
52
+ if (view.refusal) {
53
+ await answer(t(lang, `ctrl.find.file.${view.refusal}`));
54
+ return true;
55
+ }
56
+ state.preview = state.preview || {};
57
+ state.preview[key] = { root: found.root, file: hit.file, line: hit.line, start: 0 };
58
+ saveState();
59
+ await tg('sendMessage', {
60
+ chat_id: chatId,
61
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
62
+ text: view.text,
63
+ reply_markup: { inline_keyboard: inlineKeyboard(view.keyboard) },
64
+ }).catch(() => {});
65
+ await answer(t(lang, 'ctrl.find.opened', { line: hit.line }));
66
+ return true;
67
+ }
@@ -0,0 +1,60 @@
1
+ // A file in the chat: forty lines at a time, with the line that matched marked.
2
+ //
3
+ // `/find` results are buttons, and pressing one has to open the file where the
4
+ // match is — otherwise the search answers "line 412" to a person holding a phone
5
+ // who cannot go to line 412. The window is centred a little above the match so
6
+ // the context around it is readable, and "more" keeps going from where it ended.
7
+ import { readFileSync } from 'node:fs';
8
+ import { isAbsolute, resolve } from 'node:path';
9
+ import { readTextFile, resolveInRoot } from '../lib/file-fence.mjs';
10
+ import { t } from '../core/i18n.mjs';
11
+
12
+ /** Lines in one window. */
13
+ export const PAGE = 40;
14
+
15
+ /** The first line of a window that should contain `line` (1-based). */
16
+ export function windowStart(line, size, start = null) {
17
+ const total = Math.max(1, Number(size) || 1);
18
+ if (Number.isFinite(start) && start !== null) return Math.min(Math.max(0, start), Math.max(0, total - 1));
19
+ const target = Math.min(Math.max(1, Number(line) || 1), total);
20
+ return Math.max(0, Math.min(target - 1 - Math.floor(PAGE / 3), Math.max(0, total - PAGE)));
21
+ }
22
+
23
+ /**
24
+ * Text and buttons for one window of a file.
25
+ *
26
+ * @returns {{ text: string, keyboard: object[][], next: number|null } | { refusal: string }}
27
+ */
28
+ export function previewWindow({ root, file, line = 1, start = null, lang = 'en' }) {
29
+ const full = isAbsolute(file) ? file : resolve(root, file);
30
+ const inRoot = resolveInRoot(root, full);
31
+ if (inRoot.refusal) return { refusal: inRoot.refusal };
32
+ const read = readTextFile(full);
33
+ if (read.refusal) return { refusal: read.refusal };
34
+ const lines = read.text.split(/\r?\n/);
35
+ const from = windowStart(line, lines.length, start);
36
+ const slice = lines.slice(from, from + PAGE);
37
+ const hit = Number(line);
38
+ const body = slice.map((text, index) => {
39
+ const n = from + index + 1;
40
+ const mark = n === hit ? '▶' : ' ';
41
+ return `${mark} ${String(n).padStart(4, ' ')} ${text}`.slice(0, 160);
42
+ });
43
+ const to = from + slice.length;
44
+ const head = t(lang, 'ctrl.find.preview', { path: file, from: from + 1, to, total: lines.length });
45
+ const next = to < lines.length ? to : null;
46
+ const keyboard = next === null ? [] : [[{
47
+ text: t(lang, 'ctrl.find.more', { n: Math.min(PAGE, lines.length - next) }),
48
+ data: `fs:more:${next}`,
49
+ }]];
50
+ return { text: [head, '', ...body].join('\n'), keyboard, next };
51
+ }
52
+
53
+ /** Read the file back for a size check without keeping it around. */
54
+ export function lineCount(file) {
55
+ try {
56
+ return readFileSync(file, 'utf8').split(/\r?\n/).length;
57
+ } catch {
58
+ return 0;
59
+ }
60
+ }
@@ -9,7 +9,7 @@ import { t } from '../core/i18n.mjs';
9
9
 
10
10
  /** The /help group each command is listed under. */
11
11
  const SECTION = {
12
- cd: 'Work', new: 'Work', stop: 'Work', send: 'Work', seed: 'Work', diff: 'Work',
12
+ cd: 'Work', new: 'Work', stop: 'Work', send: 'Work', seed: 'Work', diff: 'Work', find: 'Work',
13
13
  goal: 'Goals', task: 'Goals', tasks: 'Goals',
14
14
  status: 'Sessions', sessions: 'Sessions', rewind: 'Sessions', profile: 'Sessions',
15
15
  agents: 'Agents', model: 'Models', prices: 'Models', cost: 'Models', thoughts: 'Models', fallback: 'Models', endpoint: 'Models',
@@ -20,7 +20,7 @@ const SECTIONS = {
20
20
  goals: ['goal', 'task', 'tasks', 'plan', 'jobs', 'remind', 'every'],
21
21
  talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'lang', 'endpoint', 'fallback'],
22
22
  ext: ['plugins', 'skills', 'soul', 'preset', 'permissions', 'crew'],
23
- house: ['load', 'settings', 'card', 'update', 'dsh', 'compact', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'help'],
23
+ house: ['load', 'settings', 'card', 'find', 'update', 'dsh', 'compact', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'help'],
24
24
  };
25
25
 
26
26
  /**
package/chat/panel.mjs CHANGED
@@ -115,6 +115,31 @@ export function stepLine(event) {
115
115
  return `${tool}: ${text.slice(0, 64)}`;
116
116
  }
117
117
 
118
+ /** Is this tool call a subagent, i.e. a whole turn running on the side? */
119
+ export function isSubagentTool(tool) {
120
+ return /^subagent/i.test(String(tool || ''));
121
+ }
122
+
123
+ /**
124
+ * A subagent as one step line, with how long it took when that is known.
125
+ *
126
+ * The headless stream has no event type for subagents — no who, no tokens, no
127
+ * live progress — so a subagent reaches the bridge as an ordinary tool call and
128
+ * result. That is still enough to say the honest part: which task ran, and how
129
+ * long it took between its call and its result. The duration is measured, not
130
+ * reported, and a line without it means the result never came.
131
+ */
132
+ export function subagentStep(event, ms = null) {
133
+ const input = event?.input ?? {};
134
+ const label = String(input.description ?? input.prompt ?? '')
135
+ .replace(/\s+/g, ' ')
136
+ .trim()
137
+ .slice(0, 52);
138
+ const head = label ? `${event?.tool || 'subagent'}: ${label}` : `${event?.tool || 'subagent'}`;
139
+ if (!Number.isFinite(ms) || ms < 0) return head;
140
+ return `${head} · ${Math.max(1, Math.round(ms / 1000))}s`;
141
+ }
142
+
118
143
  /** Push a step, folding a repeat into the line above it: `×3`, not three rows. */
119
144
  export function addStep(steps, line) {
120
145
  if (!line) return steps;
@@ -0,0 +1,122 @@
1
+ // `/find`: where does this string live in this project.
2
+ //
3
+ // The chat could send a file and show a diff, but not answer the question that
4
+ // sends a person back to their desk — "which file has this line". The search is
5
+ // literal on purpose: a query is text a person typed, not a pattern, and a stray
6
+ // dot must not change the answer or throw.
7
+ import { relative } from 'node:path';
8
+ import { readTextFile, resolveInRoot, walkFiles } from '../lib/file-fence.mjs';
9
+ import { t } from '../core/i18n.mjs';
10
+ import { config } from '../core/state.mjs';
11
+
12
+ /** Rows the card shows; more than this and the answer says how many more. */
13
+ export const CAP = 20;
14
+
15
+ /** Matches inside one already-open file. */
16
+ export function hitsInText(text, path, needle) {
17
+ const hits = [];
18
+ const lines = String(text).split(/\r?\n/);
19
+ for (let at = 0; at < lines.length; at += 1) {
20
+ if (!lines[at].includes(needle)) continue;
21
+ hits.push({ path, line: at + 1, text: lines[at].trim().slice(0, 120) });
22
+ }
23
+ return hits;
24
+ }
25
+
26
+ /**
27
+ * Search `root` for `query`, literally.
28
+ *
29
+ * A file the fence refuses is counted as skipped and never opened: reading a
30
+ * binary to prove it is binary is the cost the fence exists to avoid.
31
+ *
32
+ * @returns {{ hits: {path: string, line: number, text: string}[], found: number,
33
+ * skipped: number, stopped: boolean }}
34
+ */
35
+ export function findInFiles(root, query, { cap = CAP, bound } = {}) {
36
+ const needle = String(query || '');
37
+ const hits = [];
38
+ let found = 0;
39
+ let skipped = 0;
40
+ const walked = walkFiles(root, bound);
41
+ for (const full of walked.files) {
42
+ const read = readTextFile(full);
43
+ if (read.refusal) {
44
+ skipped += 1;
45
+ continue;
46
+ }
47
+ const rows = hitsInText(read.text, relative(root, full) || full, needle);
48
+ found += rows.length;
49
+ for (const row of rows) if (hits.length < cap) hits.push(row);
50
+ }
51
+ return { hits, found, skipped: skipped + walked.skipped, stopped: walked.stopped };
52
+ }
53
+
54
+ /** The folder this topic works in. */
55
+ export function topicRoot(state, key) {
56
+ return (state?.cwd && state.cwd[key]) || config.cwd || '';
57
+ }
58
+
59
+ export async function handleFindCommands(ctx) {
60
+ const { effective, arg, state, key, lang, reply } = ctx;
61
+ if (effective !== '/find') return false;
62
+ const parts = String(arg || '').trim().split(/\s+/).filter(Boolean);
63
+ if (parts.length === 0) {
64
+ await reply(t(lang, 'ctrl.find.usage'));
65
+ return true;
66
+ }
67
+ const query = parts[0].replace(/^"|"$/g, '');
68
+ const root = topicRoot(state, key);
69
+ const fenced = resolveInRoot(root, parts.slice(1).join(' ') || '.');
70
+ if (fenced.refusal) {
71
+ await reply(t(lang, `ctrl.find.${fenced.refusal === 'outside' ? 'outside' : fenced.refusal}`, { root }));
72
+ return true;
73
+ }
74
+ if (!fenced.dir) {
75
+ // One file asked for by name: the same answer, without the walk.
76
+ const read = readTextFile(fenced.path);
77
+ if (read.refusal) {
78
+ await reply(t(lang, `ctrl.find.file.${read.refusal}`));
79
+ return true;
80
+ }
81
+ const rows = hitsInText(read.text, fenced.path, query);
82
+ return draw(ctx, { hits: rows.slice(0, CAP), found: rows.length, skipped: 0, stopped: false }, fenced.path, query);
83
+ }
84
+ const result = findInFiles(fenced.path, query);
85
+ return draw(ctx, result, fenced.path, query);
86
+ }
87
+
88
+ /** Draw the answer: rows as buttons, and the counts that make them honest. */
89
+ async function draw(ctx, result, root, query) {
90
+ const { state, key, lang, reply } = ctx;
91
+ if (result.found === 0) {
92
+ await reply(t(lang, 'ctrl.find.none', { path: root, query }), { keyboard: [] });
93
+ return true;
94
+ }
95
+ const lines = [t(lang, 'ctrl.find.head', { query, path: root, n: result.found })];
96
+ if (result.stopped) lines.push(t(lang, 'ctrl.find.stopped'));
97
+ if (result.skipped > 0) lines.push(t(lang, 'ctrl.find.skipped', { n: result.skipped }));
98
+ if (result.found > result.hits.length) {
99
+ lines.push(t(lang, 'ctrl.find.cap', { shown: result.hits.length, found: result.found }));
100
+ }
101
+ lines.push('');
102
+ result.hits.forEach((hit, index) => {
103
+ lines.push(`${index + 1}. ${hit.path}:${hit.line}: ${hit.text}`.slice(0, 220));
104
+ });
105
+ // Rows are remembered rather than encoded: callback data is capped at 64 bytes
106
+ // and a path can be longer than that, so the button carries the number and the
107
+ // state carries the hit it points at.
108
+ state.find = state.find || {};
109
+ state.find[key] = {
110
+ root,
111
+ hits: result.hits.map((hit) => ({ file: hit.path, line: hit.line })),
112
+ query,
113
+ at: Date.now(),
114
+ };
115
+ ctx.saveState?.();
116
+ const keyboard = result.hits.map((hit, index) => [{
117
+ text: `${index + 1}. ${hit.path.split(/[\\/]/).pop()}:${hit.line}`.slice(0, 60),
118
+ data: `fs:${index}`,
119
+ }]);
120
+ await reply(lines.join('\n'), { keyboard });
121
+ return true;
122
+ }
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # CHANGELOG — DSH Telegram bridge
2
2
 
3
+ ## 1.40.0
4
+
5
+ - **`/find <text> [path]` — where a string lives in this project.** The chat could
6
+ send a file and show a diff, but not answer "which file has this line", the
7
+ question that sends a person back to their desk. The search is literal, so a
8
+ query with `.`, `*`, `(` or `\` searches for those characters instead of
9
+ throwing; it is bounded by files, milliseconds and depth, and says when the
10
+ walk stopped. Twenty rows come back as buttons, with the total and a hint how to
11
+ narrow; a file that is binary or over 512 KB is skipped and counted, never read.
12
+ Pressing a row opens the file at the matched line, marked `▶`, with a **more**
13
+ button that pages forty lines at a time.
14
+ - **One fence for every file the chat touches** (`lib/file-fence.mjs`): a path
15
+ outside the topic folder is refused with the folder named, a file is opened only
16
+ when it is plausibly text and under the cap, and the walk skips `.git`,
17
+ `node_modules` and their kind. `/ls` and `/edit` will read through the same
18
+ fence, so the rule cannot drift between three commands.
19
+ - `lib/` joins the published files; the fence is imported by shipped modules.
20
+
21
+ ## 1.39.1
22
+
23
+ - **A subagent is visible in the card as one honest line.** The headless stream
24
+ has no event type for subagents — a scan of its JSON stream found seven types,
25
+ and `subagent` is not one of them — so a subagent reaches the bridge as an
26
+ ordinary tool call plus a later result. The card now shows the task it was
27
+ given when the call starts, and adds the measured duration when the result
28
+ arrives (`subagent: Проверить релиз · 42s`), with a `✖` when it failed. The
29
+ duration is wall clock between the two events, because that is the only source
30
+ the stream offers; token counts and live progress would need a DSH plugin.
31
+
3
32
  ## 1.39.0
4
33
 
5
34
  - **A Telegram session now appears under its folder in the desktop sidebar**
package/i18n/en/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'on',
15
15
  'settings.state.off': 'off',
16
16
  'settings.state.auto': 'auto',
17
- 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e · /diff [stat]\nGoals: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels per topic: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nOther: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
17
+ 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e · /diff [stat] · /find \u003ctext\u003e\nGoals: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels per topic: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nOther: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
18
18
  'settings.reply.title': 'What the bot says',
19
19
  'settings.agent.title': 'Who answers, and how hard it works',
20
20
  'settings.updates.title': 'New releases (this install, not this topic)',
@@ -300,4 +300,23 @@ export default {
300
300
  'bridge.cb.taskUndone': 'Reopened',
301
301
  'bridge.cb.taskStale': 'That task is gone — /tasks shows the current list',
302
302
  'msg.loadHeld': "Held back: {what}. Nothing was started, so nothing was spent — press «Run anyway» to send it now, or wait until the machine calms down.",
303
+ 'ctrl.find.usage': "Usage: /find <text> [path] — searches the topic folder for a literal string.",
304
+ 'ctrl.find.outside': "That path is outside this topic folder: {root}",
305
+ 'ctrl.find.missing': "No such file or folder in {root}",
306
+ 'ctrl.find.empty': "This topic has no folder yet — /cd <project> first",
307
+ 'ctrl.find.none': "Nothing matches «{query}» in {path}",
308
+ 'ctrl.find.head': "Found {n} for «{query}» in {path}",
309
+ 'ctrl.find.stopped': "The walk stopped early — narrow the search or name a subfolder",
310
+ 'ctrl.find.skipped': "Skipped {n} file(s): binary or too large",
311
+ 'ctrl.find.cap': "Showing {shown} of {found} — add a subfolder to narrow it",
312
+ 'ctrl.find.file.large': "That file is larger than 512 KB — open it on the machine",
313
+ 'ctrl.find.file.binary': "That file is not text — /send hands it over intact",
314
+ 'ctrl.find.file.missing': "That file is gone",
315
+ 'ctrl.find.file.dir': "That is a folder, not a file",
316
+ 'ctrl.find.preview': "{path} · lines {from}–{to} of {total}",
317
+ 'ctrl.find.more': "More ({n} lines)",
318
+ 'ctrl.find.moreDone': "Next lines",
319
+ 'ctrl.find.stale': "That list is from an older search — run /find again",
320
+ 'ctrl.find.opened': "Opened at line {line}",
321
+ 'ctrl.help.about.find': "/find <text> [path] — searches this topic's folder for a literal string and shows every match as a button; pressing one opens the file at that line. Binary files and files over 512 KB are skipped and counted.",
303
322
  };
package/i18n/ru/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'вкл',
15
15
  'settings.state.off': 'выкл',
16
16
  'settings.state.auto': 'авто',
17
- 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e · /diff [stat]\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодель у каждой темы: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nПрочее: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
17
+ 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e · /diff [stat] · /find \u003ctext\u003e\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодель у каждой темы: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nПрочее: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
18
18
  'settings.reply.title': 'Что бот говорит',
19
19
  'settings.agent.title': 'Кто отвечает и как старается',
20
20
  'settings.updates.title': 'Новые версии (эта установка, не тема)',
@@ -300,4 +300,23 @@ export default {
300
300
  'bridge.cb.taskUndone': 'Снова открыта',
301
301
  'bridge.cb.taskStale': 'Такой задачи уже нет — /tasks покажет текущий список',
302
302
  'msg.loadHeld': "Придержал: {what}. Ничего не запущено, и ничего не потрачено — нажми «Всё равно запустить», чтобы отправить сейчас, или подожди, пока машина освободится.",
303
+ 'ctrl.find.usage': "Как: /find <текст> [путь] — ищет строку в папке темы, буквально.",
304
+ 'ctrl.find.outside': "Этот путь вне папки темы: {root}",
305
+ 'ctrl.find.missing': "В {root} такого файла или папки нет",
306
+ 'ctrl.find.empty': "У темы ещё нет папки — сначала /cd <проект>",
307
+ 'ctrl.find.none': "По «{query}» в {path} ничего нет",
308
+ 'ctrl.find.head': "Нашлось {n} по «{query}» в {path}",
309
+ 'ctrl.find.stopped': "Обход остановился раньше — сузь поиск или назови подпапку",
310
+ 'ctrl.find.skipped': "Пропущено файлов: {n} — двоичные или слишком большие",
311
+ 'ctrl.find.cap': "Показано {shown} из {found} — добавь подпапку, чтобы сузить",
312
+ 'ctrl.find.file.large': "Файл больше 512 КБ — открой его на машине",
313
+ 'ctrl.find.file.binary': "Это не текст — /send отдаст файл как есть",
314
+ 'ctrl.find.file.missing': "Файла больше нет",
315
+ 'ctrl.find.file.dir': "Это папка, а не файл",
316
+ 'ctrl.find.preview': "{path} · строки {from}–{to} из {total}",
317
+ 'ctrl.find.more': "Ещё ({n} строк)",
318
+ 'ctrl.find.moreDone': "Следующие строки",
319
+ 'ctrl.find.stale': "Список из прошлого поиска — запусти /find снова",
320
+ 'ctrl.find.opened': "Открыто на строке {line}",
321
+ 'ctrl.help.about.find': "/find <текст> [путь] — ищет в папке темы буквальную строку и показывает совпадения кнопками: нажатие открывает файл на этой строке. Двоичные и слишком большие файлы пропускаются со счётчиком.",
303
322
  };
package/i18n/zh/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': '开',
15
15
  'settings.state.off': '关',
16
16
  'settings.state.auto': '自动',
17
- 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e · /diff [stat]\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n每个话题各自的模型:/model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\n其他: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
17
+ 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e · /diff [stat] · /find \u003ctext\u003e\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n每个话题各自的模型:/model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\n其他: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
18
18
  'settings.reply.title': '机器人怎么说',
19
19
  'settings.agent.title': '谁来回答、投入多少',
20
20
  'settings.updates.title': '新版本(针对本次安装,而非话题)',
@@ -300,4 +300,23 @@ export default {
300
300
  'bridge.cb.taskUndone': '已重新打开',
301
301
  'bridge.cb.taskStale': '该任务已不存在——用 /tasks 查看当前列表',
302
302
  'msg.loadHeld': "已暂缓:{what}。没有启动任何东西,也没有产生费用——点按「仍然运行」立即发送,或等机器空闲。",
303
+ 'ctrl.find.usage': "用法:/find <文字> [路径] —— 在话题目录里按字面查找",
304
+ 'ctrl.find.outside': "这个路径在话题目录之外:{root}",
305
+ 'ctrl.find.missing': "{root} 里没有这个文件或目录",
306
+ 'ctrl.find.empty': "这个话题还没有目录 —— 先 /cd <项目>",
307
+ 'ctrl.find.none': "在 {path} 里没有找到「{query}」",
308
+ 'ctrl.find.head': "在 {path} 找到 {n} 处「{query}」",
309
+ 'ctrl.find.stopped': "扫描提前停止 —— 缩小范围或指定子目录",
310
+ 'ctrl.find.skipped': "跳过 {n} 个文件:二进制或过大",
311
+ 'ctrl.find.cap': "显示 {shown} / {found} —— 指定子目录可缩小范围",
312
+ 'ctrl.find.file.large': "文件超过 512 KB —— 请在电脑上打开",
313
+ 'ctrl.find.file.binary': "这不是文本文件 —— /send 可原样发送",
314
+ 'ctrl.find.file.missing': "文件已不在",
315
+ 'ctrl.find.file.dir': "这是目录,不是文件",
316
+ 'ctrl.find.preview': "{path} · 第 {from}-{to} 行,共 {total} 行",
317
+ 'ctrl.find.more': "更多({n} 行)",
318
+ 'ctrl.find.moreDone': "接下来的行",
319
+ 'ctrl.find.stale': "这是上一次搜索的列表 —— 重新运行 /find",
320
+ 'ctrl.find.opened': "已打开第 {line} 行",
321
+ 'ctrl.help.about.find': "/find <文字> [路径] —— 在话题目录里按字面查找,结果以按钮显示,点开即跳到该行。二进制或过大的文件会被跳过并计数。",
303
322
  };
@@ -0,0 +1,121 @@
1
+ // One fence in front of every file the chat touches: `/find` reads through it,
2
+ // and `/ls` and `/edit` will too.
3
+ //
4
+ // Two rules, both learned the hard way. Nothing outside the topic's folder is
5
+ // read, because a path from a chat message is not a permission. And a file is
6
+ // opened only when it is plausibly text and plausibly small: a 400 MB log would
7
+ // freeze the turn that asked for one line of it, and a binary would put noise in
8
+ // the chat. A refusal is a sentence with a reason, never a stack trace.
9
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
10
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
11
+
12
+ /** A text file bigger than this is refused rather than read. */
13
+ export const MAX_BYTES = 512 * 1024;
14
+
15
+ /** How far a walk goes before it says it stopped. */
16
+ export const BOUND = { files: 4000, ms: 1500, depth: 8 };
17
+
18
+ /** Folders that never hold an answer and can hold thousands of files. */
19
+ export const SKIP_DIRS = new Set([
20
+ '.git', 'node_modules', '.next', 'dist', 'build', 'coverage', '.cache',
21
+ '.turbo', 'vendor', '__pycache__', '.venv', 'venv', 'target', 'out',
22
+ ]);
23
+
24
+ /**
25
+ * Resolve `target` inside `root`.
26
+ *
27
+ * An absolute path is allowed only when it is already inside the root: the chat
28
+ * has no way to ask for a permit, so "outside" is a refusal with the root named,
29
+ * which tells the person where they actually are.
30
+ *
31
+ * @returns {{ path: string } | { refusal: 'outside' | 'missing' | 'empty' }}
32
+ */
33
+ export function resolveInRoot(root, target) {
34
+ const base = String(root || '').trim();
35
+ const asked = String(target || '').trim();
36
+ if (!base) return { refusal: 'empty' };
37
+ const full = isAbsolute(asked) ? resolve(asked) : resolve(base, asked || '.');
38
+ const rel = relative(resolve(base), full);
39
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return { refusal: 'outside' };
40
+ try {
41
+ const info = statSync(full);
42
+ return { path: full, dir: info.isDirectory(), size: info.size };
43
+ } catch {
44
+ return { refusal: 'missing' };
45
+ }
46
+ }
47
+
48
+ /** Does this buffer look like text rather than a picture or an archive? */
49
+ export function looksText(buffer) {
50
+ const head = buffer.subarray(0, 4096);
51
+ for (const byte of head) {
52
+ // NUL is the honest signal: a text file of any encoding has none in its head.
53
+ if (byte === 0) return false;
54
+ }
55
+ return true;
56
+ }
57
+
58
+ /**
59
+ * Read one file through the fence.
60
+ *
61
+ * @returns {{ text: string } | { refusal: 'large' | 'binary' | 'missing' | 'dir' }}
62
+ */
63
+ export function readTextFile(path) {
64
+ try {
65
+ const info = statSync(path);
66
+ if (info.isDirectory()) return { refusal: 'dir' };
67
+ if (info.size > MAX_BYTES) return { refusal: 'large' };
68
+ const buffer = readFileSync(path);
69
+ if (!looksText(buffer)) return { refusal: 'binary' };
70
+ return { text: buffer.toString('utf8') };
71
+ } catch {
72
+ return { refusal: 'missing' };
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Walk a folder, bounded by files, milliseconds and depth.
78
+ *
79
+ * Returns what it reached and whether it stopped early, because a search that
80
+ * silently gives up looks exactly like a search that found nothing — and those
81
+ * are different answers.
82
+ *
83
+ * @returns {{ files: string[], stopped: boolean, skipped: number }}
84
+ */
85
+ export function walkFiles(root, bound = BOUND) {
86
+ const files = [];
87
+ let skipped = 0;
88
+ let stopped = false;
89
+ const started = Date.now();
90
+ const visit = (dir, depth) => {
91
+ if (stopped) return;
92
+ if (depth > bound.depth) {
93
+ stopped = true;
94
+ return;
95
+ }
96
+ let rows = [];
97
+ try {
98
+ rows = readdirSync(dir, { withFileTypes: true });
99
+ } catch {
100
+ skipped += 1;
101
+ return;
102
+ }
103
+ for (const row of rows) {
104
+ if (stopped) return;
105
+ if (files.length >= bound.files || Date.now() - started > bound.ms) {
106
+ stopped = true;
107
+ return;
108
+ }
109
+ const full = resolve(dir, row.name);
110
+ if (row.isDirectory()) {
111
+ if (SKIP_DIRS.has(row.name) || row.name.startsWith('.')) continue;
112
+ visit(full, depth + 1);
113
+ continue;
114
+ }
115
+ if (!row.isFile()) continue;
116
+ files.push(full);
117
+ }
118
+ };
119
+ visit(resolve(root), 0);
120
+ return { files, stopped, skipped };
121
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.39.0",
3
+ "version": "1.40.0",
4
4
  "description": "Drive DeepSeek Harness from Telegram: one project, model and session per forum topic",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
@@ -54,6 +54,7 @@
54
54
  "scan-secrets.mjs",
55
55
  "setup.mjs",
56
56
  "sync-runtime.mjs",
57
+ "lib/",
57
58
  "core/",
58
59
  "model/",
59
60
  "turn/",
package/turn/progress.mjs CHANGED
@@ -13,7 +13,7 @@ import { sessionKey } from '../core/keys.mjs';
13
13
  import { tg } from '../chat/telegram.mjs';
14
14
  import { topicName } from '../chat/topics.mjs';
15
15
  import { t } from '../core/i18n.mjs';
16
- import { addStep, progressPanel, stepLine } from '../chat/panel.mjs';
16
+ import { addStep, isSubagentTool, progressPanel, stepLine, subagentStep } from '../chat/panel.mjs';
17
17
  import { reasoningMode, thoughtRows } from '../chat/notes.mjs';
18
18
  import { cardBlocks } from './card.mjs';
19
19
  import { cardPin } from '../profile/settings-card.mjs';
@@ -55,6 +55,10 @@ export async function startProgress(chatId, threadId, lang = config.lang || 'en'
55
55
  const started = Date.now();
56
56
  const panelKey = sessionKey(chatId, threadId);
57
57
  const steps = [];
58
+ // Subagent calls in flight, by callId, with the index of their step line and
59
+ // the moment they started: the stream says nothing about them except a call
60
+ // and a later result, so the wall clock is the only duration there is.
61
+ const subagents = new Map();
58
62
  const thinkingParts = [];
59
63
  /** Last reported token usage for this turn, for the cache line. */
60
64
  // `totalTokens` is the provider's own sum of the prompt it just sent, which is
@@ -321,10 +325,34 @@ export async function startProgress(chatId, threadId, lang = config.lang || 'en'
321
325
  },
322
326
  handle(event) {
323
327
  if (event.type === 'tool_call') {
324
- addStep(steps, stepLine(event));
328
+ if (isSubagentTool(event.tool)) {
329
+ // The line goes in when the call starts, so a subagent that runs for
330
+ // two minutes is visible as running rather than appearing at the end.
331
+ const input = event.input ?? {};
332
+ const label = String(input.description ?? input.prompt ?? '').replace(/\s+/g, ' ').trim();
333
+ subagents.set(String(event.callId || ''), { index: steps.length, at: Date.now(), tool: event.tool, label });
334
+ steps.push(subagentStep(event));
335
+ } else {
336
+ addStep(steps, stepLine(event));
337
+ }
325
338
  schedule();
326
339
  return;
327
340
  }
341
+ if (event.type === 'tool_result') {
342
+ const waiting = subagents.get(String(event.callId || ''));
343
+ if (waiting) {
344
+ subagents.delete(String(event.callId || ''));
345
+ if (steps[waiting.index] !== undefined) {
346
+ // The label comes from the call; the result adds the one thing it
347
+ // knows and the call did not — how long the subagent actually ran,
348
+ // and whether it failed.
349
+ const done = subagentStep({ tool: waiting.tool, input: { description: waiting.label } }, Date.now() - waiting.at);
350
+ steps[waiting.index] = `${done}${event.status === 'error' ? ' ✖' : ''}`;
351
+ schedule();
352
+ }
353
+ }
354
+ return;
355
+ }
328
356
  // The CLI emits one `thinking` event per committed assistant step, so the
329
357
  // panel grows a paragraph at a time — visible while the turn runs, and
330
358
  // still there, collapsed, when it ends.