telecoder 0.0.0-stage → 1.3.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.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,657 @@
1
+ /**
2
+ * Per-chat settings menus: /suggestions, /effort, /verbosity and the status line.
3
+ *
4
+ * They share one shape — render an inline keyboard reflecting current state,
5
+ * flip a setting on tap, re-render — and several need the same pty-restart
6
+ * note when the change only lands on a fresh spawn.
7
+ */
8
+ import * as path from 'path';
9
+ import { config } from '../../../config.js';
10
+ import { sessionManager } from '../../../claude/session-manager.js';
11
+ import { promptsIn } from '../../../claude/branch-tree.js';
12
+ import { getEffort, isValidEffortLevel, getActiveProviderName, } from '../../../providers/provider-router.js';
13
+ import { userPreferences } from '../../../providers/user-preferences.js';
14
+ import { contextTokens } from '../../../providers/types.js';
15
+ import { isPremiumModel, PREMIUM_MODEL_ICON } from '../../../claude/model-catalog.js';
16
+ import { getPtyProvider } from '../../../providers/claude-provider.js';
17
+ import { EntityText, joinMessages } from '../../../telegram/entities.js';
18
+ import { replyFormatted, editCallbackMessage } from '../../../telegram/send.js';
19
+ import { taskTracker } from '../../../telegram/task-tracker.js';
20
+ import { promptLabel, cutLabel } from '../../../telegram/prompt-label.js';
21
+ import { getSuggestionsSettings, setSuggestionsEnabled } from '../../../telegram/suggestions-settings.js';
22
+ import { VERBOSITY_INFO, isValidVerbosityLevel, getVerbosityLevel, resolveVerbosityFlags, } from '../../../utils/verbosity.js';
23
+ import { contextHealthColor, fmtTokens, getProgressBar } from '../../../utils/format.js';
24
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
25
+ import { PERMISSION_MODES, isPermissionModeId, parsePermissionModeArg, permissionModeInfo, defaultPermissionMode, } from '../../../claude/permission-mode.js';
26
+ import { replyMd, getEffortLabel, effortLevelLabel, EFFORT_LEVELS, } from './shared.js';
27
+ import { getSessionTopic } from './topic.js';
28
+ import { getBgProcesses } from './tasks.js';
29
+ import { parseScopeArg, isBareLevelWord, scopeSite, applyAtLevel, describeSource, levelHelp, EVERYWHERE_ADMIN_ONLY, } from './prefs-scope.js';
30
+ function buildSuggestionsMenu(sessionKey) {
31
+ const settings = getSuggestionsSettings(sessionKey);
32
+ const defaultLabel = config.PROMPT_SUGGESTIONS_DEFAULT ? 'on' : 'off';
33
+ const statusLine = settings.enabled ? 'ON' : 'OFF';
34
+ const text = new EntityText()
35
+ .add('💡 ').bold('Predicted Next Prompt').newline(2)
36
+ .add('Status: ').bold(statusLine).newline()
37
+ .add('Default: ').bold(defaultLabel).newline(2)
38
+ .italic("When enabled, TeleCoder surfaces Claude Code's speculative next-prompt as an inline button under each response. Tap to send it as your next message.")
39
+ .newline(2)
40
+ .italic('Takes effect on the next session spawn (env var is set at spawn time).')
41
+ .build();
42
+ return {
43
+ text,
44
+ keyboard: [
45
+ [
46
+ { text: settings.enabled ? '✓ On' : 'On', callback_data: 'sugg:on' },
47
+ { text: !settings.enabled ? '✓ Off' : 'Off', callback_data: 'sugg:off' },
48
+ ],
49
+ ],
50
+ };
51
+ }
52
+ // ── /effort ──────────────────────────────────────────────────────
53
+ export async function handleEffort(ctx) {
54
+ const keyInfo = getSessionKeyFromCtx(ctx);
55
+ if (!keyInfo)
56
+ return;
57
+ const { sessionKey } = keyInfo;
58
+ const text = ctx.message?.text || '';
59
+ const parsed = parseScopeArg(text.split(' ').slice(1).join(' '));
60
+ const args = parsed.value.toLowerCase();
61
+ const site = scopeSite(ctx);
62
+ if (!args) {
63
+ const currentEffort = getEffort(sessionKey) || 'default';
64
+ const keyboard = EFFORT_LEVELS.map((level) => {
65
+ const isCurrent = level.id === currentEffort;
66
+ const label = isCurrent ? `✓ ${level.label}` : level.label;
67
+ return [{ text: label, callback_data: `effort:${level.id}` }];
68
+ });
69
+ // Add auto/reset option
70
+ keyboard.push([{ text: currentEffort === 'default' ? '✓ Auto (default)' : 'Auto (default)', callback_data: 'effort:auto' }]);
71
+ const picker = new EntityText()
72
+ .add('🎯 ').bold('Effort Level').newline(2)
73
+ .italic(`Current: ${currentEffort === 'default' ? 'auto' : currentEffort}, ${describeSource(sessionKey, 'effort')}`).newline(2);
74
+ for (const l of EFFORT_LEVELS) {
75
+ picker.add('• ').bold(l.label).add(` - ${l.description}\n`);
76
+ }
77
+ picker.add('• ').bold('Auto').add(" - Claude Code's default");
78
+ picker.append(levelHelp('effort', 'high', site));
79
+ await replyFormatted(ctx, picker.build(), {
80
+ reply_markup: { inline_keyboard: keyboard },
81
+ });
82
+ return;
83
+ }
84
+ // A level word on its own has no effort level attached — point at the form
85
+ // that works rather than rejecting it as an unknown level. `default` stays
86
+ // the reset it always was.
87
+ if (args !== 'default' && isBareLevelWord(args)) {
88
+ await replyMd(ctx, `\`${args}\` says how far to apply an effort level, but it needs the level too.\n\n` +
89
+ `Try \`/effort high ${args}\`, or /effort to pick one.`);
90
+ return;
91
+ }
92
+ const reset = args === 'auto' || args === 'default' || args === 'reset';
93
+ if (!reset && !isValidEffortLevel(args)) {
94
+ await replyFormatted(ctx, `❌ Unknown effort level "${args}".\n\nValid: low, medium, high, xhigh, max, auto`);
95
+ return;
96
+ }
97
+ const level = parsed.level ?? 'thread';
98
+ if (level === 'all' && !site.admin) {
99
+ await replyFormatted(ctx, new EntityText().add(`⛔ ${EVERYWHERE_ADMIN_ONLY}`).build());
100
+ return;
101
+ }
102
+ const value = reset ? null : args;
103
+ const label = reset ? 'Auto (CLI default)' : EFFORT_LEVELS.find(l => l.id === args)?.label || args;
104
+ const { message, keyboard } = await applyAtLevel(ctx, { sessionKey, setting: 'effort', value, label, level, site });
105
+ await replyFormatted(ctx, message.build(), {
106
+ ...(keyboard ? { reply_markup: { inline_keyboard: keyboard } } : {}),
107
+ });
108
+ }
109
+ export async function handleEffortCallback(ctx) {
110
+ const keyInfo = getSessionKeyFromCtx(ctx);
111
+ if (!keyInfo)
112
+ return;
113
+ const { sessionKey } = keyInfo;
114
+ const data = ctx.callbackQuery?.data;
115
+ if (!data || !data.startsWith('effort:'))
116
+ return;
117
+ const choice = data.replace('effort:', '');
118
+ if (choice !== 'auto' && !isValidEffortLevel(choice)) {
119
+ await ctx.answerCallbackQuery({ text: 'Invalid effort level' });
120
+ return;
121
+ }
122
+ const value = choice === 'auto' ? null : choice;
123
+ const label = value === null ? 'Auto (CLI default)' : EFFORT_LEVELS.find(l => l.id === value)?.label || value;
124
+ await ctx.answerCallbackQuery({ text: value === null ? 'Effort reset to auto!' : `Effort set to ${label}!` });
125
+ const site = scopeSite(ctx);
126
+ const { message, keyboard } = await applyAtLevel(ctx, {
127
+ sessionKey, setting: 'effort', value, label, level: 'thread', site,
128
+ });
129
+ await editCallbackMessage(ctx, message.build(), {
130
+ ...(keyboard ? { reply_markup: { inline_keyboard: keyboard } } : {}),
131
+ });
132
+ }
133
+ // ── /footer ─────────────────────────────────────────────────
134
+ // A small italic message sent after each turn so the user can always see
135
+ // the current state right above the compose box without scrolling. On by
136
+ // default (STATUS_LINE_DEFAULT); /footer turns it off per chat. It
137
+ // follows the reply, which already rang the phone, so it's sent silently.
138
+ function shortenModelName(model) {
139
+ // Strip "vendor/" prefix (OpenRouter / CCR style: "anthropic/claude-4-sonnet-...")
140
+ const slashIdx = model.lastIndexOf('/');
141
+ const stripped = slashIdx >= 0 ? model.substring(slashIdx + 1) : model;
142
+ // claude-opus-4-8 → opus-4-8; trim trailing -YYYYMMDD release tags.
143
+ return stripped.replace(/^claude-/, '').replace(/-\d{8}$/, '');
144
+ }
145
+ // The last few prompts rather than only the latest: a turn often starts from
146
+ // an "ok" or a "yeah", which says nothing without the prompts before it.
147
+ const STATUS_LINE_PROMPTS = 5;
148
+ // Past this a prompt shows its start and its end. Most prompts are one
149
+ // paragraph, and across 100 recent sessions 93% of those fit, where 100
150
+ // characters cut a third of them. Five sit under every answer: at 40
151
+ // characters a row they take a median of 15 rows, and at most 40.
152
+ const STATUS_LINE_PROMPT_MAX = 300;
153
+ /**
154
+ * The status line's prompt lines, oldest first so they read in the same order
155
+ * as the chat above them. `prompts` are raw, as the session log keeps them;
156
+ * anything that wasn't a turn, like a /compact, is dropped before the last few
157
+ * are taken, so it doesn't use up one of the lines.
158
+ */
159
+ export function formatRecentPrompts(prompts) {
160
+ const b = new EntityText();
161
+ prompts
162
+ .flatMap((prompt) => promptLabel(prompt) ?? [])
163
+ .slice(-STATUS_LINE_PROMPTS)
164
+ .forEach((label, i) => {
165
+ if (i > 0)
166
+ b.newline();
167
+ b.italic(`▸ ${cutLabel(label, STATUS_LINE_PROMPT_MAX)}`);
168
+ });
169
+ return b.build();
170
+ }
171
+ /**
172
+ * The session's prompts as its log records them, so the list reaches back past
173
+ * a restart and past prompts sent from elsewhere. The turn's own prompt stands
174
+ * in when the log has none to give. A reply no prompt started, like the one to
175
+ * a background task that reported back, has only the log to go by.
176
+ */
177
+ function recentPrompts(sessionKey, lastPrompt) {
178
+ const session = sessionKey ? sessionManager.getSession(sessionKey) : undefined;
179
+ const logged = session?.claudeSessionId
180
+ ? promptsIn(session.workingDirectory, session.claudeSessionId)
181
+ : [];
182
+ if (logged.length > 0)
183
+ return logged;
184
+ return lastPrompt ? [lastPrompt] : [];
185
+ }
186
+ /**
187
+ * The usage footer, if there's a figure to show and /verbosity wants it shown.
188
+ * Plain text, whether sent alone or closing the status line.
189
+ */
190
+ function usageFooter(chatId, usage) {
191
+ if (!usage || !resolveVerbosityFlags(chatId).showUsageFooter)
192
+ return undefined;
193
+ const used = contextTokens(usage);
194
+ const pct = usage.contextWindow > 0 ? Math.round((used / usage.contextWindow) * 100) : 0;
195
+ const bar = getProgressBar(pct, contextHealthColor(used, usage.contextWindow));
196
+ return `${bar} ${pct}% context · ${fmtTokens(used)}/${fmtTokens(usage.contextWindow)} · ${usage.numTurns} turns`;
197
+ }
198
+ /**
199
+ * Build the status-line message body.
200
+ * Each enabled line picks its own formatting (italic for topic/stats,
201
+ * mono code span for the resume command so it's easy to copy).
202
+ *
203
+ * Sections are joined with blank lines so the first line (typically the
204
+ * topic) stands alone in Telegram's chat-list preview — that's the only
205
+ * line visible when distinguishing multiple bots in the same project.
206
+ *
207
+ * The usage footer, when the chat shows one, closes the message.
208
+ *
209
+ * `brief` leaves the stats and that footer: see StatusLineOptions.
210
+ */
211
+ function buildStatusLine(chatId, sessionKey, usage, lastPrompt, brief = false) {
212
+ const sections = [];
213
+ if (!brief && sessionKey && userPreferences.getShowTopicInStatusLine(chatId)) {
214
+ const topic = getSessionTopic(sessionKey);
215
+ if (topic)
216
+ sections.push(new EntityText().italic(`💬 ${topic}`).build());
217
+ }
218
+ if (!brief && userPreferences.getShowPromptInStatusLine(chatId)) {
219
+ const formatted = formatRecentPrompts(recentPrompts(sessionKey, lastPrompt));
220
+ if (formatted.text)
221
+ sections.push(formatted);
222
+ }
223
+ const tail = new EntityText();
224
+ if (!brief && sessionKey && userPreferences.getShowSessionInStatusLine(chatId)) {
225
+ const claudeSessionId = sessionManager.getSession(sessionKey)?.claudeSessionId;
226
+ if (claudeSessionId) {
227
+ tail.add('🔗 ').code(`claude --resume ${claudeSessionId}`).newline();
228
+ }
229
+ }
230
+ const stats = [];
231
+ // The bot's display name only says where it is now; this stays with each
232
+ // answer for scrolling back. After a switch it already names the new project,
233
+ // where the next message goes, even though the turn ran in the old one.
234
+ const project = sessionKey ? sessionManager.getSession(sessionKey)?.workingDirectory : undefined;
235
+ if (project)
236
+ stats.push(`📁 ${path.basename(project) || project}`);
237
+ // The chat's own /effort pick, else the effort the log says the reply ran
238
+ // at; "Auto" only while neither is known.
239
+ const label = getEffortLabel(sessionKey ?? chatId)
240
+ ?? (usage?.effort ? effortLevelLabel(usage.effort) : undefined);
241
+ stats.push(label || '🧠 Auto');
242
+ const footer = usageFooter(chatId, usage);
243
+ const provider = getActiveProviderName(sessionKey ?? chatId);
244
+ if (usage) {
245
+ if (usage.model) {
246
+ const shortened = shortenModelName(usage.model);
247
+ // The alias doesn't reflect CCR's actual backend; tag accordingly.
248
+ // A premium model swaps the robot for a badge, so it stands out of the
249
+ // row rather than reading as one more stat.
250
+ if (provider === 'ccr')
251
+ stats.push(`🤖 ${shortened} · CCR`);
252
+ else if (isPremiumModel(usage.model))
253
+ stats.push(`${PREMIUM_MODEL_ICON} ${shortened.toUpperCase()}`);
254
+ else
255
+ stats.push(`🤖 ${shortened}`);
256
+ }
257
+ // The footer gives this right below, in more detail.
258
+ if (!footer && usage.contextWindow > 0) {
259
+ const used = contextTokens(usage);
260
+ const pct = Math.round((used / usage.contextWindow) * 100);
261
+ // The chart while it's healthy; amber or red once it's grown big
262
+ // enough that a /clear or branch is worth thinking about.
263
+ const health = contextHealthColor(used, usage.contextWindow);
264
+ stats.push(`${health === '🟢' ? '📊' : health} ${pct}%`);
265
+ }
266
+ }
267
+ // Activity counters — only rendered when non-zero so quiet turns stay quiet.
268
+ // Tasks/monitors come from the task tracker; bg shells from the pty's
269
+ // /proc children, so that count is left out when no pty is live.
270
+ if (sessionKey) {
271
+ const bg = taskTracker.getTasks(sessionKey);
272
+ const monitorCount = bg.filter((t) => t.taskType === 'monitor_mcp').length;
273
+ const taskCount = bg.length - monitorCount;
274
+ if (taskCount > 0)
275
+ stats.push(`🔄 ${taskCount}`);
276
+ if (monitorCount > 0)
277
+ stats.push(`📡 ${monitorCount}`);
278
+ const claudePid = getPtyProvider().getSessionPid(sessionKey);
279
+ if (claudePid !== undefined) {
280
+ const shellCount = getBgProcesses(claudePid).length;
281
+ if (shellCount > 0)
282
+ stats.push(`🔍 ${shellCount}`);
283
+ }
284
+ }
285
+ tail.italic(stats.join(' · '));
286
+ if (footer)
287
+ tail.newline().add(footer);
288
+ sections.push(tail.build());
289
+ return joinMessages(sections);
290
+ }
291
+ /**
292
+ * The message that closes a turn: the status line, with the usage footer at its
293
+ * bottom when the chat shows both. /footer and /verbosity set them apart,
294
+ * so with the status line off, a chat that shows the footer gets it on its own.
295
+ *
296
+ * `lastPrompt` is the turn's own, for a session whose log has no prompts to
297
+ * list. Leave it out for a reply that no prompt started.
298
+ */
299
+ export async function sendStatusLine(ctx, chatId, sessionKey, usage, lastPrompt, { brief = false } = {}) {
300
+ try {
301
+ if (userPreferences.getShowStatusLine(chatId)) {
302
+ await replyFormatted(ctx, buildStatusLine(chatId, sessionKey, usage, lastPrompt, brief), {
303
+ disable_notification: true,
304
+ });
305
+ return;
306
+ }
307
+ const footer = usageFooter(chatId, usage);
308
+ if (footer)
309
+ await ctx.reply(footer, { disable_notification: true });
310
+ }
311
+ catch (err) {
312
+ console.debug('[StatusLine] Failed to send:', err instanceof Error ? err.message : err);
313
+ }
314
+ }
315
+ function buildStatusLineMenu(chatId, sessionKey) {
316
+ const enabled = userPreferences.getShowStatusLine(chatId);
317
+ const showTopic = userPreferences.getShowTopicInStatusLine(chatId);
318
+ const showSession = userPreferences.getShowSessionInStatusLine(chatId);
319
+ const showPrompt = userPreferences.getShowPromptInStatusLine(chatId);
320
+ const keyboard = [
321
+ [
322
+ { text: enabled ? '✓ Footer: On' : 'Footer: On', callback_data: 'footer:on' },
323
+ { text: !enabled ? '✓ Footer: Off' : 'Footer: Off', callback_data: 'footer:off' },
324
+ ],
325
+ [
326
+ { text: showTopic ? '✓ Show topic: On' : 'Show topic: On', callback_data: 'footer:topic:on' },
327
+ { text: !showTopic ? '✓ Show topic: Off' : 'Show topic: Off', callback_data: 'footer:topic:off' },
328
+ ],
329
+ [
330
+ { text: showPrompt ? '✓ Show last prompts: On' : 'Show last prompts: On', callback_data: 'footer:prompt:on' },
331
+ { text: !showPrompt ? '✓ Show last prompts: Off' : 'Show last prompts: Off', callback_data: 'footer:prompt:off' },
332
+ ],
333
+ [
334
+ { text: showSession ? '✓ Show session: On' : 'Show session: On', callback_data: 'footer:session:on' },
335
+ { text: !showSession ? '✓ Show session: Off' : 'Show session: Off', callback_data: 'footer:session:off' },
336
+ ],
337
+ ];
338
+ const preview = buildStatusLine(chatId, sessionKey, undefined, 'example prompt for preview');
339
+ const onOff = (on) => (on ? 'ON' : 'OFF');
340
+ const text = new EntityText()
341
+ .add('📍 ').bold('Footer').newline(2)
342
+ .add('Footer: ').bold(onOff(enabled)).newline()
343
+ .add('Show topic: ').bold(onOff(showTopic)).newline()
344
+ .add('Show last prompts: ').bold(onOff(showPrompt)).newline()
345
+ .add('Show session: ').bold(onOff(showSession)).newline(2)
346
+ .italic('Sends a small italic line after each turn so you can see the current state without scrolling.')
347
+ .add(' ')
348
+ .italic(`Show last prompts lists the last ${STATUS_LINE_PROMPTS} you sent, so an "ok" still shows what it answered. ` +
349
+ 'Handy under /verbosity verbose, where the action log can push them off screen.')
350
+ .add(' ')
351
+ .wrap('italic', (b) => b
352
+ .add('The session line shows a copy-pasteable ')
353
+ .code('claude --resume')
354
+ .add(' command for CLI fallback.'))
355
+ .add('\n\nPreview:\n')
356
+ .append(preview)
357
+ .build();
358
+ return { text, keyboard };
359
+ }
360
+ export async function handleFooter(ctx) {
361
+ const keyInfo = getSessionKeyFromCtx(ctx);
362
+ if (!keyInfo)
363
+ return;
364
+ const { chatId, sessionKey } = keyInfo;
365
+ const menu = buildStatusLineMenu(chatId, sessionKey);
366
+ await replyFormatted(ctx, menu.text, {
367
+ reply_markup: { inline_keyboard: menu.keyboard },
368
+ });
369
+ }
370
+ export async function handleFooterCallback(ctx) {
371
+ const keyInfo = getSessionKeyFromCtx(ctx);
372
+ if (!keyInfo)
373
+ return;
374
+ const { chatId, sessionKey } = keyInfo;
375
+ const data = ctx.callbackQuery?.data;
376
+ if (!data || !data.startsWith('footer:'))
377
+ return;
378
+ const action = data.replace('footer:', '');
379
+ let toastText;
380
+ if (action === 'topic:on' || action === 'topic:off') {
381
+ const newState = action === 'topic:on';
382
+ userPreferences.setShowTopicInStatusLine(chatId, newState);
383
+ toastText = `Show topic ${newState ? 'ON' : 'OFF'}`;
384
+ }
385
+ else if (action === 'session:on' || action === 'session:off') {
386
+ const newState = action === 'session:on';
387
+ userPreferences.setShowSessionInStatusLine(chatId, newState);
388
+ toastText = `Show session ${newState ? 'ON' : 'OFF'}`;
389
+ }
390
+ else if (action === 'prompt:on' || action === 'prompt:off') {
391
+ const newState = action === 'prompt:on';
392
+ userPreferences.setShowPromptInStatusLine(chatId, newState);
393
+ toastText = `Show last prompts ${newState ? 'ON' : 'OFF'}`;
394
+ }
395
+ else if (action === 'on' || action === 'off') {
396
+ const newState = action === 'on';
397
+ userPreferences.setShowStatusLine(chatId, newState);
398
+ toastText = `Footer ${newState ? 'ON' : 'OFF'}`;
399
+ }
400
+ else {
401
+ return;
402
+ }
403
+ const menu = buildStatusLineMenu(chatId, sessionKey);
404
+ await ctx.answerCallbackQuery({ text: toastText });
405
+ await editCallbackMessage(ctx, menu.text, {
406
+ reply_markup: { inline_keyboard: menu.keyboard },
407
+ });
408
+ }
409
+ // ── /verbosity ──────────────────────────────────────────────────
410
+ // Pick a verbosity tier (quiet | normal | verbose | debug) for this chat.
411
+ // The tier sets defaults for rendering flags (usage footer, compaction
412
+ // notice, completion ping, untruncated tool inputs). Explicit env vars
413
+ // (CONTEXT_SHOW_USAGE, CONTEXT_NOTIFY_COMPACTION, FULL_TOOL_INPUTS)
414
+ // still win over the tier. "Default" clears the chat-specific pref so the
415
+ // env-level VERBOSITY_DEFAULT applies.
416
+ function buildVerbosityMenu(chatId) {
417
+ const current = getVerbosityLevel(chatId);
418
+ const hasPref = userPreferences.getVerbosity(chatId) !== undefined;
419
+ const keyboard = VERBOSITY_INFO.map((info) => {
420
+ const isCurrent = info.id === current && hasPref;
421
+ const label = isCurrent ? `✓ ${info.label}` : info.label;
422
+ return [{ text: label, callback_data: `verbosity:${info.id}` }];
423
+ });
424
+ const defaultLabel = !hasPref ? `✓ Default (${config.VERBOSITY_DEFAULT})` : `Default (${config.VERBOSITY_DEFAULT})`;
425
+ keyboard.push([{ text: defaultLabel, callback_data: 'verbosity:default' }]);
426
+ const text = new EntityText()
427
+ .add('🎚️ ').bold('Verbosity').newline(2)
428
+ .add('Current: ').bold(current);
429
+ if (!hasPref)
430
+ text.add(' ').italic('(from env default)');
431
+ text.newline(2);
432
+ for (const info of VERBOSITY_INFO) {
433
+ text.add('• ').bold(info.label).add(` - ${info.description}\n`);
434
+ }
435
+ text.add('• ').bold('Default').add(' - Use the env-level setting (').code('VERBOSITY_DEFAULT').add(')');
436
+ return { text: text.build(), keyboard };
437
+ }
438
+ /** "✅ Verbosity reset to env default (**normal**)", for the command and its button. */
439
+ function verbosityResetText() {
440
+ return new EntityText()
441
+ .add('✅ Verbosity reset to env default (').bold(config.VERBOSITY_DEFAULT).add(')')
442
+ .build();
443
+ }
444
+ /** Confirmation for a chosen level, shared by the command and its buttons. */
445
+ function verbositySetText(level) {
446
+ const info = VERBOSITY_INFO.find((l) => l.id === level);
447
+ return new EntityText()
448
+ .add('✅ Verbosity set to ').bold(info?.label ?? level).newline(2)
449
+ .italic(info?.description ?? '')
450
+ .build();
451
+ }
452
+ export async function handleVerbosity(ctx) {
453
+ const keyInfo = getSessionKeyFromCtx(ctx);
454
+ if (!keyInfo)
455
+ return;
456
+ const { chatId } = keyInfo;
457
+ const arg = (ctx.message?.text || '').split(' ').slice(1).join(' ').trim().toLowerCase();
458
+ if (!arg) {
459
+ const { text, keyboard } = buildVerbosityMenu(chatId);
460
+ await replyFormatted(ctx, text, {
461
+ reply_markup: { inline_keyboard: keyboard },
462
+ });
463
+ return;
464
+ }
465
+ if (arg === 'default' || arg === 'reset' || arg === 'auto') {
466
+ userPreferences.clearVerbosity(chatId);
467
+ await replyFormatted(ctx, verbosityResetText());
468
+ return;
469
+ }
470
+ if (!isValidVerbosityLevel(arg)) {
471
+ await replyFormatted(ctx, `❌ Unknown verbosity level "${arg}".\n\nValid: quiet, normal, verbose, debug, default`);
472
+ return;
473
+ }
474
+ userPreferences.setVerbosity(chatId, arg);
475
+ await replyFormatted(ctx, verbositySetText(arg));
476
+ }
477
+ export async function handleVerbosityCallback(ctx) {
478
+ const keyInfo = getSessionKeyFromCtx(ctx);
479
+ if (!keyInfo)
480
+ return;
481
+ const { chatId } = keyInfo;
482
+ const data = ctx.callbackQuery?.data;
483
+ if (!data || !data.startsWith('verbosity:'))
484
+ return;
485
+ const choice = data.replace('verbosity:', '');
486
+ if (choice === 'default') {
487
+ userPreferences.clearVerbosity(chatId);
488
+ await ctx.answerCallbackQuery({ text: 'Verbosity reset to default' });
489
+ await editCallbackMessage(ctx, verbosityResetText());
490
+ return;
491
+ }
492
+ if (!isValidVerbosityLevel(choice)) {
493
+ await ctx.answerCallbackQuery({ text: 'Invalid verbosity level' });
494
+ return;
495
+ }
496
+ const level = choice;
497
+ userPreferences.setVerbosity(chatId, level);
498
+ const info = VERBOSITY_INFO.find((l) => l.id === level);
499
+ await ctx.answerCallbackQuery({ text: `Verbosity: ${info?.label ?? level}` });
500
+ await editCallbackMessage(ctx, verbositySetText(level));
501
+ }
502
+ export async function handleSuggestions(ctx) {
503
+ const keyInfo = getSessionKeyFromCtx(ctx);
504
+ if (!keyInfo)
505
+ return;
506
+ const { sessionKey } = keyInfo;
507
+ const menu = buildSuggestionsMenu(sessionKey);
508
+ await replyFormatted(ctx, menu.text, {
509
+ reply_markup: { inline_keyboard: menu.keyboard },
510
+ });
511
+ }
512
+ export async function handleSuggestionsCallback(ctx) {
513
+ const keyInfo = getSessionKeyFromCtx(ctx);
514
+ if (!keyInfo)
515
+ return;
516
+ const { sessionKey } = keyInfo;
517
+ const data = ctx.callbackQuery?.data;
518
+ if (!data || !data.startsWith('sugg:'))
519
+ return;
520
+ if (data === 'sugg:on') {
521
+ setSuggestionsEnabled(sessionKey, true);
522
+ }
523
+ else if (data === 'sugg:off') {
524
+ setSuggestionsEnabled(sessionKey, false);
525
+ }
526
+ const menu = buildSuggestionsMenu(sessionKey);
527
+ await ctx.answerCallbackQuery();
528
+ try {
529
+ await editCallbackMessage(ctx, menu.text, {
530
+ reply_markup: { inline_keyboard: menu.keyboard },
531
+ });
532
+ }
533
+ catch (error) {
534
+ if (!(error instanceof Error && error.message.includes('message is not modified'))) {
535
+ console.error('[Suggestions] Failed to update menu:', error);
536
+ }
537
+ }
538
+ }
539
+ /**
540
+ * `/mode` — how much claude asks before acting, per chat.
541
+ *
542
+ * The callback prefix is `permmode:` rather than the obvious `mode:`, which
543
+ * belonged to the streaming/wait toggle this command took its name from. A
544
+ * keyboard from that older menu can still be sitting in someone's chat, and
545
+ * its buttons carry `mode:streaming`.
546
+ */
547
+ /**
548
+ * What "Default" actually resolves to for this chat, and why.
549
+ *
550
+ * The menu used to call it "what this bot has always used" — true, and no help
551
+ * at all to someone deciding whether to leave it there. Which mode that is
552
+ * depends on the chat's transport, so the row names the mode and the reason
553
+ * rather than making a person read two files to find out what they already
554
+ * picked.
555
+ */
556
+ function describeTransportDefault() {
557
+ return { label: permissionModeInfo(defaultPermissionMode()).label, why: "Claude Code's own default" };
558
+ }
559
+ function buildPermissionModeMenu(scope) {
560
+ const current = userPreferences.getPermissionMode(scope);
561
+ const fallback = describeTransportDefault();
562
+ const keyboard = PERMISSION_MODES.map((info) => [{
563
+ text: info.id === current ? `✓ ${info.label}` : info.label,
564
+ callback_data: `permmode:${info.id}`,
565
+ }]);
566
+ keyboard.push([{
567
+ text: `${current ? '' : '✓ '}Default — ${fallback.label}`,
568
+ callback_data: 'permmode:default',
569
+ }]);
570
+ const text = new EntityText().add('🔐 ').bold('Permission mode').add('\n\nCurrent: ');
571
+ // Named the same way whether or not it was chosen: the mode a turn runs in
572
+ // is the useful fact, and "Default" alone never told anyone what that was.
573
+ if (current) {
574
+ text.bold(permissionModeInfo(current).label);
575
+ }
576
+ else {
577
+ text.bold(fallback.label).add(' ').italic(`(default — ${fallback.why})`);
578
+ }
579
+ text.newline(2);
580
+ for (const info of PERMISSION_MODES) {
581
+ text.add('• ').bold(info.label).add(` - ${info.description}\n`);
582
+ }
583
+ text.add('• ').bold('Default').add(' - follow the transport, which here means ')
584
+ .bold(fallback.label)
585
+ .newline(2)
586
+ .italic("Takes effect on your next message. Modes that ask will put Claude Code's own prompts in the chat as buttons.");
587
+ return { text: text.build(), keyboard };
588
+ }
589
+ /** Confirmation text shared by the command and its buttons. */
590
+ function permissionModeSetText(id) {
591
+ const info = permissionModeInfo(id);
592
+ return new EntityText()
593
+ .add('✅ Permission mode set to ').bold(info.label).newline(2)
594
+ .italic(info.description)
595
+ .build();
596
+ }
597
+ /** Same, for the reset — which names the mode it reset *to*, not just "default". */
598
+ function permissionModeResetText(scope) {
599
+ const { label, why } = describeTransportDefault();
600
+ return new EntityText()
601
+ .add('✅ Permission mode reset to the transport default: ').bold(label).newline(2)
602
+ .italic(why)
603
+ .build();
604
+ }
605
+ export async function handlePermissionMode(ctx) {
606
+ const keyInfo = getSessionKeyFromCtx(ctx);
607
+ if (!keyInfo)
608
+ return;
609
+ const { sessionKey } = keyInfo;
610
+ const arg = (ctx.message?.text || '').split(' ').slice(1).join(' ').trim();
611
+ if (!arg) {
612
+ const { text, keyboard } = buildPermissionModeMenu(sessionKey);
613
+ await replyFormatted(ctx, text, {
614
+ reply_markup: { inline_keyboard: keyboard },
615
+ });
616
+ return;
617
+ }
618
+ const lower = arg.toLowerCase();
619
+ if (lower === 'default' || lower === 'reset') {
620
+ userPreferences.clearPermissionMode(sessionKey);
621
+ await replyFormatted(ctx, permissionModeResetText(sessionKey));
622
+ return;
623
+ }
624
+ const parsed = parsePermissionModeArg(arg);
625
+ if (!parsed) {
626
+ const valid = new EntityText().add(`❌ Unknown mode "${arg}".\n\nValid: `);
627
+ for (const m of PERMISSION_MODES)
628
+ valid.code(m.id).add(', ');
629
+ await replyFormatted(ctx, valid.code('default').build());
630
+ return;
631
+ }
632
+ userPreferences.setPermissionMode(sessionKey, parsed);
633
+ await replyFormatted(ctx, permissionModeSetText(parsed));
634
+ }
635
+ export async function handlePermissionModeCallback(ctx) {
636
+ const keyInfo = getSessionKeyFromCtx(ctx);
637
+ if (!keyInfo)
638
+ return;
639
+ const { sessionKey } = keyInfo;
640
+ const data = ctx.callbackQuery?.data;
641
+ if (!data || !data.startsWith('permmode:'))
642
+ return;
643
+ const choice = data.replace('permmode:', '');
644
+ if (choice === 'default') {
645
+ userPreferences.clearPermissionMode(sessionKey);
646
+ const { label } = describeTransportDefault();
647
+ await ctx.answerCallbackQuery({ text: `Default: ${label}` });
648
+ await editCallbackMessage(ctx, permissionModeResetText(sessionKey));
649
+ return;
650
+ }
651
+ if (!isPermissionModeId(choice))
652
+ return;
653
+ userPreferences.setPermissionMode(sessionKey, choice);
654
+ await ctx.answerCallbackQuery({ text: `Mode: ${permissionModeInfo(choice).label}` });
655
+ await editCallbackMessage(ctx, permissionModeSetText(choice));
656
+ }
657
+ //# sourceMappingURL=settings.js.map