@grinev/opencode-telegram-bot 0.15.0 → 0.16.1
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/.env.example +16 -0
- package/README.md +22 -1
- package/dist/app/start-bot-app.js +82 -7
- package/dist/bot/assistant-run-state.js +60 -0
- package/dist/bot/commands/abort.js +2 -0
- package/dist/bot/commands/commands.js +10 -0
- package/dist/bot/commands/definitions.js +1 -0
- package/dist/bot/commands/open.js +314 -0
- package/dist/bot/commands/projects.js +5 -38
- package/dist/bot/commands/start.js +2 -0
- package/dist/bot/handlers/inline-menu.js +9 -1
- package/dist/bot/handlers/prompt.js +11 -0
- package/dist/bot/index.js +187 -100
- package/dist/bot/streaming/response-streamer.js +26 -17
- package/dist/bot/utils/assistant-rendering.js +117 -0
- package/dist/bot/utils/assistant-run-footer.js +9 -0
- package/dist/bot/utils/browser-roots.js +140 -0
- package/dist/bot/utils/file-tree.js +92 -0
- package/dist/bot/utils/finalize-assistant-response.js +18 -24
- package/dist/bot/utils/send-with-markdown-fallback.js +3 -3
- package/dist/bot/utils/switch-project.js +48 -0
- package/dist/bot/utils/telegram-text.js +95 -1
- package/dist/cli/args.js +36 -7
- package/dist/cli.js +133 -15
- package/dist/config.js +4 -0
- package/dist/i18n/de.js +15 -10
- package/dist/i18n/en.js +15 -10
- package/dist/i18n/es.js +15 -10
- package/dist/i18n/fr.js +15 -10
- package/dist/i18n/ru.js +15 -10
- package/dist/i18n/zh.js +15 -10
- package/dist/index.js +2 -0
- package/dist/project/manager.js +2 -1
- package/dist/scheduled-task/runtime.js +8 -0
- package/dist/service/manager.js +244 -0
- package/dist/service/runtime.js +19 -0
- package/dist/service/types.js +1 -0
- package/dist/summary/aggregator.js +17 -1
- package/dist/summary/formatter.js +2 -88
- package/dist/telegram/render/block-fallback.js +28 -0
- package/dist/telegram/render/block-parser.js +295 -0
- package/dist/telegram/render/block-renderer.js +457 -0
- package/dist/telegram/render/chunker.js +281 -0
- package/dist/telegram/render/inline-renderer.js +128 -0
- package/dist/telegram/render/markdown-normalizer.js +94 -0
- package/dist/telegram/render/pipeline.js +9 -0
- package/dist/telegram/render/types.js +1 -0
- package/dist/telegram/render/validator.js +160 -0
- package/dist/utils/logger.js +200 -73
- package/package.json +6 -2
|
@@ -2,16 +2,22 @@ import { logger } from "../../utils/logger.js";
|
|
|
2
2
|
function buildStateKey(sessionId, messageId) {
|
|
3
3
|
return `${sessionId}:${messageId}`;
|
|
4
4
|
}
|
|
5
|
+
function clonePart(part) {
|
|
6
|
+
return {
|
|
7
|
+
text: part.text,
|
|
8
|
+
entities: part.entities ? [...part.entities] : undefined,
|
|
9
|
+
fallbackText: part.fallbackText,
|
|
10
|
+
source: part.source,
|
|
11
|
+
};
|
|
12
|
+
}
|
|
5
13
|
function normalizePayload(payload) {
|
|
6
|
-
const normalizedParts = payload.parts
|
|
7
|
-
.map((part) => part.trim())
|
|
8
|
-
.filter((part) => part.length > 0);
|
|
14
|
+
const normalizedParts = payload.parts.map(clonePart).filter((part) => part.text.length > 0);
|
|
9
15
|
if (normalizedParts.length === 0) {
|
|
16
|
+
logger.debug("[ResponseStreamer] Dropped empty streaming payload after normalization");
|
|
10
17
|
return null;
|
|
11
18
|
}
|
|
12
19
|
return {
|
|
13
20
|
parts: normalizedParts,
|
|
14
|
-
format: payload.format,
|
|
15
21
|
sendOptions: payload.sendOptions,
|
|
16
22
|
editOptions: payload.editOptions,
|
|
17
23
|
};
|
|
@@ -37,8 +43,8 @@ function getRetryAfterMs(error) {
|
|
|
37
43
|
}
|
|
38
44
|
return seconds * 1000;
|
|
39
45
|
}
|
|
40
|
-
function createSignature(
|
|
41
|
-
return `${
|
|
46
|
+
function createSignature(part) {
|
|
47
|
+
return `${part.text}\n${JSON.stringify(part.entities ?? null)}`;
|
|
42
48
|
}
|
|
43
49
|
function delay(ms) {
|
|
44
50
|
return new Promise((resolve) => {
|
|
@@ -47,14 +53,14 @@ function delay(ms) {
|
|
|
47
53
|
}
|
|
48
54
|
export class ResponseStreamer {
|
|
49
55
|
throttleMs;
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
sendPart;
|
|
57
|
+
editPart;
|
|
52
58
|
deleteText;
|
|
53
59
|
states = new Map();
|
|
54
60
|
constructor(options) {
|
|
55
61
|
this.throttleMs = Math.max(0, Math.floor(options.throttleMs));
|
|
56
|
-
this.
|
|
57
|
-
this.
|
|
62
|
+
this.sendPart = options.sendPart;
|
|
63
|
+
this.editPart = options.editPart;
|
|
58
64
|
this.deleteText = options.deleteText;
|
|
59
65
|
}
|
|
60
66
|
enqueue(sessionId, messageId, payload) {
|
|
@@ -73,6 +79,7 @@ export class ResponseStreamer {
|
|
|
73
79
|
const notStreamed = { streamed: false, telegramMessageIds: [] };
|
|
74
80
|
const state = this.states.get(buildStateKey(sessionId, messageId));
|
|
75
81
|
if (!state) {
|
|
82
|
+
logger.debug(`[ResponseStreamer] Complete skipped, no active stream state: session=${sessionId}, message=${messageId}`);
|
|
76
83
|
return notStreamed;
|
|
77
84
|
}
|
|
78
85
|
if (payload) {
|
|
@@ -90,6 +97,7 @@ export class ResponseStreamer {
|
|
|
90
97
|
return notStreamed;
|
|
91
98
|
}
|
|
92
99
|
if (state.telegramMessageIds.length === 0) {
|
|
100
|
+
logger.debug(`[ResponseStreamer] Complete returned not streamed: session=${sessionId}, message=${messageId}, reason=no_visible_partials`);
|
|
93
101
|
this.cancelState(state);
|
|
94
102
|
this.states.delete(state.key);
|
|
95
103
|
return notStreamed;
|
|
@@ -204,10 +212,11 @@ export class ResponseStreamer {
|
|
|
204
212
|
if (!payload) {
|
|
205
213
|
return state.telegramMessageIds.length > 0;
|
|
206
214
|
}
|
|
207
|
-
const targetSignatures = payload.parts.map((part) => createSignature(part
|
|
215
|
+
const targetSignatures = payload.parts.map((part) => createSignature(part));
|
|
208
216
|
const unchanged = targetSignatures.length === state.lastSentSignatures.length &&
|
|
209
217
|
targetSignatures.every((signature, index) => signature === state.lastSentSignatures[index]);
|
|
210
218
|
if (unchanged) {
|
|
219
|
+
logger.debug(`[ResponseStreamer] Skipped unchanged payload: session=${state.sessionId}, message=${state.messageId}, parts=${payload.parts.length}`);
|
|
211
220
|
return state.telegramMessageIds.length > 0;
|
|
212
221
|
}
|
|
213
222
|
try {
|
|
@@ -259,20 +268,20 @@ export class ResponseStreamer {
|
|
|
259
268
|
}
|
|
260
269
|
async syncMessages(state, payload, targetSignatures) {
|
|
261
270
|
for (let index = 0; index < payload.parts.length; index++) {
|
|
262
|
-
const
|
|
271
|
+
const part = payload.parts[index];
|
|
263
272
|
const nextSignature = targetSignatures[index];
|
|
264
273
|
const currentMessageId = state.telegramMessageIds[index];
|
|
265
274
|
if (currentMessageId) {
|
|
266
275
|
if (state.lastSentSignatures[index] === nextSignature) {
|
|
267
276
|
continue;
|
|
268
277
|
}
|
|
269
|
-
await this.
|
|
270
|
-
state.lastSentSignatures[index] =
|
|
278
|
+
const result = await this.editPart(currentMessageId, part, payload.editOptions);
|
|
279
|
+
state.lastSentSignatures[index] = result.deliveredSignature;
|
|
271
280
|
continue;
|
|
272
281
|
}
|
|
273
|
-
const
|
|
274
|
-
state.telegramMessageIds[index] = messageId;
|
|
275
|
-
state.lastSentSignatures[index] =
|
|
282
|
+
const result = await this.sendPart(part, payload.sendOptions);
|
|
283
|
+
state.telegramMessageIds[index] = result.messageId;
|
|
284
|
+
state.lastSentSignatures[index] = result.deliveredSignature;
|
|
276
285
|
}
|
|
277
286
|
for (let index = state.telegramMessageIds.length - 1; index >= payload.parts.length; index--) {
|
|
278
287
|
const messageId = state.telegramMessageIds[index];
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { config } from "../../config.js";
|
|
2
|
+
import { logger } from "../../utils/logger.js";
|
|
3
|
+
import { chunkTelegramRenderedBlocks } from "../../telegram/render/chunker.js";
|
|
4
|
+
import { renderTelegramBlocks, renderTelegramParts } from "../../telegram/render/pipeline.js";
|
|
5
|
+
export function createPlainRenderedBlock(text) {
|
|
6
|
+
return {
|
|
7
|
+
blockType: "plain",
|
|
8
|
+
mode: "plain",
|
|
9
|
+
text,
|
|
10
|
+
fallbackText: text,
|
|
11
|
+
source: "plain",
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function createPlainRenderedParts(text, maxPartLength) {
|
|
15
|
+
return chunkTelegramRenderedBlocks([createPlainRenderedBlock(text)], { maxPartLength });
|
|
16
|
+
}
|
|
17
|
+
function useAssistantEntitiesFormat() {
|
|
18
|
+
return config.bot.messageFormatMode === "markdown";
|
|
19
|
+
}
|
|
20
|
+
function renderAssistantBlocksSafe(text) {
|
|
21
|
+
if (!text) {
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
return renderTelegramBlocks(text);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
logger.warn("[AssistantRender] Block rendering failed, falling back to plain streaming block", error);
|
|
29
|
+
return [createPlainRenderedBlock(text)];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function renderAssistantFinalPartsSafe(text, maxPartLength = 4096) {
|
|
33
|
+
if (!text) {
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
const formatMode = useAssistantEntitiesFormat() ? "entities" : "raw";
|
|
37
|
+
if (!useAssistantEntitiesFormat()) {
|
|
38
|
+
const parts = createPlainRenderedParts(text, maxPartLength);
|
|
39
|
+
logger.debug("[AssistantRender] Built final assistant parts in raw mode", {
|
|
40
|
+
formatMode,
|
|
41
|
+
textLength: text.length,
|
|
42
|
+
partCount: parts.length,
|
|
43
|
+
});
|
|
44
|
+
return parts;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const parts = renderTelegramParts(text, { maxPartLength });
|
|
48
|
+
logger.debug("[AssistantRender] Built final assistant parts in entities mode", {
|
|
49
|
+
formatMode,
|
|
50
|
+
textLength: text.length,
|
|
51
|
+
partCount: parts.length,
|
|
52
|
+
richParts: parts.filter((part) => part.source === "entities").length,
|
|
53
|
+
plainParts: parts.filter((part) => part.source === "plain").length,
|
|
54
|
+
});
|
|
55
|
+
return parts;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
logger.warn("[AssistantRender] Part rendering failed, falling back to plain text parts", error);
|
|
59
|
+
const parts = createPlainRenderedParts(text, maxPartLength);
|
|
60
|
+
logger.debug("[AssistantRender] Built final assistant parts in raw fallback mode", {
|
|
61
|
+
formatMode,
|
|
62
|
+
textLength: text.length,
|
|
63
|
+
partCount: parts.length,
|
|
64
|
+
});
|
|
65
|
+
return parts;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function getStableStreamingBoundary(messageText) {
|
|
69
|
+
if (!messageText) {
|
|
70
|
+
return 0;
|
|
71
|
+
}
|
|
72
|
+
if (messageText.endsWith("\n\n")) {
|
|
73
|
+
return messageText.length;
|
|
74
|
+
}
|
|
75
|
+
const lastBlockSeparatorIndex = messageText.lastIndexOf("\n\n");
|
|
76
|
+
return lastBlockSeparatorIndex >= 0 ? lastBlockSeparatorIndex + 2 : 0;
|
|
77
|
+
}
|
|
78
|
+
export function prepareAssistantStreamingPayload(messageText, maxPartLength) {
|
|
79
|
+
if (!messageText) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
const formatMode = useAssistantEntitiesFormat() ? "entities" : "raw";
|
|
83
|
+
if (!useAssistantEntitiesFormat()) {
|
|
84
|
+
const parts = createPlainRenderedParts(messageText, maxPartLength);
|
|
85
|
+
logger.debug("[AssistantRender] Built streaming assistant payload in raw mode", {
|
|
86
|
+
formatMode,
|
|
87
|
+
textLength: messageText.length,
|
|
88
|
+
partCount: parts.length,
|
|
89
|
+
});
|
|
90
|
+
return parts.length > 0 ? { parts } : null;
|
|
91
|
+
}
|
|
92
|
+
const stableBoundary = getStableStreamingBoundary(messageText);
|
|
93
|
+
const blocks = [];
|
|
94
|
+
if (stableBoundary > 0) {
|
|
95
|
+
blocks.push(...renderAssistantBlocksSafe(messageText.slice(0, stableBoundary)));
|
|
96
|
+
}
|
|
97
|
+
const unstableTail = stableBoundary > 0 ? messageText.slice(stableBoundary) : messageText;
|
|
98
|
+
if (unstableTail) {
|
|
99
|
+
blocks.push(createPlainRenderedBlock(unstableTail));
|
|
100
|
+
}
|
|
101
|
+
const parts = chunkTelegramRenderedBlocks(blocks, { maxPartLength });
|
|
102
|
+
logger.debug("[AssistantRender] Built streaming assistant payload in entities mode", {
|
|
103
|
+
formatMode,
|
|
104
|
+
textLength: messageText.length,
|
|
105
|
+
stableBoundary,
|
|
106
|
+
tailLength: unstableTail.length,
|
|
107
|
+
blockCount: blocks.length,
|
|
108
|
+
partCount: parts.length,
|
|
109
|
+
richParts: parts.filter((part) => part.source === "entities").length,
|
|
110
|
+
plainParts: parts.filter((part) => part.source === "plain").length,
|
|
111
|
+
});
|
|
112
|
+
return parts.length > 0 ? { parts } : null;
|
|
113
|
+
}
|
|
114
|
+
export function prepareAssistantFinalStreamingPayload(messageText, maxPartLength) {
|
|
115
|
+
const parts = renderAssistantFinalPartsSafe(messageText, maxPartLength);
|
|
116
|
+
return parts.length > 0 ? { parts } : null;
|
|
117
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { getAgentDisplayName } from "../../agent/types.js";
|
|
2
|
+
function formatElapsedSeconds(elapsedMs) {
|
|
3
|
+
const safeElapsedMs = Math.max(0, elapsedMs);
|
|
4
|
+
return `${(safeElapsedMs / 1000).toFixed(1)}s`;
|
|
5
|
+
}
|
|
6
|
+
export function formatAssistantRunFooter({ agent, providerID, modelID, elapsedMs, }) {
|
|
7
|
+
const agentDisplay = getAgentDisplayName(agent);
|
|
8
|
+
return `${agentDisplay} · 🤖 ${providerID}/${modelID} · 🕒 ${formatElapsedSeconds(elapsedMs)}`;
|
|
9
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { realpath } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { logger } from "../../utils/logger.js";
|
|
5
|
+
/**
|
|
6
|
+
* Allowed root directories for the `/open` command.
|
|
7
|
+
*
|
|
8
|
+
* Configured via `OPEN_BROWSER_ROOTS` env var (comma-separated absolute paths).
|
|
9
|
+
* Defaults to `[os.homedir()]` when the variable is not set.
|
|
10
|
+
*
|
|
11
|
+
* All navigation in the directory browser is restricted to stay within one
|
|
12
|
+
* of the configured roots. This prevents the bot from browsing arbitrary
|
|
13
|
+
* locations on the filesystem.
|
|
14
|
+
*/
|
|
15
|
+
let resolvedRoots = null;
|
|
16
|
+
function isWindows() {
|
|
17
|
+
return process.platform === "win32";
|
|
18
|
+
}
|
|
19
|
+
function resolveConfiguredPath(p) {
|
|
20
|
+
return path.resolve(expandTilde(p));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Expand a leading `~` or `~/` to the user's home directory.
|
|
24
|
+
* Does not handle `~user/` syntax — only the current user's home.
|
|
25
|
+
*/
|
|
26
|
+
function expandTilde(p) {
|
|
27
|
+
if (p === "~") {
|
|
28
|
+
return os.homedir();
|
|
29
|
+
}
|
|
30
|
+
if (p.startsWith("~/") || p.startsWith("~\\")) {
|
|
31
|
+
return path.join(os.homedir(), p.slice(2));
|
|
32
|
+
}
|
|
33
|
+
return p;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Normalize a path for comparison: expand tilde, resolve, then lowercase on Windows.
|
|
37
|
+
*/
|
|
38
|
+
function normalizePath(p) {
|
|
39
|
+
const resolved = resolveConfiguredPath(p);
|
|
40
|
+
return isWindows() ? resolved.toLowerCase() : resolved;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Initialize (or re-initialize) the allowed browser roots from the raw
|
|
44
|
+
* env string. Each entry is resolved to an absolute path via `path.resolve`.
|
|
45
|
+
*
|
|
46
|
+
* Entries that cannot be resolved are logged and skipped.
|
|
47
|
+
*/
|
|
48
|
+
export function initBrowserRoots(raw) {
|
|
49
|
+
if (!raw || raw.trim() === "") {
|
|
50
|
+
resolvedRoots = [resolveConfiguredPath(os.homedir())];
|
|
51
|
+
logger.debug(`[BrowserRoots] No OPEN_BROWSER_ROOTS configured, defaulting to home: ${resolvedRoots[0]}`);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const entries = raw
|
|
55
|
+
.split(",")
|
|
56
|
+
.map((s) => s.trim())
|
|
57
|
+
.filter((s) => s.length > 0);
|
|
58
|
+
const roots = [];
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
roots.push(resolveConfiguredPath(entry));
|
|
61
|
+
}
|
|
62
|
+
if (roots.length === 0) {
|
|
63
|
+
resolvedRoots = [resolveConfiguredPath(os.homedir())];
|
|
64
|
+
logger.warn("[BrowserRoots] All configured roots were invalid, falling back to home directory");
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
resolvedRoots = roots;
|
|
68
|
+
logger.info(`[BrowserRoots] Configured roots: ${roots.join(", ")}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Return the configured browser roots. Lazily initializes from env if
|
|
73
|
+
* `initBrowserRoots` was never called.
|
|
74
|
+
*/
|
|
75
|
+
export function getBrowserRoots() {
|
|
76
|
+
if (resolvedRoots === null) {
|
|
77
|
+
initBrowserRoots(process.env.OPEN_BROWSER_ROOTS);
|
|
78
|
+
}
|
|
79
|
+
return resolvedRoots;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Return the original (non-normalized) root paths for display/navigation.
|
|
83
|
+
* On Windows the display roots are lowercased because `normalizePath` is
|
|
84
|
+
* used during init — this is acceptable for button labels.
|
|
85
|
+
*/
|
|
86
|
+
export function getBrowserRootPaths() {
|
|
87
|
+
return getBrowserRoots();
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Check whether a target path is inside one of the allowed roots.
|
|
91
|
+
*
|
|
92
|
+
* Uses `path.resolve` on the target for consistent comparison, then
|
|
93
|
+
* checks that the target equals a root or is a descendant (starts with
|
|
94
|
+
* root + separator).
|
|
95
|
+
*
|
|
96
|
+
* For full symlink-proof validation, callers can optionally resolve the
|
|
97
|
+
* target with `fs.realpath` before calling this function.
|
|
98
|
+
*/
|
|
99
|
+
export function isWithinAllowedRoot(targetPath) {
|
|
100
|
+
const normalizedTarget = normalizePath(targetPath);
|
|
101
|
+
const roots = getBrowserRoots();
|
|
102
|
+
for (const root of roots) {
|
|
103
|
+
const normalizedRoot = normalizePath(root);
|
|
104
|
+
if (normalizedTarget === normalizedRoot) {
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
// Check both separators — `path.sep` is always `/` on Unix but a
|
|
108
|
+
// lowercased Windows path may contain either `\` or `/`.
|
|
109
|
+
if (normalizedTarget.startsWith(normalizedRoot + "/") ||
|
|
110
|
+
normalizedTarget.startsWith(normalizedRoot + "\\")) {
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Like `isWithinAllowedRoot` but resolves symlinks first using `realpath`.
|
|
118
|
+
* Falls back to the plain path if `realpath` fails (e.g. ENOENT).
|
|
119
|
+
*/
|
|
120
|
+
export async function isWithinAllowedRootSafe(targetPath) {
|
|
121
|
+
let resolved = targetPath;
|
|
122
|
+
try {
|
|
123
|
+
resolved = await realpath(targetPath);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// Path doesn't exist yet or can't be resolved — use as-is
|
|
127
|
+
}
|
|
128
|
+
return isWithinAllowedRoot(resolved);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Check whether a path is exactly one of the allowed roots (not a descendant).
|
|
132
|
+
*/
|
|
133
|
+
export function isAllowedRoot(targetPath) {
|
|
134
|
+
const normalizedTarget = normalizePath(targetPath);
|
|
135
|
+
return getBrowserRoots().some((root) => normalizePath(root) === normalizedTarget);
|
|
136
|
+
}
|
|
137
|
+
/** Reset state — for testing only. */
|
|
138
|
+
export function __resetBrowserRootsForTests() {
|
|
139
|
+
resolvedRoots = null;
|
|
140
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { t } from "../../i18n/index.js";
|
|
5
|
+
export const MAX_ENTRIES_PER_PAGE = 8;
|
|
6
|
+
export function getHomeDirectory() {
|
|
7
|
+
return os.homedir();
|
|
8
|
+
}
|
|
9
|
+
export function pathToDisplayPath(absolutePath) {
|
|
10
|
+
const home = getHomeDirectory();
|
|
11
|
+
if (absolutePath === home) {
|
|
12
|
+
return "~";
|
|
13
|
+
}
|
|
14
|
+
if (absolutePath.startsWith(home + path.sep)) {
|
|
15
|
+
return "~" + absolutePath.slice(home.length);
|
|
16
|
+
}
|
|
17
|
+
return absolutePath;
|
|
18
|
+
}
|
|
19
|
+
export async function scanDirectory(dirPath, page = 0) {
|
|
20
|
+
try {
|
|
21
|
+
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
|
22
|
+
const subdirs = [];
|
|
23
|
+
for (const entry of entries) {
|
|
24
|
+
if (entry.isDirectory() && !entry.name.startsWith(".")) {
|
|
25
|
+
subdirs.push({
|
|
26
|
+
name: entry.name,
|
|
27
|
+
fullPath: path.join(dirPath, entry.name),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
subdirs.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
|
|
32
|
+
const parentPath = path.dirname(dirPath);
|
|
33
|
+
const hasParent = dirPath !== path.parse(dirPath).root;
|
|
34
|
+
// Clamp page to valid range so stale or crafted callbacks never produce
|
|
35
|
+
// an out-of-bounds page indicator like "(4/2)".
|
|
36
|
+
const totalPages = Math.max(1, Math.ceil(subdirs.length / MAX_ENTRIES_PER_PAGE));
|
|
37
|
+
const safePage = Math.max(0, Math.min(page, totalPages - 1));
|
|
38
|
+
const start = safePage * MAX_ENTRIES_PER_PAGE;
|
|
39
|
+
const pageEntries = subdirs.slice(start, start + MAX_ENTRIES_PER_PAGE);
|
|
40
|
+
return {
|
|
41
|
+
entries: pageEntries,
|
|
42
|
+
totalCount: subdirs.length,
|
|
43
|
+
page: safePage,
|
|
44
|
+
currentPath: dirPath,
|
|
45
|
+
displayPath: pathToDisplayPath(dirPath),
|
|
46
|
+
hasParent,
|
|
47
|
+
parentPath: hasParent ? parentPath : null,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error instanceof Error) {
|
|
52
|
+
if ("code" in error) {
|
|
53
|
+
const code = error.code;
|
|
54
|
+
if (code === "ENOENT" || code === "ELOOP") {
|
|
55
|
+
return { error: `Directory not found: ${dirPath}`, code: "ENOENT" };
|
|
56
|
+
}
|
|
57
|
+
if (code === "EACCES" || code === "EPERM") {
|
|
58
|
+
return { error: `Permission denied: ${dirPath}`, code: "EACCES" };
|
|
59
|
+
}
|
|
60
|
+
if (code === "ENOTDIR") {
|
|
61
|
+
return { error: `Not a directory: ${dirPath}`, code: "ENOTDIR" };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
67
|
+
code: "UNKNOWN",
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export function buildEntryLabel(entry) {
|
|
72
|
+
return `📁 ${entry.name}`;
|
|
73
|
+
}
|
|
74
|
+
export function buildTreeHeader(displayPath, totalCount, page, totalPages) {
|
|
75
|
+
let header = `📂 ${displayPath}`;
|
|
76
|
+
if (totalPages > 1) {
|
|
77
|
+
header += ` (${page + 1}/${totalPages})`;
|
|
78
|
+
}
|
|
79
|
+
if (totalCount === 0) {
|
|
80
|
+
header += `\n${t("open.no_subfolders")}`;
|
|
81
|
+
}
|
|
82
|
+
else if (totalCount === 1) {
|
|
83
|
+
header += `\n${t("open.subfolder_count", { count: String(totalCount) })}`;
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
header += `\n${t("open.subfolders_count", { count: String(totalCount) })}`;
|
|
87
|
+
}
|
|
88
|
+
return header;
|
|
89
|
+
}
|
|
90
|
+
export function isScanError(result) {
|
|
91
|
+
return "error" in result;
|
|
92
|
+
}
|
|
@@ -1,35 +1,29 @@
|
|
|
1
1
|
import { logger } from "../../utils/logger.js";
|
|
2
|
-
export async function finalizeAssistantResponse({ sessionId, messageId, messageText, responseStreamer, flushPendingServiceMessages, prepareStreamingPayload,
|
|
3
|
-
|
|
2
|
+
export async function finalizeAssistantResponse({ sessionId, messageId, messageText, responseStreamer, flushPendingServiceMessages, prepareStreamingPayload, renderFinalParts, getReplyKeyboard, sendRenderedPart, }) {
|
|
3
|
+
logger.debug(`[FinalizeResponse] Final assistant raw text received: session=${sessionId}, message=${messageId}`, messageText);
|
|
4
|
+
const keyboard = getReplyKeyboard();
|
|
5
|
+
const replyOptions = keyboard ? { reply_markup: keyboard } : undefined;
|
|
6
|
+
const silentReplyOptions = {
|
|
7
|
+
disable_notification: true,
|
|
8
|
+
...(replyOptions ?? {}),
|
|
9
|
+
};
|
|
10
|
+
const streamSendOptions = {
|
|
11
|
+
...silentReplyOptions,
|
|
12
|
+
};
|
|
4
13
|
const preparedStreamPayload = prepareStreamingPayload(messageText);
|
|
5
14
|
if (preparedStreamPayload) {
|
|
6
|
-
preparedStreamPayload.sendOptions =
|
|
15
|
+
preparedStreamPayload.sendOptions = streamSendOptions;
|
|
7
16
|
preparedStreamPayload.editOptions = undefined;
|
|
8
17
|
}
|
|
9
18
|
const result = await responseStreamer.complete(sessionId, messageId, preparedStreamPayload ?? undefined);
|
|
10
|
-
if (result.streamed) {
|
|
11
|
-
streamedMessageIds = result.telegramMessageIds;
|
|
12
|
-
}
|
|
13
19
|
await flushPendingServiceMessages();
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
try {
|
|
18
|
-
await deleteMessages(streamedMessageIds);
|
|
19
|
-
}
|
|
20
|
-
catch (err) {
|
|
21
|
-
logger.warn("[FinalizeResponse] Failed to delete streamed messages, sending with keyboard anyway:", err);
|
|
22
|
-
}
|
|
20
|
+
if (result.streamed) {
|
|
21
|
+
logger.debug(`[FinalizeResponse] Finalized streamed assistant message in place: session=${sessionId}, message=${messageId}, telegramMessages=${result.telegramMessageIds.length}`);
|
|
22
|
+
return true;
|
|
23
23
|
}
|
|
24
|
-
const parts =
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
for (let partIndex = 0; partIndex < parts.length; partIndex++) {
|
|
28
|
-
const part = parts[partIndex];
|
|
29
|
-
const rawFallbackText = rawParts[partIndex];
|
|
30
|
-
const keyboard = getReplyKeyboard();
|
|
31
|
-
const options = keyboard ? { reply_markup: keyboard } : undefined;
|
|
32
|
-
await sendText(part, rawFallbackText, options, format);
|
|
24
|
+
const parts = renderFinalParts(messageText);
|
|
25
|
+
for (const part of parts) {
|
|
26
|
+
await sendRenderedPart(part, silentReplyOptions);
|
|
33
27
|
}
|
|
34
28
|
return false;
|
|
35
29
|
}
|
|
@@ -110,7 +110,7 @@ export async function sendMessageWithMarkdownFallback({ api, chatId, text, rawFa
|
|
|
110
110
|
if (parseMode === "MarkdownV2") {
|
|
111
111
|
const escapedText = escapeTelegramMarkdownV2(text);
|
|
112
112
|
if (escapedText !== text) {
|
|
113
|
-
logger.warn("[Bot] Markdown parse failed, retrying
|
|
113
|
+
logger.warn("[Bot] Markdown parse failed, retrying message with escaped MarkdownV2", error);
|
|
114
114
|
try {
|
|
115
115
|
return await api.sendMessage(chatId, escapedText, markdownOptions);
|
|
116
116
|
}
|
|
@@ -118,12 +118,12 @@ export async function sendMessageWithMarkdownFallback({ api, chatId, text, rawFa
|
|
|
118
118
|
if (!isTelegramMarkdownParseError(escapedError)) {
|
|
119
119
|
throw escapedError;
|
|
120
120
|
}
|
|
121
|
-
logger.warn("[Bot] Escaped Markdown parse failed, retrying
|
|
121
|
+
logger.warn("[Bot] Escaped Markdown parse failed, retrying message in raw mode", escapedError);
|
|
122
122
|
return api.sendMessage(chatId, fallbackText, stripMarkdownFormattingOptions(options));
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
125
|
}
|
|
126
|
-
logger.warn("[Bot] Markdown parse failed, retrying
|
|
126
|
+
logger.warn("[Bot] Markdown parse failed, retrying message in raw mode", error);
|
|
127
127
|
return api.sendMessage(chatId, fallbackText, stripMarkdownFormattingOptions(options));
|
|
128
128
|
}
|
|
129
129
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { setCurrentProject } from "../../settings/manager.js";
|
|
2
|
+
import { clearSession } from "../../session/manager.js";
|
|
3
|
+
import { summaryAggregator } from "../../summary/aggregator.js";
|
|
4
|
+
import { pinnedMessageManager } from "../../pinned/manager.js";
|
|
5
|
+
import { keyboardManager } from "../../keyboard/manager.js";
|
|
6
|
+
import { getStoredAgent, resolveProjectAgent } from "../../agent/manager.js";
|
|
7
|
+
import { getStoredModel } from "../../model/manager.js";
|
|
8
|
+
import { formatVariantForButton } from "../../variant/manager.js";
|
|
9
|
+
import { clearAllInteractionState } from "../../interaction/cleanup.js";
|
|
10
|
+
import { createMainKeyboard } from "./keyboard.js";
|
|
11
|
+
import { logger } from "../../utils/logger.js";
|
|
12
|
+
/**
|
|
13
|
+
* Shared logic for switching the active project.
|
|
14
|
+
*
|
|
15
|
+
* Called by both `/projects` (selecting an existing project) and `/open`
|
|
16
|
+
* (browsing and adding a new directory). Performs the full state transition:
|
|
17
|
+
* persists the project, clears the session, resets the pinned message and
|
|
18
|
+
* keyboard, and returns a fresh reply keyboard for the caller to attach to
|
|
19
|
+
* its confirmation message.
|
|
20
|
+
*
|
|
21
|
+
* @param ctx grammY callback context (used for `ctx.chat` / `ctx.api`)
|
|
22
|
+
* @param project the project to switch to
|
|
23
|
+
* @param reason short tag for `clearAllInteractionState` (e.g. "project_switched")
|
|
24
|
+
*/
|
|
25
|
+
export async function switchToProject(ctx, project, reason) {
|
|
26
|
+
setCurrentProject(project);
|
|
27
|
+
clearSession();
|
|
28
|
+
summaryAggregator.clear();
|
|
29
|
+
clearAllInteractionState(reason);
|
|
30
|
+
try {
|
|
31
|
+
await pinnedMessageManager.clear();
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
logger.error("[Bot] Error clearing pinned message:", err);
|
|
35
|
+
}
|
|
36
|
+
if (ctx.chat) {
|
|
37
|
+
keyboardManager.initialize(ctx.api, ctx.chat.id);
|
|
38
|
+
}
|
|
39
|
+
await pinnedMessageManager.refreshContextLimit();
|
|
40
|
+
const contextLimit = pinnedMessageManager.getContextLimit();
|
|
41
|
+
keyboardManager.updateContext(0, contextLimit);
|
|
42
|
+
const currentAgent = await resolveProjectAgent(getStoredAgent());
|
|
43
|
+
const currentModel = getStoredModel();
|
|
44
|
+
const contextInfo = { tokensUsed: 0, tokensLimit: contextLimit };
|
|
45
|
+
const variantName = formatVariantForButton(currentModel.variant || "default");
|
|
46
|
+
keyboardManager.updateAgent(currentAgent);
|
|
47
|
+
return createMainKeyboard(currentAgent, currentModel, contextInfo, variantName);
|
|
48
|
+
}
|