telecoder 1.2.0 → 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 (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -2,7 +2,7 @@ import { config } from '../config.js';
2
2
  import { hasGuestUsers } from '../utils/admins.js';
3
3
  import { isCheckout } from '../utils/install-mode.js';
4
4
  import { EntityText } from '../telegram/entities.js';
5
- const CLAUDE_COMMANDS = ['plan', 'explore', 'model', 'commands', 'loop', 'resume', 'continue', 'sessions', 'provider'];
5
+ const CLAUDE_COMMANDS = ['model', 'commands', 'resume'];
6
6
  export function parseClaudeCommand(message) {
7
7
  const trimmed = message.trim();
8
8
  // Check if message starts with a slash command
@@ -41,9 +41,7 @@ export function stripCommandBotMention(text) {
41
41
  }
42
42
  /**
43
43
  * True if `text` is the native Claude Code `/compact` slash command (optionally
44
- * with a `@BotName` mention or trailing custom-instructions argument). Single
45
- * source of truth shared by the SDK interceptor (agent.ts) and the PTY provider
46
- * so both agree on what counts as a manual compaction request.
44
+ * with a `@BotName` mention or trailing custom-instructions argument).
47
45
  */
48
46
  export function isNativeCompactCommand(text) {
49
47
  return /^\/compact(?:@\w+)?(?:\s|$)/.test(text.trim());
@@ -64,71 +62,57 @@ export function getAvailableCommands() {
64
62
  {
65
63
  title: 'Claude Commands',
66
64
  commands: [
67
- '• `/plan <task>` - Enter plan mode for complex tasks',
68
- '• `/explore <question>` - Use explore agent for codebase questions',
69
- '• `/loop <task>` - Run iteratively until task complete',
70
65
  '• `/model [name]` - Show or set AI model',
71
66
  "• `/later [text]` - Set an idea aside, and be asked about it after Claude's turn",
72
67
  '• `/steer <text>` - Stop the running turn and send this in its place',
73
- ...(config.CCR_ENABLED ? [`• \`/provider\` - Switch AI provider (Claude / CCR)${adminTag}`] : []),
68
+ '• `/ctrlb` - Move the shell command or subagent Claude is waiting on to the background, as Ctrl+B does in Claude Code',
69
+ ...(config.CCR_ENABLED ? [`• \`/ccr\` - Switch between Claude and CCR${adminTag}`] : []),
74
70
  '• `/commands` - Show this list',
75
71
  ],
76
72
  },
77
73
  {
78
74
  title: 'Session Commands',
79
75
  commands: [
80
- '• `/project <path>` - Set working directory',
81
- '• `/newproject <name>` - Create a new project',
76
+ '• `/dir <path>` - Set working directory',
82
77
  '• `/newbot [project]` - Create a bot for a project, named after it and starting in it',
83
78
  '• `/resume` - Pick from recent sessions to resume',
84
- '• `/continue` - Resume most recent session',
85
- '• `/sessions` - List all sessions',
86
- '• `/teleport` - Move session to terminal (forked)',
79
+ '• `/terminal` - Continue this session in a terminal, as a branch',
87
80
  '• `/clear` - Clear session and start fresh',
88
- '• `/status` - Show current session info',
89
- '• `/fork` - Fork current conversation to another bot',
81
+ '• `/info` - Show current session info',
82
+ '• `/branch` - Branch this conversation into a new thread or another bot',
90
83
  '• `/spinoff <task>` - Split a task off into a new thread, compacted around it (as a reply: from that message)',
84
+ '• `/threaddelete` - Delete this thread and its messages, and end its session',
91
85
  '• `/tree` - Show where this conversation branched, and jump between branches',
92
- '• `/accept` - Accept a pending fork from another bot',
93
- '• `/decline` - Discard a pending fork',
86
+ '• `/branchaccept` - Accept a pending branch from another bot',
87
+ '• `/branchdecline` - Discard a pending branch',
94
88
  ],
95
89
  },
96
90
  {
97
91
  title: 'File Commands',
98
92
  commands: [
99
93
  '• `/file <path>` - Download a file from project',
100
- '• `/telegraph <path>` - View markdown with Instant View',
101
94
  ],
102
95
  },
103
96
  ];
104
- const mediaCommands = [];
105
- if (config.TRANSCRIBE_ENABLED) {
106
- mediaCommands.push('• `/transcribe` - Transcribe audio to text (reply to voice/audio, or ForceReply)');
107
- }
108
- if (mediaCommands.length > 0) {
109
- sections.push({ title: 'Media Commands', commands: mediaCommands });
110
- }
111
97
  sections.push({
112
98
  title: 'Bot Commands',
113
99
  commands: [
114
- '• `/tts` - Toggle voice replies',
115
- '• `/context` - Show Claude context usage',
116
- '• `/cost` - Show usage limits and cost from Claude Code',
100
+ '• `/context` - What fills the context window, as Claude Code reports it',
101
+ '• `/usage` - Show usage limits and cost from Claude Code (alias: `/cost`)',
117
102
  '• `/compact` - Compact the context window (reports the token reduction)',
118
- '• `/botstatus` - Show bot process status',
119
- '• `/version` - Show the running version and whether it\'s the latest',
120
- `• \`/restartbot\` - Restart the bot process${adminTag}`,
103
+ '• `/rewind` - Go back to an earlier prompt: restore the conversation, the code, or both',
104
+ '• `/cc <command>` - Run Claude Code\'s own command of that name, where the bot has one too (`/cc model`)',
105
+ '• `/botstatus` - Show bot process status; answers mid-turn too',
106
+ '• `/botversion` - Show the running version and whether it\'s the latest',
107
+ `• \`/botrestart\` - Restart the bot process${adminTag}`,
121
108
  ...(isCheckout()
122
- ? [`• \`/rebuildbot\` - Rebuild and restart with auto-resume; \`/rebuildbot idle\` waits for each bot to finish first${adminTag}`]
109
+ ? [`• \`/botrebuild\` - Rebuild and restart with auto-resume; \`/botrebuild idle\` waits for each bot to finish first${adminTag}`]
123
110
  : []),
124
- '• `/ping` - Check if bot is responsive',
125
111
  '• `/cancel` - Stop the current request and drop anything queued',
126
112
  '• `/mode` - How much Claude asks before acting',
127
113
  `• \`/autoapprove [30m|off|status]\` - Let the gate approve instead of asking, for a while${approverTag}`,
128
- '• `/streaming` - Toggle streaming / wait replies',
129
114
  '• `/verbosity` - Pick verbosity tier (quiet / normal / verbose / debug)',
130
- '• `/terminalui` - Toggle terminal-style display',
131
- '• `/botname` - Toggle dynamic bot name',
115
+ '• `/botname <name>` - Rename the bot (admins)',
132
116
  '• `/topic <text>` - Set current work topic in bot name',
133
117
  ],
134
118
  });
@@ -139,9 +123,11 @@ export function getAvailableCommands() {
139
123
  '`/security-review`, `/simplify`, `/init`, `/run` and any `.claude/commands/`',
140
124
  'command all work by typing them here.',
141
125
  '',
142
- '⚠️ Where a bot command shares the name, the bot wins — `/loop` and',
143
- '`/schedule` are TeleCoder\'s, not Claude Code\'s. The overlap shifts with',
144
- 'each Claude Code release, so `/projectcommands` reports the current one.',
126
+ '⚠️ Where a bot command shares the name, the bot answers in its own way —',
127
+ '`/model` and `/usage` are TeleCoder\'s pickers and summaries, not Claude',
128
+ 'Code\'s dialogs. `/cc` reaches the one underneath: `/cc model`, `/cc usage`.',
129
+ 'The overlap shifts with each Claude Code release, so `/projectcommands`',
130
+ 'reports the current one.',
145
131
  '',
146
132
  '• `/projectcommands` - List everything this project offers, shadowing included',
147
133
  ],
@@ -173,10 +159,10 @@ export function getAvailableCommands() {
173
159
  * recorded as they register (see the `cmd()` wrapper in `bot.ts`).
174
160
  *
175
161
  * A bot command wins over the native Claude Code command of the same name:
176
- * grammY matches it first and the text never reaches the agent. `/loop` and
177
- * `/schedule` are TeleCoder's own features rather than Claude Code's skills of
178
- * those names, and `/model` answers about the bot's state rather than the
179
- * CLI's. Keeping the list live rather than hand-maintained means
162
+ * grammY matches it first and the text never reaches the agent. The bot takes
163
+ * a Claude Code name only for a command that does the same thing its own way:
164
+ * `/model` answers about the bot's state rather than the CLI's, and `/usage`
165
+ * is a summary rather than the dialog. Keeping the list live rather than hand-maintained means
180
166
  * `/projectcommands` names the shadowed commands accurately — the overlap
181
167
  * shifts with every Claude Code release.
182
168
  *
@@ -186,13 +172,33 @@ export function getAvailableCommands() {
186
172
  * are not shadowed and must not be reported as such.
187
173
  */
188
174
  const registeredBotCommands = new Set();
175
+ const forwardedBotCommands = new Set();
189
176
  export function registerBotCommandName(name, forwardsToAgent = false) {
190
177
  if (forwardsToAgent) {
191
178
  registeredBotCommands.delete(name);
179
+ forwardedBotCommands.add(name);
192
180
  return;
193
181
  }
194
182
  registeredBotCommands.add(name);
195
183
  }
184
+ /**
185
+ * What `/cc <command>` types at Claude Code: `/cc model` is `/model`, and
186
+ * `/cc usage` is `/usage`, arguments and all. Null when no command was named.
187
+ *
188
+ * It is the way to a Claude Code command that a bot command of the same name
189
+ * stands in front of. grammY matches the bot's `/model` before the text can
190
+ * reach the agent, so the name alone can never get there; under `/cc` it is
191
+ * an argument, and goes through as typed. The slash is optional, since
192
+ * `/cc /model` is what half of people will write.
193
+ */
194
+ export function nativeCommandIn(text) {
195
+ const match = /^\/cc(?:@\w+)?\s+\/?([\w:-]+)(\s[\s\S]*)?$/.exec(text.trim());
196
+ return match ? `/${match[1]}${match[2] ?? ''}`.trimEnd() : null;
197
+ }
198
+ /** Names registered only to route into the agent, `/compact` among them. */
199
+ export function getForwardedCommandNames() {
200
+ return forwardedBotCommands;
201
+ }
196
202
  /** Names that shadow a same-named Claude Code command. */
197
203
  export function getBotCommandNames() {
198
204
  return registeredBotCommands;
@@ -31,8 +31,13 @@
31
31
  * The panel scrolls, so only its first screenful is rendered. That is where
32
32
  * the Session block lives, which is why this scrapes it and leaves the rest.
33
33
  */
34
- /** The overlay's top rule. Full-width in practice; 10 is a safe floor. */
35
- const OVERLAY_RULE_RE = /^▔{10,}$/;
34
+ /**
35
+ * The overlay's top rule. Full-width in practice; 10 is a safe floor. `▔` up
36
+ * to claude 2.1.226; from 2.1.311 the same `─` as the input box, which is
37
+ * why the `Session` heading has to follow within HEADING_SEARCH_LINES — the
38
+ * lowest rule on a screen with no panel open is the input box's lower edge.
39
+ */
40
+ const OVERLAY_RULE_RE = /^(?:▔{10,}|─{10,})$/;
36
41
  /** The block's heading, on its own line. */
37
42
  const SESSION_HEADING_RE = /^Session$/;
38
43
  /**
@@ -0,0 +1,5 @@
1
+ const VALID_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
2
+ export function isValidEffortLevel(level) {
3
+ return VALID_EFFORT_LEVELS.includes(level);
4
+ }
5
+ //# sourceMappingURL=effort-level.js.map
@@ -1,23 +1,19 @@
1
1
  /**
2
- * Which marketplace plugins the agent loads.
2
+ * Which marketplace plugins the bot enables on top of the settings claude reads.
3
3
  *
4
- * Claude Code keeps plugin enablement in settings.json under `enabledPlugins`,
5
- * and both transports deliberately decline to read the user's copy of that
6
- * file. The pty spawns with `--setting-sources project,local` so that
7
- * `editorMode: "vim"` cannot turn Enter into a newline and swallow every prompt
8
- * (see pty-provider.ts); the SDK defaults to `settingSources: ['project']` so
9
- * that a machine's worth of MCP servers cannot inflate the tool count into
10
- * deferral. Both are worth keeping — but `enabledPlugins` lives in the file
11
- * they skip, so a plugin enabled in the terminal is simply absent in Telegram,
12
- * and absent silently: a missing skill looks like a model that ignored it.
4
+ * Claude Code keeps plugin enablement in settings.json under `enabledPlugins`.
5
+ * A plugin enabled in the terminal sits in the user's copy of that file, which
6
+ * the pty reads along with the rest of the user setup — unless that setup
7
+ * stays out, as it does on a bot with guests (loadsUserSetup in
8
+ * pty-spawn-config.ts). Then a plugin enabled in the terminal is simply absent
9
+ * in Telegram, and absent silently: a missing skill looks like a model that
10
+ * ignored it.
13
11
  *
14
- * CLAUDE_PLUGINS names the few worth bringing across. It goes in at the *flag*
15
- * tier — `--settings` for the pty, `settings:` for the SDK — which sits above
16
- * project and local in Claude Code's precedence order and merges with them
12
+ * CLAUDE_PLUGINS names the ones to bring across in that case, or to enable for
13
+ * the bot alone. It goes in at the *flag* tier, `--settings`, which sits above
14
+ * the other tiers in Claude Code's precedence order and merges with them
17
15
  * key-by-key, so a project that enables its own plugins keeps them and picks
18
- * these up as well. Nothing else from ~/.claude/settings.json comes with it,
19
- * except the answer to the bypass warning, which the pty carries for itself (see
20
- * buildSettingsJson).
16
+ * these up as well.
21
17
  */
22
18
  import { config } from '../config.js';
23
19
  /**
@@ -49,6 +49,27 @@ export function clearInFlight(sessionKey) {
49
49
  const filtered = all.filter((e) => e.sessionKey !== sessionKey);
50
50
  if (filtered.length !== all.length)
51
51
  writeAll(filtered);
52
+ const after = afterTurn.get(sessionKey);
53
+ if (after) {
54
+ afterTurn.delete(sessionKey);
55
+ try {
56
+ after();
57
+ }
58
+ catch (err) {
59
+ console.warn(`[InFlight] After-turn action for ${sessionKey} failed:`, err instanceof Error ? err.message : err);
60
+ }
61
+ }
62
+ }
63
+ /** One action per session, run when its running turn ends. In memory only. */
64
+ const afterTurn = new Map();
65
+ /**
66
+ * Run `action` once the turn now running in this session ends, before the
67
+ * next queued message starts: for a setting change that needs a fresh claude
68
+ * but shouldn't cut a turn short. A later call for the same session replaces
69
+ * the earlier one, which only ever restarts the same pty.
70
+ */
71
+ export function runAfterTurn(sessionKey, action) {
72
+ afterTurn.set(sessionKey, action);
52
73
  }
53
74
  /** Read all entries and clear the file. Used at startup to surface tasks that
54
75
  * were interrupted by an unexpected exit. */
@@ -22,7 +22,10 @@ import { registerIpcHandler } from './ipc-server.js';
22
22
  import { settleBeforePost } from './monitor-relay.js';
23
23
  import { sessionManager } from './session-manager.js';
24
24
  import { getWorkspaceRoot, isPathWithinRoot } from '../utils/workspace-guard.js';
25
- import { createPendingQuestion, buildAskUserMessageText, buildAskUserKeyboard, buildAskUserExpiredNote, closeExpiredQuestion, questionTimeoutMinutes, } from './ask-user.js';
25
+ import { resolveSendablePath, sendableRefusalMessage } from '../bot/file-access.js';
26
+ import { createPendingQuestion, buildAskUserMessageText, buildAskUserKeyboard, buildAskUserExpiredNote, answerOrHangUp, closeAnsweredQuestion, closeExpiredQuestion, closeWithdrawnQuestion, questionTimeoutMinutes, resolvePendingQuestionWithText, withdrawPendingQuestion, } from './ask-user.js';
27
+ import { resolveAskUserArgs, runAskUserForm } from './ask-user-form.js';
28
+ import { acceptTypedAnswers, acknowledgeTypedAnswer, shownTypedAnswer } from './typed-answer.js';
26
29
  import { createPendingPoll } from './poll-user.js';
27
30
  import { scheduler } from './scheduler.js';
28
31
  import { readLastAssistantTurnText } from './session-jsonl.js';
@@ -93,39 +96,51 @@ async function flushTurnProse(sessionKey, ctx, messageSender) {
93
96
  }
94
97
  }
95
98
  // ── /mcp/ask_user ────────────────────────────────────────────────────
96
- // Long-polling IPC handler: registers a pending question in the same shared
97
- // ask-user registry SDK mode uses, sends a Telegram inline keyboard, and
99
+ // Long-polling IPC handler: registers a pending question in the shared
100
+ // ask-user registry, sends a Telegram inline keyboard, and
98
101
  // awaits the user's button tap. The existing callback-query dispatcher
99
102
  // (handling `q:<id>:<idx>` callback_data) resolves the promise so we can
100
- // return the chosen label to claude. Times out after QUESTION_TIMEOUT_MINUTES via
101
- // createPendingQuestion's default.
102
- registerIpcHandler('/mcp/ask_user', async (turn, body) => {
103
- const question = String(body.question ?? '').trim();
103
+ // return the chosen label to claude, and a message the user sends instead is
104
+ // their answer in their own words (typed-answer.ts). Times out after
105
+ // QUESTION_TIMEOUT_MINUTES via createPendingQuestion's default, and closes
106
+ // early when claude cancels the call.
107
+ registerIpcHandler('/mcp/ask_user', async (turn, body, signal) => {
104
108
  const context = typeof body.context === 'string' ? body.context : undefined;
105
- const rawOptions = Array.isArray(body.options) ? body.options : [];
106
- const options = rawOptions
107
- .map((o) => {
108
- if (!o || typeof o !== 'object')
109
- return null;
110
- const oo = o;
111
- if (typeof oo.label !== 'string' || !oo.label)
112
- return null;
113
- return {
114
- label: oo.label,
115
- description: typeof oo.description === 'string' ? oo.description : undefined,
116
- };
117
- })
118
- .filter((o) => o !== null);
119
- if (!question || options.length < 2) {
120
- return { success: false, message: 'Error: ask_user requires a non-empty question and ≥ 2 options.' };
121
- }
109
+ const asked = resolveAskUserArgs(body);
110
+ if (typeof asked === 'string')
111
+ return { success: false, message: asked };
122
112
  const ctx = getTelegramCtx(turn.options);
123
113
  if (!ctx?.chat?.id) {
124
114
  return { success: false, message: 'Error: no Telegram context available to ask the user.' };
125
115
  }
116
+ // From the session key, not `ctx.message` — a turn started by a tapped
117
+ // button carries a callback-query context with no `message`, which would
118
+ // silently drop the thread and post the question into General.
119
+ const threadId = parseSessionKey(turn.sessionKey).threadId;
120
+ if (asked.form) {
121
+ // Same prose flush as the single question below: what the model wrote
122
+ // to set up the form is still undelivered, and belongs above it.
123
+ const { messageSender } = await import('../telegram/message-sender.js');
124
+ await beforePosting(turn);
125
+ if (!turn.selfStarted)
126
+ await flushTurnProse(turn.sessionKey, ctx, messageSender);
127
+ const message = await runAskUserForm({
128
+ api: ctx.api,
129
+ chatId: ctx.chat.id,
130
+ threadId,
131
+ sessionKey: turn.sessionKey,
132
+ questions: asked.form,
133
+ context,
134
+ signal,
135
+ onPosted: () => messageSender.noteQuestionPosted(ctx, turn.sessionKey),
136
+ onSettled: () => messageSender.noteQuestionAnswered(ctx, turn.sessionKey),
137
+ });
138
+ return message === null ? withdrawnAnswer() : { success: true, message };
139
+ }
140
+ const { question, options } = asked;
126
141
  const optionLabels = options.map((o) => o.label);
127
142
  const { id, promise } = createPendingQuestion(optionLabels, undefined, turn.sessionKey);
128
- // PTY mode holds the turn's prose in the JSONL log until end-of-turn, so
143
+ // The turn's prose stays in the JSONL log until end-of-turn, so
129
144
  // anything the model wrote to set up this question is still undelivered.
130
145
  // Flush it above the buttons; the provider strips it from the end-of-turn
131
146
  // text so it isn't shown twice. Imported lazily to keep this module's eager
@@ -146,10 +161,6 @@ registerIpcHandler('/mcp/ask_user', async (turn, body) => {
146
161
  // Telegram returns 400, grammy throws, the IPC server returns 500, and the
147
162
  // model just sees the tool fail. The bold on labels was a nice-to-have; the
148
163
  // body lists every option in full, keyed by the letter on its button.
149
- // From the session key, not `ctx.message` — a turn started by a tapped
150
- // button carries a callback-query context with no `message`, which would
151
- // silently drop the thread and post the question into General.
152
- const threadId = parseSessionKey(turn.sessionKey).threadId;
153
164
  const sent = await ctx.api.sendMessage(ctx.chat.id, messageText, {
154
165
  reply_markup: { inline_keyboard: keyboard },
155
166
  ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
@@ -158,8 +169,26 @@ registerIpcHandler('/mcp/ask_user', async (turn, body) => {
158
169
  // posted below it rather than edited into the bubble above it, and the
159
170
  // status line says we're blocked on the user.
160
171
  await messageSender.noteQuestionPosted(ctx, turn.sessionKey);
161
- const answer = await promise;
172
+ // A message sent now is an answer in the user's own words (typed-answer.ts).
173
+ const stopTypedAnswers = acceptTypedAnswers({
174
+ sessionKey: turn.sessionKey,
175
+ chatId: ctx.chat.id,
176
+ messageId: sent.message_id,
177
+ take: async (msgCtx, text) => {
178
+ if (resolvePendingQuestionWithText(id, text, msgCtx.from?.id) !== 'resolved')
179
+ return false;
180
+ await acknowledgeTypedAnswer(msgCtx);
181
+ return true;
182
+ },
183
+ });
184
+ const answer = await answerOrHangUp(promise, signal);
185
+ stopTypedAnswers();
162
186
  await messageSender.noteQuestionAnswered(ctx, turn.sessionKey);
187
+ if (answer === 'hung-up') {
188
+ withdrawPendingQuestion(id);
189
+ await closeWithdrawnQuestion(ctx.api, sent, messageText);
190
+ return withdrawnAnswer();
191
+ }
163
192
  if (!answer) {
164
193
  await closeExpiredQuestion(ctx.api, sent, messageText, buildAskUserExpiredNote());
165
194
  return {
@@ -167,8 +196,17 @@ registerIpcHandler('/mcp/ask_user', async (turn, body) => {
167
196
  message: `User did not respond within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment or ask again.`,
168
197
  };
169
198
  }
199
+ if (answer.typed) {
200
+ // A tap closes its question in bot.ts; a typed answer has no tap to do it.
201
+ await closeAnsweredQuestion(ctx.api, sent, messageText, shownTypedAnswer(answer.label));
202
+ return { success: true, message: `User answered in their own words: ${answer.label}` };
203
+ }
170
204
  return { success: true, message: `User selected: ${answer.label}` };
171
205
  });
206
+ /** What claude reads for a question it stopped waiting on, should the reply still reach it. */
207
+ function withdrawnAnswer() {
208
+ return { success: false, message: 'The question was withdrawn before the user answered.' };
209
+ }
172
210
  // ── /mcp/request_secret ──────────────────────────────────────────────
173
211
  // Long-polls like ask_user: the user's answer is a message that
174
212
  // captureSecretMessages takes out of the chat, or a sign-in code for the
@@ -197,7 +235,7 @@ registerIpcHandler('/mcp/request_secret', async (turn, body, signal) => {
197
235
  // ── /mcp/switch_project ──────────────────────────────────────────────
198
236
  // Updates the session's working directory. PtyProvider's _getOrCreateSession
199
237
  // detects the cwd mismatch on the next turn and respawns the pty in the new
200
- // dir — so the switch is logically "happens on next query," same as SDK mode.
238
+ // dir — so the switch is logically "happens on next query".
201
239
  registerIpcHandler('/mcp/switch_project', async (turn, body) => {
202
240
  const projectName = String(body.project_name ?? '').trim();
203
241
  if (!projectName) {
@@ -212,13 +250,9 @@ registerIpcHandler('/mcp/switch_project', async (turn, body) => {
212
250
  return { success: false, message: `Error: Project not found: ${projectName}` };
213
251
  }
214
252
  sessionManager.setWorkingDirectory(turn.sessionKey, targetPath);
215
- // Refresh the Telegram bot display name so it reflects the new project.
216
- // Matches the behavior of /project and the SDK in-process switch_project tool.
217
- const ctx = getTelegramCtx(turn.options);
218
- if (ctx) {
219
- const { clearTopicAndRefreshBotName } = await import('../bot/handlers/command.handler.js');
220
- await clearTopicAndRefreshBotName(ctx, turn.sessionKey);
221
- }
253
+ // A new project is a new topic, as after /dir.
254
+ const { clearTopic } = await import('../bot/handlers/command.handler.js');
255
+ clearTopic(turn.sessionKey);
222
256
  return {
223
257
  success: true,
224
258
  message: `Switched to project: ${projectName} (${targetPath}). The new working directory will take effect on the next query.`,
@@ -239,9 +273,9 @@ registerIpcHandler('/mcp/create_bot', async (turn, body) => {
239
273
  return { success: result.ok, message: result.message };
240
274
  });
241
275
  // ── /mcp/send_file ───────────────────────────────────────────────────
242
- // Sends a file from the bot's filesystem (workspace or /tmp) to the user via
243
- // Telegram. Mirrors the SDK in-process MCP tool in src/claude/mcp-tools.ts but
244
- // routed through IPC so the MCP subprocess can stay out of process.
276
+ // Sends a file from the bot's filesystem to the user via Telegram, under the
277
+ // same rules as /file (bot/file-access.ts) plus /tmp, routed through IPC so
278
+ // the MCP subprocess can stay out of process.
245
279
  registerIpcHandler('/mcp/send_file', async (turn, body) => {
246
280
  const filePath = String(body.file_path ?? '');
247
281
  const caption = typeof body.caption === 'string' && body.caption.length > 0 ? body.caption : undefined;
@@ -253,24 +287,18 @@ registerIpcHandler('/mcp/send_file', async (turn, body) => {
253
287
  if (!ctx) {
254
288
  return { success: false, message: 'Error: No Telegram context for this turn.' };
255
289
  }
256
- // Resolve relative paths against the session's workspace, same as SDK mode.
257
- const resolvedPath = path.isAbsolute(filePath)
258
- ? filePath
259
- : path.resolve(session.workingDirectory, filePath);
260
- // Path must be inside the workspace root or /tmp — anything outside is
261
- // treated as an exfiltration attempt and rejected. Same guards as the
262
- // in-process MCP version.
263
- const workspaceRoot = getWorkspaceRoot();
264
- if (!isPathWithinRoot(workspaceRoot, resolvedPath) && !isPathWithinRoot('/tmp', resolvedPath)) {
265
- return { success: false, message: `Error: File path must be within the workspace (${workspaceRoot}) or /tmp. Access denied.` };
266
- }
267
- if (!fs.existsSync(resolvedPath)) {
268
- return { success: false, message: `Error: File not found: ${path.basename(resolvedPath)}` };
290
+ // The credential denylist for everyone, the chat's project for a guest, the
291
+ // workspace for an admin — judged by who sent the message this turn answers
292
+ // — and /tmp for files claude made to send.
293
+ const resolved = resolveSendablePath(filePath, session.workingDirectory, ctx.from?.id);
294
+ if (!resolved.ok) {
295
+ if (resolved.reason === 'sensitive') {
296
+ console.log(`[MCP] send_file REFUSED credential path for user:${ctx.from?.id ?? 'unknown'}`);
297
+ }
298
+ return { success: false, message: sendableRefusalMessage(resolved.reason, filePath, resolved.root) };
269
299
  }
300
+ const resolvedPath = resolved.path;
270
301
  const stat = fs.statSync(resolvedPath);
271
- if (stat.isDirectory()) {
272
- return { success: false, message: `Error: Path is a directory, not a file: ${path.basename(resolvedPath)}` };
273
- }
274
302
  if (stat.size > TELEGRAM_MAX_FILE_SIZE) {
275
303
  const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);
276
304
  return { success: false, message: `Error: File too large (${sizeMB}MB). Telegram limit is 50MB.` };
@@ -346,7 +374,7 @@ registerIpcHandler('/mcp/poll_user', async (turn, body) => {
346
374
  });
347
375
  // ── /mcp/schedule_loop ───────────────────────────────────────────────
348
376
  // Claude-initiated interval scheduling. Same scheduler as the Telegram-side
349
- // /schedule command — only the entrypoint differs, so caps and persistence
377
+ // /loop command — only the entrypoint differs, so caps and persistence
350
378
  // are uniformly enforced regardless of who created the schedule.
351
379
  registerIpcHandler('/mcp/schedule_loop', async (turn, body) => {
352
380
  const prompt = String(body.prompt ?? '').trim();