telecoder 0.0.0-stage → 1.2.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/.env.example +363 -0
- package/CHANGELOG.md +1186 -0
- package/LICENSE +22 -0
- package/README.md +126 -2
- package/dist/audio/transcribe.js +50 -0
- package/dist/bin/mcp-server.js +378 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +592 -0
- package/dist/bot/file-access.js +141 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +827 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/btw.js +224 -0
- package/dist/bot/handlers/command/cost.js +409 -0
- package/dist/bot/handlers/command/media.js +197 -0
- package/dist/bot/handlers/command/model.js +305 -0
- package/dist/bot/handlers/command/prefs-scope.js +197 -0
- package/dist/bot/handlers/command/project.js +536 -0
- package/dist/bot/handlers/command/resume.js +321 -0
- package/dist/bot/handlers/command/session.js +438 -0
- package/dist/bot/handlers/command/settings.js +1012 -0
- package/dist/bot/handlers/command/shared.js +210 -0
- package/dist/bot/handlers/command/streaming-mode.js +16 -0
- package/dist/bot/handlers/command/tasks.js +513 -0
- package/dist/bot/handlers/command/topic-store.js +113 -0
- package/dist/bot/handlers/command/topic.js +80 -0
- package/dist/bot/handlers/command.handler.js +772 -0
- package/dist/bot/handlers/fork.handler.js +1109 -0
- package/dist/bot/handlers/media-fallback.js +121 -0
- package/dist/bot/handlers/message/replies.js +133 -0
- package/dist/bot/handlers/message/shared.js +117 -0
- package/dist/bot/handlers/message/throttle.js +49 -0
- package/dist/bot/handlers/message/turn-notify.js +169 -0
- package/dist/bot/handlers/message/turn-runner.js +141 -0
- package/dist/bot/handlers/message.handler.js +107 -0
- package/dist/bot/handlers/newbot.handler.js +221 -0
- package/dist/bot/handlers/photo.handler.js +327 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/schedule.handler.js +303 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +209 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +139 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +971 -0
- package/dist/bot/middleware/stale-filter.js +31 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/agent-watchdog.js +162 -0
- package/dist/claude/agent.js +1458 -0
- package/dist/claude/ask-user.js +295 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +126 -0
- package/dist/claude/available-commands.js +153 -0
- package/dist/claude/carry-over.js +27 -0
- package/dist/claude/ccr-shim.js +46 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +121 -0
- package/dist/claude/command-parser.js +200 -0
- package/dist/claude/cost-overlay-scraper.js +129 -0
- package/dist/claude/enabled-plugins.js +56 -0
- package/dist/claude/fork-tree.js +393 -0
- package/dist/claude/held-query.js +190 -0
- package/dist/claude/in-flight-tracker.js +61 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +453 -0
- package/dist/claude/mcp-tools.js +354 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +450 -0
- package/dist/claude/model-catalog.js +85 -0
- package/dist/claude/monitor-relay.js +597 -0
- package/dist/claude/pending-forks.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +337 -0
- package/dist/claude/permission-mode.js +178 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-provider.js +2214 -0
- package/dist/claude/pty-spawn-config.js +296 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/request-queue.js +135 -0
- package/dist/claude/scheduled-runner.js +91 -0
- package/dist/claude/scheduler.js +237 -0
- package/dist/claude/scope-guard.js +274 -0
- package/dist/claude/sdk-permission-gate.js +77 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-cost.js +41 -0
- package/dist/claude/session-history.js +286 -0
- package/dist/claude/session-jsonl.js +920 -0
- package/dist/claude/session-manager.js +195 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +249 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/system-prompt.js +162 -0
- package/dist/claude/tasks-overlay-scraper.js +94 -0
- package/dist/claude/tip-scraper.js +78 -0
- package/dist/claude/tui-modal.js +501 -0
- package/dist/claude/tui-state.js +384 -0
- package/dist/claude/turn-end.js +91 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +305 -0
- package/dist/cli/commands/help.js +25 -0
- package/dist/cli/commands/init.js +123 -0
- package/dist/cli/commands/service.js +678 -0
- package/dist/cli/commands/start.js +53 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/dispatch.js +79 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +638 -0
- package/dist/cli/init/prompter.js +116 -0
- package/dist/cli/init/telegram.js +94 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +500 -0
- package/dist/index.js +367 -0
- package/dist/launcher.js +933 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +149 -0
- package/dist/providers/ccr-provider.js +60 -0
- package/dist/providers/claude-provider.js +63 -0
- package/dist/providers/prefs-sync.js +164 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +127 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/sdk-provider.js +37 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +214 -0
- package/dist/restart-when-idle.js +153 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +173 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +684 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +336 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +27 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +57 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1287 -0
- package/dist/telegram/prompt-label.js +142 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +105 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +209 -0
- package/dist/telegram/telegraph-settings.js +31 -0
- package/dist/telegram/telegraph.js +453 -0
- package/dist/telegram/terminal-renderer.js +671 -0
- package/dist/telegram/terminal-settings.js +25 -0
- package/dist/telegram/thread-titles.js +190 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/tts/tts-settings.js +62 -0
- package/dist/tts/tts.js +245 -0
- package/dist/tts/voice-reply.js +78 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-token.js +74 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +50 -0
- package/dist/utils/claude-env.js +54 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/debug-agent.js +117 -0
- package/dist/utils/debug-watchdog.js +121 -0
- package/dist/utils/download.js +111 -0
- package/dist/utils/exit-codes.js +48 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +81 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/project-data-dir.js +33 -0
- package/dist/utils/reasoning-summary.js +12 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +63 -0
- package/dist/utils/respawn-backoff.js +19 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +76 -4
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/autoapprove` — open, inspect and close a chat's auto-approve window.
|
|
3
|
+
*
|
|
4
|
+
* The command is deliberately small. Everything about what a window *means*
|
|
5
|
+
* lives in src/claude/auto-approve.ts; this file is the part a person types at,
|
|
6
|
+
* and its job is to make two things impossible to get wrong: how long the
|
|
7
|
+
* window lasts, and what it does not cover. Both are stated when it opens,
|
|
8
|
+
* because that is the only moment someone is definitely reading.
|
|
9
|
+
*/
|
|
10
|
+
import { closeWindow, formatDuration, formatRemaining, getWindow, listAlwaysPrompted, openWindow, parseWindowDuration, } from '../../../claude/auto-approve.js';
|
|
11
|
+
import { isPermissionGateEnabled } from '../../../claude/permission-gate.js';
|
|
12
|
+
import { isAdmin } from '../../../utils/admins.js';
|
|
13
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
14
|
+
import { replyFormatted } from '../../../telegram/send.js';
|
|
15
|
+
/** How the announcement names whoever opened the window. */
|
|
16
|
+
function describeOpener(ctx) {
|
|
17
|
+
const from = ctx.from;
|
|
18
|
+
if (!from)
|
|
19
|
+
return 'someone';
|
|
20
|
+
return [from.first_name, from.last_name].filter(Boolean).join(' ') || from.username || `user ${from.id}`;
|
|
21
|
+
}
|
|
22
|
+
/** The carve-outs a window never approves, under their heading. */
|
|
23
|
+
function appendCarveOuts(b) {
|
|
24
|
+
b.bold('Still asks, always:');
|
|
25
|
+
for (const reason of listAlwaysPrompted())
|
|
26
|
+
b.add(`\n• ${reason}`);
|
|
27
|
+
return b;
|
|
28
|
+
}
|
|
29
|
+
/** A heading line: the emoji, then the rest in bold. */
|
|
30
|
+
function heading(emoji, text) {
|
|
31
|
+
return new EntityText().add(`${emoji} `).bold(text);
|
|
32
|
+
}
|
|
33
|
+
const END_EARLY = new EntityText()
|
|
34
|
+
.add('End it early with ').code('/autoapprove off').add('.')
|
|
35
|
+
.build();
|
|
36
|
+
export async function handleAutoApprove(ctx) {
|
|
37
|
+
const chatId = ctx.chat?.id;
|
|
38
|
+
if (chatId === undefined)
|
|
39
|
+
return;
|
|
40
|
+
const arg = (ctx.message?.text ?? '').split(' ').slice(1).join(' ').trim();
|
|
41
|
+
const lowered = arg.toLowerCase();
|
|
42
|
+
if (lowered === 'off' || lowered === 'stop' || lowered === 'end') {
|
|
43
|
+
await handleClose(ctx, chatId);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (lowered === 'status') {
|
|
47
|
+
await handleStatus(ctx, chatId);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const duration = parseWindowDuration(arg);
|
|
51
|
+
if (!duration.ok) {
|
|
52
|
+
await ctx.reply(`❌ ${duration.error}`);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
await handleOpen(ctx, chatId, duration.ms);
|
|
56
|
+
}
|
|
57
|
+
async function handleOpen(ctx, chatId, durationMs) {
|
|
58
|
+
const existing = getWindow(chatId);
|
|
59
|
+
const openerName = describeOpener(ctx);
|
|
60
|
+
const window = openWindow(chatId, {
|
|
61
|
+
openedBy: ctx.from?.id ?? 0,
|
|
62
|
+
openedByName: openerName,
|
|
63
|
+
durationMs,
|
|
64
|
+
// Announced rather than silent: a window that lapses unnoticed leaves
|
|
65
|
+
// people tapping prompts they thought were handled, and — worse the other
|
|
66
|
+
// way — a window people believe is shut but is not.
|
|
67
|
+
onExpire: (lapsed) => {
|
|
68
|
+
void announceExpiry(ctx, lapsed);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
console.log(`[AutoApprove] chat:${chatId} opened by ${ctx.from?.id ?? '?'} for ${formatDuration(durationMs)}`
|
|
72
|
+
+ (existing ? ' (replacing an open window)' : ''));
|
|
73
|
+
const b = heading('⚡', `Auto-approve is on for ${formatDuration(durationMs)}`).add('\n\n');
|
|
74
|
+
if (existing) {
|
|
75
|
+
b.italic(`Replaces the window ${existing.openedByName} opened, which had ${formatRemaining(existing)} left.`)
|
|
76
|
+
.add('\n\n');
|
|
77
|
+
}
|
|
78
|
+
b.add(`Opened by ${openerName}. Guarded commands in this chat will run without ` +
|
|
79
|
+
'asking, and each one is posted here as it happens.\n\n');
|
|
80
|
+
appendCarveOuts(b).add('\n\n').append(END_EARLY);
|
|
81
|
+
if (!isPermissionGateEnabled()) {
|
|
82
|
+
b.add('\n\n⚠️ The permission gate is ').bold('off')
|
|
83
|
+
.add(' in this bot, so nothing was prompting in the first place and this window changes nothing.');
|
|
84
|
+
}
|
|
85
|
+
await replyFormatted(ctx, b.build());
|
|
86
|
+
}
|
|
87
|
+
async function handleClose(ctx, chatId) {
|
|
88
|
+
const closed = closeWindow(chatId);
|
|
89
|
+
if (!closed) {
|
|
90
|
+
await ctx.reply('✅ No auto-approve window is open here.');
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
// Anyone who could open one can close one, including someone else's: a
|
|
94
|
+
// supervision hole should be closable by whoever notices it, not only by
|
|
95
|
+
// whoever left it open.
|
|
96
|
+
const byOther = closed.openedBy !== ctx.from?.id;
|
|
97
|
+
console.log(`[AutoApprove] chat:${chatId} closed by ${ctx.from?.id ?? '?'}${byOther ? ` (opened by ${closed.openedBy})` : ''}`);
|
|
98
|
+
const b = heading('🔒', 'Auto-approve is off.').add(`\n\n${describeTally(closed)}`);
|
|
99
|
+
if (byOther)
|
|
100
|
+
b.add('\n\n').italic(`It was ${closed.openedByName}'s window.`);
|
|
101
|
+
await replyFormatted(ctx, b.build());
|
|
102
|
+
}
|
|
103
|
+
async function handleStatus(ctx, chatId) {
|
|
104
|
+
const window = getWindow(chatId);
|
|
105
|
+
if (!window) {
|
|
106
|
+
const b = heading('🔒', 'Auto-approve is off here.')
|
|
107
|
+
.add('\n\nGuarded commands post an approval prompt, and an admin or approver taps it.')
|
|
108
|
+
.add('\n\nOpen a window with ').code('/autoapprove 30m').add('.');
|
|
109
|
+
if (!isAdmin(ctx.from?.id)) {
|
|
110
|
+
b.add('\n\n').italic('You can open one — approvers may, guests may not.');
|
|
111
|
+
}
|
|
112
|
+
await replyFormatted(ctx, b.build());
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const b = heading('⚡', `Auto-approve is on — ${formatRemaining(window)} left.`)
|
|
116
|
+
.add(`\n\nOpened by ${window.openedByName}. ${describeTally(window)}\n\n`);
|
|
117
|
+
appendCarveOuts(b).add('\n\n').append(END_EARLY);
|
|
118
|
+
await replyFormatted(ctx, b.build());
|
|
119
|
+
}
|
|
120
|
+
function describeTally(window) {
|
|
121
|
+
if (window.approved === 0)
|
|
122
|
+
return 'Nothing has needed approving yet.';
|
|
123
|
+
return window.approved === 1
|
|
124
|
+
? 'It approved 1 command.'
|
|
125
|
+
: `It approved ${window.approved} commands.`;
|
|
126
|
+
}
|
|
127
|
+
async function announceExpiry(ctx, window) {
|
|
128
|
+
console.log(`[AutoApprove] chat:${window.chatId} lapsed after approving ${window.approved}`);
|
|
129
|
+
try {
|
|
130
|
+
await ctx.api.sendMessage(window.chatId, `🔒 Auto-approve has lapsed — guarded commands ask again. ${describeTally(window)}`);
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
// Fires on a bare timer with nobody to catch it, and a chat that has gone
|
|
134
|
+
// away must not take the process with it.
|
|
135
|
+
console.error('[AutoApprove] expiry notice failed:', err instanceof Error ? err.message : err);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=auto-approve.js.map
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /btw — ask a side question without disturbing the main conversation.
|
|
3
|
+
*
|
|
4
|
+
* Runs the question against a fork of the current session, streaming a
|
|
5
|
+
* progress line while it works, so the answer lands without the main turn
|
|
6
|
+
* losing its place.
|
|
7
|
+
*/
|
|
8
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
9
|
+
import { getActiveQuery } from '../../../claude/request-queue.js';
|
|
10
|
+
import { askForkedSideQuestion } from '../../../claude/side-question.js';
|
|
11
|
+
import { messageSender } from '../../../telegram/message-sender.js';
|
|
12
|
+
import { getActiveProviderName } from '../../../providers/provider-router.js';
|
|
13
|
+
import { getActiveMethod } from '../../../providers/claude-provider.js';
|
|
14
|
+
import { sanitizeError } from '../../../utils/sanitize.js';
|
|
15
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
16
|
+
// ── /btw ─────────────────────────────────────────────────────────
|
|
17
|
+
export async function handleBtw(ctx) {
|
|
18
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
19
|
+
if (!keyInfo)
|
|
20
|
+
return;
|
|
21
|
+
const { sessionKey } = keyInfo;
|
|
22
|
+
const text = ctx.message?.text || '';
|
|
23
|
+
const question = text.replace(/^\/btw\s*/i, '').trim();
|
|
24
|
+
if (!question) {
|
|
25
|
+
await ctx.reply('Usage: /btw <your question>\n\nAsk a side question without interrupting the current task.');
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
await askBtw(ctx, sessionKey, question);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Answer `question` alongside the running turn, without it reaching the main
|
|
32
|
+
* conversation. Also what "Ask as /btw" on a queued message calls, with the
|
|
33
|
+
* context of the tap rather than of a typed command.
|
|
34
|
+
*/
|
|
35
|
+
export async function askBtw(ctx, sessionKey, question) {
|
|
36
|
+
// PTY mode has no SDK Query to hang askSideQuestion off — answer from a
|
|
37
|
+
// read-only fork of the live session instead. Only Claude sessions have a
|
|
38
|
+
// resumable JSONL transcript; ccr falls through to the SDK path.
|
|
39
|
+
const usesPty = getActiveProviderName(sessionKey) === 'claude'
|
|
40
|
+
&& getActiveMethod(sessionKey) === 'pty';
|
|
41
|
+
if (usesPty) {
|
|
42
|
+
await handleBtwViaFork(ctx, sessionKey, question);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const activeQuery = getActiveQuery(sessionKey);
|
|
46
|
+
if (!activeQuery) {
|
|
47
|
+
// The query object only exists while a turn is in flight — this is not a
|
|
48
|
+
// statement about whether the conversation itself exists.
|
|
49
|
+
await ctx.reply('No turn is running right now, so there is nothing to ask alongside. Send your question as a regular message instead.');
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// askSideQuestion exists at runtime but isn't in the TypeScript types yet
|
|
53
|
+
const queryAny = activeQuery;
|
|
54
|
+
if (typeof queryAny.askSideQuestion !== 'function') {
|
|
55
|
+
await ctx.reply('Side questions are not supported by the current SDK version.');
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
// The SDK reports no progress for a side question, so the line just shows
|
|
59
|
+
// it's alive with a ticking elapsed — without it nothing appears until the
|
|
60
|
+
// whole answer lands.
|
|
61
|
+
const headline = `💬 /btw — ${btwLabel(question)}`;
|
|
62
|
+
const ack = await ctx.reply(`${headline}\nasking on the side… (main task keeps running)`);
|
|
63
|
+
const progress = new BtwProgressLine(ctx, ctx.chat.id, ack.message_id, headline);
|
|
64
|
+
const startedAt = Date.now();
|
|
65
|
+
try {
|
|
66
|
+
const result = await queryAny.askSideQuestion(question);
|
|
67
|
+
await progress.finish(0, Date.now() - startedAt);
|
|
68
|
+
if (!result || !result.response) {
|
|
69
|
+
await ctx.reply("I don't have enough context to answer that.");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
await messageSender.sendMessage(ctx, formatSideAnswer(question, result.response));
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
const msg = error instanceof Error ? error.message : 'Unknown error';
|
|
76
|
+
console.error('[btw] Error:', msg);
|
|
77
|
+
await progress.fail();
|
|
78
|
+
await ctx.reply(`Failed to answer side question: ${msg}`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Longest slice of the question echoed back in /btw labels. */
|
|
82
|
+
const BTW_LABEL_MAX = 80;
|
|
83
|
+
/**
|
|
84
|
+
* One-line echo of the question, for labels that sit next to live turn output.
|
|
85
|
+
* Formatting characters are dropped — the label is interpolated inside an
|
|
86
|
+
* italic run, and a stray `_` or `*` would unbalance it and fail the parse.
|
|
87
|
+
*/
|
|
88
|
+
export function btwLabel(question) {
|
|
89
|
+
const flat = question.replace(/[_*`[\]]/g, '').replace(/\s+/g, ' ').trim();
|
|
90
|
+
return flat.length > BTW_LABEL_MAX ? `${flat.slice(0, BTW_LABEL_MAX - 1)}…` : flat;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* A /btw answer lands in the middle of a running turn's output, so it has to
|
|
94
|
+
* announce itself — otherwise it reads as something the main task said. The
|
|
95
|
+
* echoed question also tells two concurrent side questions apart.
|
|
96
|
+
*/
|
|
97
|
+
export function formatSideAnswer(question, response) {
|
|
98
|
+
return `💬 **/btw** — _${btwLabel(question)}_\n\n${response}`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* PTY-mode `/btw`: shell out to a forked, non-persisted copy of the live
|
|
102
|
+
* claude session so the running turn is never interrupted or mutated.
|
|
103
|
+
*/
|
|
104
|
+
async function handleBtwViaFork(ctx, sessionKey, question) {
|
|
105
|
+
const session = sessionManager.getSession(sessionKey);
|
|
106
|
+
if (!session?.claudeSessionId) {
|
|
107
|
+
await ctx.reply('No conversation to ask about yet. Send a message first, then /btw can answer alongside it.');
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const chatId = ctx.chat.id;
|
|
111
|
+
const headline = `💬 /btw — ${btwLabel(question)}`;
|
|
112
|
+
// Labelled ack: this sits alongside the main turn's live status message, so
|
|
113
|
+
// it has to be obvious which one belongs to the side question. It then
|
|
114
|
+
// doubles as the progress line, and finally as a one-line receipt.
|
|
115
|
+
const ack = await ctx.reply(`${headline}\nasking on the side… (main task keeps running)`);
|
|
116
|
+
const progress = new BtwProgressLine(ctx, chatId, ack.message_id, headline);
|
|
117
|
+
try {
|
|
118
|
+
const result = await askForkedSideQuestion({
|
|
119
|
+
question,
|
|
120
|
+
sessionId: session.claudeSessionId,
|
|
121
|
+
cwd: session.workingDirectory,
|
|
122
|
+
onProgress: (p) => progress.update(p),
|
|
123
|
+
});
|
|
124
|
+
await progress.finish(result.toolCount ?? 0, result.elapsedMs ?? 0);
|
|
125
|
+
if (!result.response) {
|
|
126
|
+
await ctx.reply("I don't have enough context to answer that.");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
await messageSender.sendMessage(ctx, formatSideAnswer(question, result.response));
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
const msg = error instanceof Error ? error.message : 'Unknown error';
|
|
133
|
+
console.error('[btw] Fork error:', sanitizeError(error));
|
|
134
|
+
await progress.fail();
|
|
135
|
+
await ctx.reply(`Failed to answer side question: ${msg}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Minimum gap between /btw progress edits — Telegram rate-limits edits hard. */
|
|
139
|
+
const BTW_EDIT_INTERVAL_MS = 2000;
|
|
140
|
+
/** How often the elapsed counter ticks while a single slow tool runs. */
|
|
141
|
+
const BTW_TICK_MS = 5000;
|
|
142
|
+
/**
|
|
143
|
+
* Owns the single `/btw` message across its three lives: ack → live progress →
|
|
144
|
+
* one-line receipt. Keeping it as one message is the point — a side question
|
|
145
|
+
* shouldn't add a second log competing with the running turn's own output.
|
|
146
|
+
*/
|
|
147
|
+
class BtwProgressLine {
|
|
148
|
+
ctx;
|
|
149
|
+
chatId;
|
|
150
|
+
messageId;
|
|
151
|
+
headline;
|
|
152
|
+
latest = null;
|
|
153
|
+
lastRendered = '';
|
|
154
|
+
lastEditAt = 0;
|
|
155
|
+
ticker;
|
|
156
|
+
done = false;
|
|
157
|
+
constructor(ctx, chatId, messageId, headline) {
|
|
158
|
+
this.ctx = ctx;
|
|
159
|
+
this.chatId = chatId;
|
|
160
|
+
this.messageId = messageId;
|
|
161
|
+
this.headline = headline;
|
|
162
|
+
// Repaint on a timer too, so elapsed keeps moving during a long tool call.
|
|
163
|
+
this.ticker = setInterval(() => { void this.render(); }, BTW_TICK_MS);
|
|
164
|
+
}
|
|
165
|
+
update(p) {
|
|
166
|
+
this.latest = p;
|
|
167
|
+
void this.render();
|
|
168
|
+
}
|
|
169
|
+
/** Collapse to a receipt: what the side question did, in one line. */
|
|
170
|
+
async finish(toolCount, elapsedMs) {
|
|
171
|
+
this.stop();
|
|
172
|
+
const detail = toolCount > 0
|
|
173
|
+
? `${toolCount} ${toolCount === 1 ? 'tool' : 'tools'} · ${formatBtwElapsed(elapsedMs)}`
|
|
174
|
+
: formatBtwElapsed(elapsedMs);
|
|
175
|
+
await this.edit(`${this.headline} · ${detail}`);
|
|
176
|
+
}
|
|
177
|
+
async fail() {
|
|
178
|
+
this.stop();
|
|
179
|
+
await this.edit(`${this.headline} · failed`);
|
|
180
|
+
}
|
|
181
|
+
stop() {
|
|
182
|
+
this.done = true;
|
|
183
|
+
if (this.ticker) {
|
|
184
|
+
clearInterval(this.ticker);
|
|
185
|
+
this.ticker = null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
async render() {
|
|
189
|
+
if (this.done)
|
|
190
|
+
return;
|
|
191
|
+
const now = Date.now();
|
|
192
|
+
if (now - this.lastEditAt < BTW_EDIT_INTERVAL_MS)
|
|
193
|
+
return;
|
|
194
|
+
const p = this.latest;
|
|
195
|
+
const elapsed = formatBtwElapsed(p ? p.elapsedMs : 0);
|
|
196
|
+
const activity = p?.currentTool
|
|
197
|
+
? `🔧 ${p.currentTool}${p.currentHint ? `: ${btwLabel(p.currentHint)}` : ''}`
|
|
198
|
+
: 'thinking…';
|
|
199
|
+
const counter = p && p.toolCount > 0
|
|
200
|
+
? ` · ${p.toolCount} ${p.toolCount === 1 ? 'tool' : 'tools'} · ${elapsed}`
|
|
201
|
+
: ` · ${elapsed}`;
|
|
202
|
+
await this.edit(`${this.headline}\n${activity}${counter}`);
|
|
203
|
+
}
|
|
204
|
+
async edit(text) {
|
|
205
|
+
// Telegram rejects an edit that changes nothing, so skip those outright.
|
|
206
|
+
if (text === this.lastRendered)
|
|
207
|
+
return;
|
|
208
|
+
this.lastEditAt = Date.now();
|
|
209
|
+
this.lastRendered = text;
|
|
210
|
+
try {
|
|
211
|
+
await this.ctx.api.editMessageText(this.chatId, this.messageId, text);
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
console.debug('[btw] progress edit failed:', err instanceof Error ? err.message : err);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function formatBtwElapsed(ms) {
|
|
219
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
220
|
+
if (seconds < 60)
|
|
221
|
+
return `${seconds}s`;
|
|
222
|
+
return `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, '0')}s`;
|
|
223
|
+
}
|
|
224
|
+
//# sourceMappingURL=btw.js.map
|