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
@@ -1,1458 +0,0 @@
1
- import { query, } from '@anthropic-ai/claude-agent-sdk';
2
- import { randomUUID } from 'crypto';
3
- import * as fs from 'fs';
4
- import { sessionManager } from './session-manager.js';
5
- import { setActiveQuery, clearActiveQuery, isCancelled } from './request-queue.js';
6
- import { config } from '../config.js';
7
- import { AgentWatchdog } from './agent-watchdog.js';
8
- import { hasPendingQuestionForSession } from './ask-user.js';
9
- import { createTeleCoderMcpServer } from './mcp-tools.js';
10
- import { isSubagentTool } from './subagent-tools.js';
11
- import { isNativeCompactCommand } from './command-parser.js';
12
- import { recordAvailableCommands } from './available-commands.js';
13
- import { permissionModeInfo, transportDefaultMode } from './permission-mode.js';
14
- import { enabledPluginsSetting } from './enabled-plugins.js';
15
- import { forgetTurnContext, noteTurnContext, permissionGateHook } from './sdk-permission-gate.js';
16
- import { getSessionTopic, getMsSinceTopicSet } from '../bot/handlers/command/topic-store.js';
17
- import { createAgentTimer, recordMessage, formatDuration, getElapsedMs, getTimingReport, } from '../utils/agent-timer.js';
18
- import { userPreferences } from '../providers/user-preferences.js';
19
- import { hasForeignThinkingSignatures } from './session-jsonl.js';
20
- import { BoundedMap } from '../utils/bounded-map.js';
21
- import { withPendingCarryOver } from './carry-over.js';
22
- import { recordTurnCost, clearSessionCost } from './session-cost.js';
23
- import { resolveBundledClaudeBin, resolveActiveClaudeExecutable } from '../utils/resolve-claude-bin.js';
24
- import { formatCompactionConfirmation } from '../utils/format.js';
25
- import { PromptChannel, QueryFeed, holdQuery, takeHeldQuery, } from './held-query.js';
26
- import { taskTracker } from '../telegram/task-tracker.js';
27
- import { SYSTEM_PROMPT } from './system-prompt.js';
28
- import { stripReasoningSummary } from '../utils/reasoning-summary.js';
29
- import { findModelUsageKey } from './model-catalog.js';
30
- import { ClaudeNotLoggedInError, CLAUDE_NOT_LOGGED_IN_REPLY, isClaudeAuthError } from './claude-auth.js';
31
- const conversationHistory = new BoundedMap(1000);
32
- // Track Claude Code session IDs per session for conversation continuity
33
- const chatSessionIds = new BoundedMap(1000);
34
- // Cache latest usage per session for /context and /status commands
35
- const chatUsageCache = new BoundedMap(1000);
36
- export function getCachedUsage(sessionKey) {
37
- return chatUsageCache.get(sessionKey);
38
- }
39
- /**
40
- * The turn's prompt as a message for the query's input stream (image blocks
41
- * first when there are any).
42
- *
43
- * The stream is a PromptChannel, held open past the reply while a background
44
- * task the query started is still live. Given a finished input, the CLI exits
45
- * about five seconds after the model's last turn and stops any background
46
- * shell still running — a build or a deploy killed halfway, and the model,
47
- * whose turn is over, never hears about it. With the input still open it
48
- * stays up, the shell finishes, and its task-notification starts a sub-turn
49
- * like a Monitor event does.
50
- *
51
- * The uuid is how the prompt's own turn is told apart: the CLI reports it
52
- * queued, started and completed in `command_lifecycle` messages.
53
- */
54
- function userMessage(text, images, sessionId, uuid) {
55
- const content = images.length === 0
56
- ? text
57
- : [
58
- ...images.map((img) => ({
59
- type: 'image',
60
- source: { type: 'base64', media_type: img.mediaType, data: img.data },
61
- })),
62
- { type: 'text', text },
63
- ];
64
- return {
65
- type: 'user',
66
- uuid,
67
- message: { role: 'user', content },
68
- parent_tool_use_id: null,
69
- session_id: sessionId || '',
70
- };
71
- }
72
- /** The state a `command_lifecycle` message reports for the given prompt. */
73
- function promptLifecycle(message, uuid) {
74
- const m = message;
75
- return m.type === 'command_lifecycle' && m.command_uuid === uuid ? m.state : undefined;
76
- }
77
- /**
78
- * The query held open for this chat, if this turn can join it: same Claude
79
- * session, same everything a query is started with but the model and the
80
- * permission mode, which it can be switched to. The prompt is pushed into its
81
- * input. A held query this turn can't join is let go, and waited out — two
82
- * CLIs on one session would each write to its transcript.
83
- */
84
- async function joinHeldQuery(sessionKey, sessionId, fingerprint, model, permissionMode, message) {
85
- const held = takeHeldQuery(sessionKey);
86
- if (!held)
87
- return undefined;
88
- if (held.input.isOpen && held.sessionId === sessionId && held.fingerprint === fingerprint) {
89
- try {
90
- if (held.model !== model) {
91
- await held.query.setModel(model);
92
- held.model = model;
93
- }
94
- if (held.permissionMode !== permissionMode) {
95
- await held.query.setPermissionMode(permissionMode);
96
- held.permissionMode = permissionMode;
97
- }
98
- if (held.input.push(message))
99
- return held;
100
- }
101
- catch (err) {
102
- console.error('[Claude] Could not join the held query:', err);
103
- }
104
- }
105
- logAt('basic', `[Claude] Letting go of the query held for ${[...held.shared.liveTasks].join(', ') || 'nothing'}, which this turn can't join`);
106
- held.input.end();
107
- await Promise.race([held.feed.closed, new Promise((resolve) => setTimeout(resolve, 15_000))]);
108
- return undefined;
109
- }
110
- /** How long an interrupt gets to stop a cancelled turn before the query is closed. */
111
- const CANCEL_GRACE_MS = 10_000;
112
- const LOG_LEVELS = {
113
- off: 0,
114
- basic: 1,
115
- verbose: 2,
116
- trace: 3,
117
- };
118
- function getLogLevel() {
119
- return config.CLAUDE_SDK_LOG_LEVEL;
120
- }
121
- function logAt(level, message, data) {
122
- if (LOG_LEVELS[level] <= LOG_LEVELS[getLogLevel()]) {
123
- if (data !== undefined) {
124
- console.log(message, data);
125
- }
126
- else {
127
- console.log(message);
128
- }
129
- }
130
- }
131
- /**
132
- * Which mode this turn runs in, most specific wins.
133
- *
134
- * `/plan` is a single-turn instruction and beats everything. A mode the chat
135
- * chose beats DANGEROUS_MODE next, because every choice other than bypass is
136
- * the stricter of the two and an explicit choice that a config flag could
137
- * silently override would not be a choice. Having chosen nothing lands on
138
- * `transportDefaultMode`, which is also what /mode reads to name the default
139
- * in the chat — one rule, so the menu cannot describe a mode this returns.
140
- */
141
- function getPermissionMode(command, scope) {
142
- if (command === 'plan') {
143
- return 'plan';
144
- }
145
- const chosen = scope !== undefined ? userPreferences.getPermissionMode(scope) : undefined;
146
- // The SDK and the CLI spell the ask-every-time mode differently; the table
147
- // holds both, and this transport needs `sdk`.
148
- const mode = chosen ?? transportDefaultMode('sdk', config.DANGEROUS_MODE);
149
- return permissionModeInfo(mode).sdk;
150
- }
151
- /**
152
- * Log operations when DANGEROUS_MODE is enabled for security auditing.
153
- */
154
- function logDangerousModeOperation(sessionKey, operation, details) {
155
- if (!config.DANGEROUS_MODE)
156
- return;
157
- const timestamp = new Date().toISOString();
158
- const detailStr = details ? ` — ${details}` : '';
159
- console.log(`[DANGEROUS_MODE] ${timestamp} session:${sessionKey} ${operation}${detailStr}`);
160
- }
161
- /**
162
- * Detect a Claude Max usage-limit throttle from upstream error text and
163
- * extract the reset timestamp when present. Returns undefined for any
164
- * error that isn't a usage-limit signal.
165
- */
166
- function parseThrottle(errorText) {
167
- if (!errorText)
168
- return undefined;
169
- // Patterns observed in Claude Code CLI / Anthropic API throttle messages.
170
- const isUsageLimit = /usage limit/i.test(errorText) ||
171
- /usage_limit_exceeded/i.test(errorText) ||
172
- /rate.?limit/i.test(errorText);
173
- if (!isUsageLimit)
174
- return undefined;
175
- let resetAt;
176
- // ISO-style "resets at 2026-05-12T14:00:00Z"
177
- const iso = errorText.match(/(?:reset(?:s)?\s+at[:\s]+)([0-9T:\-+.Z ]{10,})/i);
178
- if (iso) {
179
- const t = Date.parse(iso[1].trim());
180
- if (!Number.isNaN(t))
181
- resetAt = t;
182
- }
183
- // Unix-seconds "resetAt: 1731412800"
184
- if (resetAt === undefined) {
185
- const ts = errorText.match(/reset(?:At)?[":\s]+(\d{10})\b/i);
186
- if (ts)
187
- resetAt = parseInt(ts[1], 10) * 1000;
188
- }
189
- return { message: errorText.trim(), resetAt };
190
- }
191
- export async function sendToAgent(sessionKey, message, options = {}) {
192
- const { onProgress, onToolStart, onToolEnd, onTaskEvent, onSubTurnResponse, onToolResult, onEditDiff, abortController, command, model, images, executableOverride, providerName } = options;
193
- // Native `/compact` used to be intercepted here and refused as PTY-only.
194
- // It isn't: the CLI runs local slash commands in headless mode too, so a
195
- // `/compact` on a resumed session emits `status: compacting`, then a
196
- // `compact_boundary` carrying the token reduction, and writes the boundary
197
- // into the session JSONL so the next resume picks up the compacted context.
198
- // We forward it like any other prompt and report the outcome below — the
199
- // result message's own text is empty for a manual compact, so the
200
- // confirmation has to be synthesized from the boundary.
201
- const manualCompact = isNativeCompactCommand(message);
202
- // Whoever's turn this is answers for the tool calls the permission gate
203
- // stops from here on, in this query or a held one this turn joins.
204
- noteTurnContext(sessionKey, options.telegramCtx);
205
- async function emitTaskEvent(event) {
206
- try {
207
- await onTaskEvent?.(event);
208
- }
209
- catch (err) {
210
- console.error('[Claude] onTaskEvent handler threw:', err);
211
- }
212
- }
213
- async function emitSubTurnResponse(text) {
214
- try {
215
- await onSubTurnResponse?.(text);
216
- }
217
- catch (err) {
218
- console.error('[Claude] onSubTurnResponse handler threw:', err);
219
- }
220
- }
221
- async function emitToolResult(event) {
222
- try {
223
- await onToolResult?.(event);
224
- }
225
- catch (err) {
226
- console.error('[Claude] onToolResult handler threw:', err);
227
- }
228
- }
229
- async function emitEditDiff(event) {
230
- try {
231
- await onEditDiff?.(event);
232
- }
233
- catch (err) {
234
- console.error('[Claude] onEditDiff handler threw:', err);
235
- }
236
- }
237
- /**
238
- * Extract a readable string from a tool_result.content payload. The SDK
239
- * may deliver content as a plain string, an array of typed blocks
240
- * (text/image/etc.), or rarely something else. Non-text blocks become
241
- * placeholders so the user knows there was a result but it isn't a text
242
- * preview we can render.
243
- */
244
- function extractToolResultText(content) {
245
- if (typeof content === 'string')
246
- return content;
247
- if (!Array.isArray(content))
248
- return '';
249
- const parts = [];
250
- for (const block of content) {
251
- if (!block || typeof block !== 'object')
252
- continue;
253
- const b = block;
254
- if (b.type === 'text' && typeof b.text === 'string') {
255
- parts.push(b.text);
256
- }
257
- else if (b.type === 'image') {
258
- parts.push('[image]');
259
- }
260
- else if (typeof b.type === 'string') {
261
- parts.push(`[${b.type}]`);
262
- }
263
- }
264
- return parts.join('\n');
265
- }
266
- const session = sessionManager.getSession(sessionKey);
267
- if (!session) {
268
- throw new Error('No active session. Use /project to set working directory.');
269
- }
270
- sessionManager.updateActivity(sessionKey, message);
271
- // Clear stale assistant preview from previous query so a mid-task restart
272
- // doesn't show an old response alongside the new prompt
273
- sessionManager.clearLastAssistantPreview(sessionKey);
274
- // Get or initialize conversation history
275
- let history = conversationHistory.get(sessionKey) || [];
276
- // Determine the prompt based on command
277
- let prompt = message;
278
- if (command === 'explore') {
279
- prompt = `Explore the codebase and answer: ${message}`;
280
- }
281
- // Prepend any one-shot carry-over context queued by a provider switch or a
282
- // cross-backend /resume. Plain text, so it's safe to replay on any backend.
283
- prompt = withPendingCarryOver(sessionKey, prompt);
284
- // Add user message to history
285
- history.push({
286
- role: 'user',
287
- content: prompt,
288
- });
289
- let fullText = '';
290
- const toolsUsed = [];
291
- let gotResult = false;
292
- let resultUsage;
293
- // The main thread's latest API call: its usage is the context as it now
294
- // stands, and its model is the one answering. The result's modelUsage can't
295
- // say either — it adds every call of the query together and lists the CLI's
296
- // own Haiku side calls alongside, sometimes first.
297
- let lastMainCall;
298
- let compactionEvent;
299
- // Post-compaction size, kept alongside compactionEvent rather than on it:
300
- // the shared AgentResponse.compaction shape only carries preTokens, and the
301
- // "before → after" confirmation for a manual /compact needs both.
302
- let compactionPostTokens;
303
- // Set when a manual /compact finished without producing a boundary, e.g.
304
- // "Not enough messages to compact." The CLI reports it on the status
305
- // message; the result message text is empty.
306
- let compactError;
307
- let initEvent;
308
- let throttleInfo;
309
- // Background timer that periodically flushes lastAssistantPreview to disk.
310
- // This runs independently of SDK events so that long tool executions (where
311
- // the for-await loop is blocked) still get a recent snapshot saved.
312
- let lastFlushedText = '';
313
- let firstTextFlushed = false;
314
- function flushPreview() {
315
- if (fullText && fullText !== lastFlushedText) {
316
- lastFlushedText = fullText;
317
- const preview = stripReasoningSummary(fullText);
318
- if (preview) {
319
- sessionManager.updateLastAssistantMessage(sessionKey, preview);
320
- }
321
- }
322
- }
323
- const previewFlushTimer = setInterval(flushPreview, 5_000);
324
- // Determine permission mode
325
- const permissionMode = getPermissionMode(command, sessionKey);
326
- // Log in dangerous mode for security auditing
327
- logDangerousModeOperation(sessionKey, 'query', `prompt_length:${message.length} cwd:${session.workingDirectory}`);
328
- // Determine model to use (default to 'opus' to match getModel() default)
329
- const effectiveModel = model || getModel(sessionKey);
330
- // Determine effort level (undefined = SDK default)
331
- const effectiveEffort = getEffort(sessionKey);
332
- // Initialize timer for tracking query duration (watchdog created inside try with controller)
333
- const timer = createAgentTimer();
334
- let watchdog = null;
335
- let silenceTimedOut = false;
336
- let staleToolTimedOut = false;
337
- // The prompt stream stays open while a task this query started is still
338
- // live, and ends once none is — see userMessage. Tasks are counted from
339
- // their task_started to their task_notification, foreground ones included:
340
- // one that is still live when a result arrives is running in the
341
- // background, however it got there. A turn that joins a held query takes
342
- // this over from the turn before.
343
- let shared = { liveTasks: new Set(), waitingOnTasks: false, costSoFar: 0 };
344
- let releaseInput = () => { };
345
- // Set once the reply has gone out while the query stays open: from then on
346
- // this call only reads the query's sub-turns, until the next turn joins it.
347
- let detached = false;
348
- let replied = () => { };
349
- const replyReady = new Promise((resolve) => { replied = resolve; });
350
- // Messages for an already delivered reply have nowhere to go.
351
- const progress = (text) => { if (!detached)
352
- onProgress?.(text); };
353
- const toolStart = (name, input) => { if (!detached)
354
- onToolStart?.(name, input); };
355
- const toolEnd = () => { if (!detached)
356
- onToolEnd?.(); };
357
- // Cache usage for /context and /status commands. A turn's totalCostUsd is
358
- // its own part of the query's total, and the conversation's total is only
359
- // ever the sum kept here.
360
- const recordUsage = (usage) => {
361
- const running = recordTurnCost(sessionKey, usage.totalCostUsd);
362
- usage.sessionCostUsd = running.usd;
363
- usage.sessionCostTurns = running.turns;
364
- chatUsageCache.set(sessionKey, usage);
365
- };
366
- // Foreground shell commands still running. The CLI ends each one at its
367
- // own timeout, so a quiet one is not stuck.
368
- const runningShells = new Set();
369
- // Runs until the query's stream ends, or until the next turn joins it. The
370
- // reply is ready earlier when the query is kept open: see replyReady.
371
- const consume = (async () => {
372
- let reader;
373
- try {
374
- let controller = abortController || new AbortController();
375
- let existingSessionId = chatSessionIds.get(sessionKey) || session.claudeSessionId;
376
- // Cross-backend resume guard. A Claude session created by one provider
377
- // can't be safely resumed by another: DeepSeek-via-CCR mints placeholder
378
- // thinking-block signatures that the real Anthropic API rejects with
379
- // `400 Invalid signature in thinking block`. Switch paths normally fork
380
- // the session for us, but this is the last-resort net for paths that
381
- // didn't (legacy sessions, post-restart in-memory loss). When a mismatch
382
- // is detected we abandon the old session id and start fresh instead.
383
- if (existingSessionId && providerName) {
384
- const owner = session.ownerProvider;
385
- const ownerMismatch = owner !== undefined && owner !== providerName;
386
- // No recorded owner (legacy / restarted): fall back to a content scan,
387
- // but only when resuming on real Anthropic — CCR/DeepSeek ignore sigs.
388
- const poisonedForAnthropic = owner === undefined &&
389
- providerName === 'claude' &&
390
- hasForeignThinkingSignatures(session.workingDirectory, existingSessionId);
391
- if (ownerMismatch || poisonedForAnthropic) {
392
- logAt('basic', `[Claude] Refusing cross-backend resume of ${existingSessionId} ` +
393
- `(owner=${owner ?? 'unknown'}, now=${providerName}${poisonedForAnthropic ? ', foreign thinking signatures' : ''}); starting fresh session.`);
394
- chatSessionIds.delete(sessionKey);
395
- sessionManager.startNewConversation(sessionKey);
396
- existingSessionId = undefined;
397
- }
398
- }
399
- // Log session resume if applicable
400
- if (existingSessionId) {
401
- if (!chatSessionIds.get(sessionKey)) {
402
- chatSessionIds.set(sessionKey, existingSessionId);
403
- }
404
- logAt('basic', `[Claude] Resuming session ${existingSessionId} for session ${sessionKey}`);
405
- }
406
- // The curated set for non-dangerous mode. The Task* tools keep Claude Code's
407
- // task list, which the chat mirrors (telegram/task-list.ts).
408
- const explicitTools = [
409
- 'Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Task', 'Skill',
410
- 'TaskCreate', 'TaskGet', 'TaskList', 'TaskUpdate',
411
- 'WebFetch', 'WebSearch', 'NotebookEdit',
412
- ];
413
- const toolsOption = config.DANGEROUS_MODE
414
- ? { type: 'preset', preset: 'claude_code' }
415
- : explicitTools;
416
- const allowedToolsOption = config.DANGEROUS_MODE
417
- ? undefined
418
- : explicitTools;
419
- // PreCompact hook always registered (logging only — notification sent from compact_boundary message)
420
- const preCompactHook = {
421
- PreCompact: [{
422
- hooks: [async (input) => {
423
- logAt('basic', '[Hook] PreCompact — context is about to be compacted', {
424
- trigger: input.trigger,
425
- customInstructions: input.custom_instructions,
426
- });
427
- return { continue: true };
428
- }],
429
- }],
430
- };
431
- // The permission gate, as the PTY transport runs it — see
432
- // sdk-permission-gate.ts. Always registered, and first: the verbose
433
- // logging below adds its own PreToolUse matcher after it.
434
- const gateHook = permissionGateHook(sessionKey);
435
- const gateHooks = {
436
- PreToolUse: [gateHook],
437
- };
438
- // SDK hook logging: only register the noisy hooks (PreToolUse, PostToolUse, etc.)
439
- // when LOG_AGENT_HOOKS is true. Session lifecycle hooks are always registered.
440
- const verboseHooks = config.LOG_AGENT_HOOKS
441
- ? {
442
- PreToolUse: [gateHook, {
443
- hooks: [async (input) => {
444
- logAt('verbose', '[Hook] PreToolUse', input);
445
- return { continue: true };
446
- }],
447
- }],
448
- PostToolUse: [{
449
- hooks: [async (input) => {
450
- logAt('verbose', '[Hook] PostToolUse', input);
451
- return { continue: true };
452
- }],
453
- }],
454
- PostToolUseFailure: [{
455
- hooks: [async (input) => {
456
- logAt('verbose', '[Hook] PostToolUseFailure', input);
457
- return { continue: true };
458
- }],
459
- }],
460
- PermissionRequest: [{
461
- hooks: [async (input) => {
462
- logAt('verbose', '[Hook] PermissionRequest', input);
463
- return { continue: true };
464
- }],
465
- }],
466
- Notification: [{
467
- hooks: [async (input) => {
468
- logAt('verbose', '[Hook] Notification', input);
469
- return { continue: true };
470
- }],
471
- }],
472
- }
473
- : {};
474
- // Auto-topic reminder: inject a per-turn nudge so the model considers
475
- // updating the topic on every user message. Skip when the topic was just
476
- // set (within the cooldown window) to avoid wasted tokens on follow-ups.
477
- // Also skipped entirely when AUTO_TOPIC_HAIKU is on — the parallel Haiku
478
- // side-call owns topic updates, making the model-driven nudge redundant.
479
- const TOPIC_REMINDER_COOLDOWN_MS = 90_000;
480
- const autoTopicHook = config.DYNAMIC_BOT_NAME && !config.AUTO_TOPIC_HAIKU
481
- ? {
482
- UserPromptSubmit: [{
483
- hooks: [async () => {
484
- const sinceMs = getMsSinceTopicSet(sessionKey);
485
- if (sinceMs !== undefined && sinceMs < TOPIC_REMINDER_COOLDOWN_MS) {
486
- return { continue: true };
487
- }
488
- const currentTopic = getSessionTopic(sessionKey);
489
- const topicLabel = currentTopic ? `"${currentTopic}"` : 'none';
490
- return {
491
- continue: true,
492
- hookSpecificOutput: {
493
- hookEventName: 'UserPromptSubmit',
494
- additionalContext: `[Topic: ${topicLabel}] If user shifted focus, call telecoder_set_topic before replying.`,
495
- },
496
- };
497
- }],
498
- }],
499
- }
500
- : {};
501
- const hooks = LOG_LEVELS[getLogLevel()] >= LOG_LEVELS.verbose
502
- ? {
503
- ...preCompactHook,
504
- ...gateHooks,
505
- ...verboseHooks,
506
- ...autoTopicHook,
507
- SessionStart: [{
508
- hooks: [async (input) => {
509
- logAt('basic', '[Hook] SessionStart', input);
510
- return { continue: true };
511
- }],
512
- }],
513
- SessionEnd: [{
514
- hooks: [async (input) => {
515
- logAt('basic', '[Hook] SessionEnd', input);
516
- return { continue: true };
517
- }],
518
- }],
519
- }
520
- : { ...preCompactHook, ...gateHooks, ...autoTopicHook };
521
- // Validate cwd exists — stale sessions may reference paths from another OS
522
- let cwd = session.workingDirectory;
523
- try {
524
- if (!fs.existsSync(cwd)) {
525
- const fallback = process.env.HOME || process.cwd();
526
- console.warn(`[Claude] Working directory does not exist: ${cwd}, falling back to ${fallback}`);
527
- cwd = fallback;
528
- }
529
- }
530
- catch {
531
- cwd = process.env.HOME || process.cwd();
532
- }
533
- // Create MCP server for TeleCoder tools (if telegramCtx is available)
534
- const mcpServers = {};
535
- if (options.telegramCtx) {
536
- const server = createTeleCoderMcpServer({
537
- telegramCtx: options.telegramCtx,
538
- sessionKey,
539
- });
540
- mcpServers['telecoder-tools'] = server;
541
- }
542
- // Resolved once, because two things need it: the SDK, and the command
543
- // cache below — whose entries are only valid for the binary that reported
544
- // them. Undefined means "let the SDK pick", which is its own auto-detect.
545
- const sdkExecutable = executableOverride
546
- ?? (config.CLAUDE_USE_BUNDLED_EXECUTABLE
547
- ? resolveBundledClaudeBin()
548
- : config.CLAUDE_EXECUTABLE_PATH);
549
- const enabledPlugins = enabledPluginsSetting();
550
- const queryOptions = {
551
- cwd,
552
- tools: toolsOption,
553
- ...(allowedToolsOption ? { allowedTools: allowedToolsOption } : {}),
554
- permissionMode,
555
- abortController: controller,
556
- systemPrompt: {
557
- type: 'preset',
558
- preset: 'claude_code',
559
- append: SYSTEM_PROMPT,
560
- },
561
- settingSources: (config.CLAUDE_SDK_LOAD_USER_SETTINGS
562
- ? ['project', 'user']
563
- : ['project']),
564
- // The pty's --settings equivalent, and here for the same reason: the
565
- // sources above skip ~/.claude/settings.json, so CLAUDE_PLUGINS is what
566
- // carries a marketplace plugin into the session. Flag tier, so it merges
567
- // with the project's own enabledPlugins rather than replacing them.
568
- ...(enabledPlugins ? { settings: { enabledPlugins } } : {}),
569
- model: effectiveModel,
570
- ...(effectiveEffort ? { effort: effectiveEffort } : {}),
571
- resume: existingSessionId,
572
- ...(permissionMode === 'bypassPermissions' ? { allowDangerouslySkipPermissions: true } : {}),
573
- ...(sdkExecutable ? { pathToClaudeCodeExecutable: sdkExecutable } : {}),
574
- // Text deltas, so the reply can be shown while it is being written.
575
- includePartialMessages: true,
576
- hooks,
577
- ...(Object.keys(mcpServers).length > 0 ? { mcpServers } : {}),
578
- stderr: (data) => {
579
- console.error('[Claude stderr]:', data);
580
- },
581
- };
582
- const promptUuid = randomUUID();
583
- const promptMessage = userMessage(prompt, images ?? [], existingSessionId, promptUuid);
584
- // What a turn has to agree on with a held query to join it.
585
- const fingerprint = JSON.stringify([
586
- cwd, sdkExecutable ?? null, providerName ?? null, effectiveEffort ?? null, enabledPlugins ?? null,
587
- queryOptions.settingSources, Object.keys(mcpServers), Object.keys(hooks ?? {}), toolsOption,
588
- ]);
589
- let response;
590
- let input;
591
- let feed;
592
- const held = await joinHeldQuery(sessionKey, existingSessionId, fingerprint, effectiveModel, permissionMode, promptMessage);
593
- if (held) {
594
- ({ query: response, input, feed, shared, controller } = held);
595
- const heldController = held.controller;
596
- abortController?.signal.addEventListener('abort', () => heldController.abort(), { once: true });
597
- // The turn before may still be answering a task's notification; this
598
- // one's messages start where its prompt does.
599
- reader = feed.attach((m) => {
600
- const state = promptLifecycle(m, promptUuid);
601
- return state !== undefined && state !== 'queued';
602
- });
603
- logAt('basic', `[Claude] Joining the query kept open for ${[...shared.liveTasks].join(', ') || 'background work'}`);
604
- }
605
- else {
606
- input = new PromptChannel(promptMessage);
607
- const sdkQuery = query({ prompt: input, options: queryOptions });
608
- response = sdkQuery;
609
- feed = new QueryFeed(sdkQuery, () => sdkQuery.close());
610
- reader = feed.attach();
611
- }
612
- releaseInput = () => input.end();
613
- const heldModel = held?.model ?? effectiveModel;
614
- // The reply goes out now; the query stays open for its background work,
615
- // for the next turn to join.
616
- const detach = () => {
617
- detached = true;
618
- clearInterval(previewFlushTimer);
619
- holdQuery(sessionKey, {
620
- query: response, controller, input, feed, shared,
621
- sessionId: chatSessionIds.get(sessionKey),
622
- model: heldModel,
623
- permissionMode,
624
- fingerprint,
625
- });
626
- replied();
627
- };
628
- // Store the Query object so /cancel can call interrupt()
629
- setActiveQuery(sessionKey, response);
630
- // Initialize watchdog for long-running query monitoring
631
- watchdog = config.AGENT_WATCHDOG_ENABLED
632
- ? new AgentWatchdog({
633
- chatId: sessionKey,
634
- warnAfterSeconds: config.AGENT_WATCHDOG_WARN_SECONDS,
635
- logIntervalSeconds: config.AGENT_WATCHDOG_LOG_SECONDS,
636
- timeoutMs: config.AGENT_QUERY_TIMEOUT_MS > 0 ? config.AGENT_QUERY_TIMEOUT_MS : undefined,
637
- onWarning: (sinceMsg, total) => {
638
- logAt('basic', `[Claude] WATCHDOG: No messages for ${formatDuration(sinceMsg)} (total: ${formatDuration(total)}), session:${sessionKey}`);
639
- },
640
- onTimeout: () => {
641
- logAt('basic', `[Claude] WATCHDOG: Query timeout reached, aborting session:${sessionKey}`);
642
- controller.abort();
643
- },
644
- silenceTimeoutMs: config.AGENT_SILENCE_TIMEOUT_MS > 0 ? config.AGENT_SILENCE_TIMEOUT_MS : undefined,
645
- onSilenceTimeout: () => {
646
- logAt('basic', `[Claude] WATCHDOG: Silence timeout — no messages for ${formatDuration(config.AGENT_SILENCE_TIMEOUT_MS)}, force-closing query for session:${sessionKey}`);
647
- silenceTimedOut = true;
648
- response.close();
649
- controller.abort();
650
- },
651
- staleToolTimeoutMs: config.AGENT_STALE_TOOL_TIMEOUT_MS > 0 ? config.AGENT_STALE_TOOL_TIMEOUT_MS : undefined,
652
- onStaleToolTimeout: () => {
653
- logAt('basic', `[Claude] WATCHDOG: Stale tool timeout — only heartbeats for ${formatDuration(config.AGENT_STALE_TOOL_TIMEOUT_MS)}, force-closing query for session:${sessionKey}`);
654
- staleToolTimedOut = true;
655
- silenceTimedOut = true; // preserve session for recovery
656
- response.close();
657
- controller.abort();
658
- },
659
- // Waiting on a quiet background shell is no stall: nothing is
660
- // expected until it ends.
661
- shouldPauseTimeouts: () => hasPendingQuestionForSession(sessionKey) || shared.waitingOnTasks,
662
- shouldPauseStaleTool: () => runningShells.size > 0,
663
- })
664
- : null;
665
- watchdog?.start();
666
- // Track whether we've captured a plan from spontaneous plan mode
667
- let planCaptured = false;
668
- // Track tool_use_ids that were launched with run_in_background:true,
669
- // so the matching task_started event can be marked as backgrounded.
670
- // (task_updated.is_backgrounded only fires on transitions, not initial state.)
671
- const backgroundedToolUseIds = new Set();
672
- // Track tool_use_id → tool name so we can label tool_result blocks that
673
- // arrive later on user messages. Tools whose results we never want to
674
- // surface (the Task* list tools have a dedicated card; topic/ask_user
675
- // return noise)
676
- // are kept in `silentToolUseIds` and skipped at emit-time.
677
- const toolUseIdToName = new Map();
678
- const toolUseIdToInput = new Map();
679
- const silentToolUseIds = new Set();
680
- const SILENT_TOOL_NAMES = new Set([
681
- 'TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet',
682
- 'mcp__telecoder-tools__telecoder_set_topic',
683
- 'mcp__telecoder-tools__telecoder_ask_user',
684
- ]);
685
- const editDiffInputs = new Map();
686
- // Monitor tool calls — same wire shape as other backgrounded tasks but
687
- // we want to render their lifecycle as "📡 Monitor event/armed/ended"
688
- // instead of the generic "✅ Background task" wording.
689
- const monitorToolUseIds = new Set();
690
- // Per-turn state for surfacing SDK-driven sub-turns as their own
691
- // Telegram messages:
692
- // - The first SDK init corresponds to the user's actual message —
693
- // this is the main turn that owns the streaming bubble.
694
- // - Subsequent inits are SDK-driven sub-turns: monitor event
695
- // deliveries, post-task_notification commentary, etc.
696
- // - When the query has launched a backgrounded task, every sub-turn's
697
- // text response gets posted as its own ctx.reply rather than
698
- // edited into the streaming bubble. Otherwise post-stream
699
- // commentary would land at the top of the chat (overwriting the
700
- // user-facing reply) instead of chronologically at the bottom.
701
- let initCount = 0;
702
- let hadBackgroundedTask = false;
703
- let inSubTurn = false;
704
- let subTurnBuffer = '';
705
- // Insert a visual separator between text blocks that had a tool_use
706
- // between them, so the streaming bubble preserves the model's natural
707
- // beats. The TUI gets this for free because tool calls render inline;
708
- // we send tool calls to the action log, so without this the narration
709
- // collapses into one wall of text.
710
- let pendingTextSeparator = false;
711
- // The text block being streamed right now, from its deltas. The finished
712
- // block arrives in the assistant message and replaces it in fullText.
713
- let partialText = '';
714
- // Whether the CLI has reported on this prompt's own turn yet. On resume it
715
- // can answer something queued ahead of the prompt first — the notice for
716
- // a task the session's previous process left behind — with a result of
717
- // its own. That result isn't this turn's: ending the input at it, as
718
- // nothing seemed to be running, ended it before the prompt was even read,
719
- // and the CLI stopped this turn's background work five seconds after its
720
- // reply.
721
- let promptQueued = false;
722
- let promptStarted = false;
723
- // Set at a result after which the query is kept open, and acted on once
724
- // the result is fully handled.
725
- let holdAfterResult = false;
726
- // When this turn's message loop first saw the /cancel flag.
727
- let cancelSeenAt;
728
- // Process response messages
729
- for await (const responseMessage of reader.messages) {
730
- // Record activity for watchdog
731
- recordMessage(timer);
732
- watchdog?.recordActivity(responseMessage.type);
733
- const lifecycle = promptLifecycle(responseMessage, promptUuid);
734
- if (lifecycle !== undefined) {
735
- promptQueued = true;
736
- if (lifecycle !== 'queued')
737
- promptStarted = true;
738
- continue;
739
- }
740
- // If /cancel was issued but interrupt() failed to stop the turn,
741
- // force-abort on a later heartbeat so we don't hang forever. The
742
- // interrupt gets a grace period first: closing the query at the first
743
- // message after it — usually the interrupted turn's own result — would
744
- // also stop the background tasks it is being kept open for.
745
- if (!controller.signal.aborted && !gotResult && !detached && isCancelled(sessionKey)) {
746
- cancelSeenAt ??= Date.now();
747
- if (Date.now() - cancelSeenAt >= CANCEL_GRACE_MS) {
748
- logAt('basic', `[Claude] Cancel flag detected on heartbeat, force-closing query for session:${sessionKey}`);
749
- response.close();
750
- controller.abort();
751
- }
752
- }
753
- // Check for abort
754
- if (controller.signal.aborted) {
755
- watchdog?.stop();
756
- fullText = isCancelled(sessionKey)
757
- ? '🛑 Request cancelled.'
758
- : staleToolTimedOut
759
- ? `⏱️ A tool appears stuck (no progress for ${formatDuration(config.AGENT_STALE_TOOL_TIMEOUT_MS)}). Your session has been preserved — send another message to continue.`
760
- : silenceTimedOut
761
- ? `⏱️ The query stalled (no activity for ${formatDuration(config.AGENT_SILENCE_TIMEOUT_MS)}). Your session has been preserved — send another message to continue.`
762
- : '⏱️ Request timed out — the query took too long and was automatically stopped. Try a simpler prompt or break it into smaller steps.';
763
- break;
764
- }
765
- logAt('trace', `[Claude] [${formatDuration(getElapsedMs(timer))}] Message: ${responseMessage.type}`);
766
- if (responseMessage.type === 'assistant') {
767
- // The CLI's answer when it has no credentials is a synthetic
768
- // assistant message, "Not logged in · Please run /login". Stop here
769
- // rather than stream that into the chat as if it were the reply.
770
- if (responseMessage.error === 'authentication_failed') {
771
- throw new ClaudeNotLoggedInError();
772
- }
773
- logAt('verbose', '[Claude] Assistant content blocks:', responseMessage.message.content.length);
774
- if (responseMessage.parent_tool_use_id === null && responseMessage.message.usage) {
775
- lastMainCall = {
776
- model: responseMessage.message.model,
777
- usage: responseMessage.message.usage,
778
- };
779
- }
780
- for (const block of responseMessage.message.content) {
781
- logAt('trace', '[Claude] Block type:', block.type);
782
- if (block.type === 'text') {
783
- // Sub-turns (monitor events, post-completion commentary):
784
- // buffer the model's text and post it as its own chat message
785
- // at result-time instead of editing it into the main streaming
786
- // bubble (which would visually overwrite the user-facing reply
787
- // and surface the new text at the top of the chat instead of
788
- // chronologically at the bottom).
789
- if (inSubTurn) {
790
- subTurnBuffer += block.text;
791
- }
792
- else {
793
- if (pendingTextSeparator && fullText.length > 0) {
794
- fullText += '\n\n───\n\n';
795
- }
796
- pendingTextSeparator = false;
797
- partialText = '';
798
- fullText += block.text;
799
- progress(fullText);
800
- // Flush immediately on first text so early restarts have something
801
- if (!firstTextFlushed) {
802
- firstTextFlushed = true;
803
- flushPreview();
804
- }
805
- }
806
- }
807
- else if (block.type === 'tool_use') {
808
- pendingTextSeparator = true;
809
- const toolInput = 'input' in block ? block.input : {};
810
- const inputSummary = toolInput.command
811
- ? String(toolInput.command).substring(0, 150)
812
- : toolInput.pattern
813
- ? String(toolInput.pattern)
814
- : toolInput.file_path
815
- ? String(toolInput.file_path)
816
- : '';
817
- logAt('verbose', `[Claude] [${formatDuration(getElapsedMs(timer))}] Tool: ${block.name}${inputSummary ? ` → ${inputSummary}` : ''}`);
818
- toolsUsed.push(block.name);
819
- // Remember tool_use_ids launched as background tasks so we can
820
- // stamp the matching task_started event with isBackgrounded:true.
821
- // Monitor is inherently a streaming subscription (model isn't
822
- // blocked on it) so treat it as backgrounded too.
823
- const isMonitorCall = block.name === 'Monitor';
824
- const isBackgroundedToolCall = toolInput.run_in_background === true || isMonitorCall;
825
- if ('id' in block && typeof block.id === 'string') {
826
- toolUseIdToName.set(block.id, block.name);
827
- toolUseIdToInput.set(block.id, toolInput);
828
- if ((block.name === 'Bash' || block.name === 'PowerShell') && !isBackgroundedToolCall) {
829
- runningShells.add(block.id);
830
- }
831
- if (SILENT_TOOL_NAMES.has(block.name) || isBackgroundedToolCall) {
832
- // Backgrounded tasks return a "running in the background"
833
- // placeholder; the real outcome surfaces via task_notification.
834
- silentToolUseIds.add(block.id);
835
- }
836
- if ((block.name === 'Edit' || block.name === 'Write')
837
- && typeof toolInput.file_path === 'string') {
838
- const newString = block.name === 'Edit'
839
- ? (typeof toolInput.new_string === 'string' ? toolInput.new_string : undefined)
840
- : (typeof toolInput.content === 'string' ? toolInput.content : undefined);
841
- if (typeof newString === 'string') {
842
- editDiffInputs.set(block.id, {
843
- toolName: block.name,
844
- filePath: toolInput.file_path,
845
- oldString: block.name === 'Edit' && typeof toolInput.old_string === 'string'
846
- ? toolInput.old_string
847
- : undefined,
848
- newString,
849
- });
850
- }
851
- }
852
- }
853
- if (isBackgroundedToolCall && 'id' in block && typeof block.id === 'string') {
854
- backgroundedToolUseIds.add(block.id);
855
- if (isMonitorCall)
856
- monitorToolUseIds.add(block.id);
857
- logAt('verbose', `[Claude] BACKGROUND TASK LAUNCH: tool=${block.name} tool_use_id=${block.id}`);
858
- }
859
- // Special logging for the subagent tool (Task/Agent) - always log at basic level
860
- if (isSubagentTool(block.name)) {
861
- const taskDesc = toolInput.description || toolInput.prompt || 'unnamed task';
862
- const subagentType = toolInput.subagent_type || 'unknown';
863
- logAt('basic', `[Claude] SUBAGENT START: ${subagentType} — ${String(taskDesc).substring(0, 100)}`);
864
- }
865
- // Capture plan content from spontaneous plan mode (Write to ~/.claude/plans/)
866
- if (!planCaptured && block.name === 'Write'
867
- && typeof toolInput.file_path === 'string'
868
- && toolInput.file_path.includes('/.claude/plans/')
869
- && typeof toolInput.content === 'string') {
870
- planCaptured = true;
871
- const planSection = '📋 **Plan**\n\n' + toolInput.content + '\n\n---\n\n';
872
- fullText = planSection + fullText;
873
- progress(fullText);
874
- logAt('basic', `[Claude] Captured plan from ${toolInput.file_path}`);
875
- }
876
- // Notify tool start for terminal UI — but skip backgrounded
877
- // tool calls. Their placeholder result returns immediately, so
878
- // showing them as the active foreground operation is misleading.
879
- // The streaming UI's footer represents them instead.
880
- if (!isBackgroundedToolCall) {
881
- toolStart(block.name, toolInput);
882
- }
883
- }
884
- }
885
- }
886
- else if (responseMessage.type === 'system') {
887
- if (responseMessage.subtype === 'compact_boundary') {
888
- const cbMsg = responseMessage;
889
- compactionEvent = {
890
- trigger: cbMsg.compact_metadata.trigger,
891
- preTokens: cbMsg.compact_metadata.pre_tokens,
892
- };
893
- compactionPostTokens = cbMsg.compact_metadata.post_tokens;
894
- logAt('basic', `[Claude] COMPACTION: trigger=${cbMsg.compact_metadata.trigger}, pre_tokens=${cbMsg.compact_metadata.pre_tokens}, post_tokens=${cbMsg.compact_metadata.post_tokens ?? '?'}`);
895
- }
896
- else if (responseMessage.subtype === 'init') {
897
- const sysMsg = responseMessage;
898
- initEvent = {
899
- model: sysMsg.model,
900
- sessionId: sysMsg.session_id,
901
- };
902
- // Store session ID early so it's available for recovery if the query hangs
903
- chatSessionIds.set(sessionKey, sysMsg.session_id);
904
- sessionManager.setClaudeSessionId(sessionKey, sysMsg.session_id, providerName);
905
- logAt('basic', `[Claude] SESSION INIT: model=${sysMsg.model}, session=${sysMsg.session_id}`);
906
- // The init message is the only in-band source for what slash
907
- // commands and skills this working directory actually has —
908
- // built-ins, plugin commands and `.claude/commands/` alike. Cache
909
- // it so /projectcommands can list them without paying for a probe.
910
- recordAvailableCommands(sysMsg.cwd, sdkExecutable ?? resolveActiveClaudeExecutable(), sysMsg.slash_commands, sysMsg.skills);
911
- // Detect SDK-driven sub-turns. The first init in a query is the
912
- // user's own turn (owns the streaming bubble). Subsequent inits
913
- // are sub-turns (monitor events, post-completion commentary).
914
- // We only redirect sub-turn text to a fresh ctx.reply when this
915
- // query actually launched a backgrounded task — otherwise normal
916
- // foreground subagent inits would be wrongly suppressed.
917
- initCount++;
918
- shared.waitingOnTasks = false;
919
- inSubTurn = detached || (initCount > 1 && hadBackgroundedTask);
920
- subTurnBuffer = '';
921
- }
922
- else if (responseMessage.subtype === 'status') {
923
- const statusMsg = responseMessage;
924
- if (statusMsg.status === 'compacting') {
925
- logAt('basic', '[Claude] STATUS: compacting in progress');
926
- }
927
- // A finished compaction reports its outcome on a second status
928
- // message with status: null. On failure the reason lives here and
929
- // nowhere else — the boundary is never written and the result text
930
- // is empty, so without this a failed /compact answers with silence.
931
- if (statusMsg.compact_result === 'failed') {
932
- compactError = statusMsg.compact_error || 'compaction failed';
933
- logAt('basic', `[Claude] COMPACTION FAILED: ${compactError}`);
934
- }
935
- }
936
- else if (responseMessage.subtype === 'local_command_output') {
937
- // Output from a slash command the CLI ran locally rather than
938
- // sending to the model. Most locally-handled commands answer with a
939
- // synthetic assistant message (which the assistant branch above
940
- // already collects); this subtype is the other shape they can take,
941
- // and dropping it would answer the user with an empty turn.
942
- const localMsg = responseMessage;
943
- if (localMsg.content) {
944
- if (pendingTextSeparator && fullText.length > 0)
945
- fullText += '\n\n───\n\n';
946
- pendingTextSeparator = false;
947
- fullText += localMsg.content;
948
- progress(fullText);
949
- logAt('verbose', `[Claude] LOCAL COMMAND OUTPUT: ${localMsg.content.length} chars`);
950
- }
951
- }
952
- else if (responseMessage.subtype === 'task_started') {
953
- const m = responseMessage;
954
- const isBackgrounded = m.tool_use_id ? backgroundedToolUseIds.has(m.tool_use_id) : false;
955
- const isMonitor = m.tool_use_id ? monitorToolUseIds.has(m.tool_use_id) : false;
956
- // Override task_type with 'monitor_mcp' for Monitor tool calls.
957
- // The SDK's actual task_type value isn't part of the public type
958
- // contract, so we tag based on the launching tool name instead.
959
- const taskType = isMonitor ? 'monitor_mcp' : m.task_type;
960
- if (isBackgrounded)
961
- hadBackgroundedTask = true;
962
- shared.liveTasks.add(m.task_id);
963
- logAt('verbose', `[Claude] TASK STARTED: ${m.task_id} — ${m.description} backgrounded=${isBackgrounded} taskType=${taskType ?? '?'}`);
964
- await emitTaskEvent({
965
- type: 'started',
966
- taskId: m.task_id,
967
- description: m.description,
968
- toolUseId: m.tool_use_id,
969
- taskType,
970
- workflowName: m.workflow_name,
971
- skipTranscript: m.skip_transcript,
972
- isBackgrounded,
973
- });
974
- }
975
- else if (responseMessage.subtype === 'task_progress') {
976
- const m = responseMessage;
977
- logAt('trace', `[Claude] TASK PROGRESS: ${m.task_id} — ${m.last_tool_name ?? '?'}`);
978
- await emitTaskEvent({
979
- type: 'progress',
980
- taskId: m.task_id,
981
- description: m.description,
982
- lastToolName: m.last_tool_name,
983
- summary: m.summary,
984
- usage: m.usage ? {
985
- totalTokens: m.usage.total_tokens,
986
- toolUses: m.usage.tool_uses,
987
- durationMs: m.usage.duration_ms,
988
- } : undefined,
989
- });
990
- }
991
- else if (responseMessage.subtype === 'task_updated') {
992
- const m = responseMessage;
993
- logAt('verbose', `[Claude] TASK UPDATED: ${m.task_id} — status=${m.patch.status ?? '?'} backgrounded=${m.patch.is_backgrounded ?? '?'}`);
994
- // A shell moved to the background partway through only says so here.
995
- if (m.patch.is_backgrounded)
996
- hadBackgroundedTask = true;
997
- await emitTaskEvent({
998
- type: 'updated',
999
- taskId: m.task_id,
1000
- status: m.patch.status,
1001
- description: m.patch.description,
1002
- isBackgrounded: m.patch.is_backgrounded,
1003
- error: m.patch.error,
1004
- endTime: m.patch.end_time,
1005
- });
1006
- }
1007
- else if (responseMessage.subtype === 'task_notification') {
1008
- const m = responseMessage;
1009
- logAt('basic', `[Claude] TASK NOTIFICATION: ${m.task_id} — ${m.status}`);
1010
- shared.liveTasks.delete(m.task_id);
1011
- // Nothing left to wait for. The CLI still answers this notification
1012
- // before it exits, the way it did with a string prompt.
1013
- if (shared.waitingOnTasks && shared.liveTasks.size === 0)
1014
- releaseInput();
1015
- await emitTaskEvent({
1016
- type: 'notification',
1017
- taskId: m.task_id,
1018
- status: m.status,
1019
- outputFile: m.output_file,
1020
- summary: m.summary,
1021
- usage: m.usage ? {
1022
- totalTokens: m.usage.total_tokens,
1023
- toolUses: m.usage.tool_uses,
1024
- durationMs: m.usage.duration_ms,
1025
- } : undefined,
1026
- });
1027
- }
1028
- else {
1029
- logAt('verbose', `[Claude] System: ${responseMessage.subtype ?? 'unknown'}`, responseMessage);
1030
- }
1031
- }
1032
- else if (responseMessage.type === 'user') {
1033
- // User messages carry tool_result blocks for tools the agent just ran.
1034
- // Surface them via onToolResult so the bot can show truncated previews
1035
- // when verbosity is verbose or higher. Synthetic/replay messages are
1036
- // ignored to avoid duplicating results during resumed sessions.
1037
- const isSynthetic = responseMessage.isSynthetic === true;
1038
- const msgContent = responseMessage.message?.content;
1039
- if (!isSynthetic && Array.isArray(msgContent)) {
1040
- for (const block of msgContent) {
1041
- if (!block || typeof block !== 'object')
1042
- continue;
1043
- const b = block;
1044
- if (b.type !== 'tool_result' || typeof b.tool_use_id !== 'string')
1045
- continue;
1046
- runningShells.delete(b.tool_use_id);
1047
- if (silentToolUseIds.has(b.tool_use_id))
1048
- continue;
1049
- const isError = b.is_error === true;
1050
- // Successful Edit/Write: render the captured before/after content
1051
- // as a diff instead of the generic "File edited successfully" reply.
1052
- // Errors still fall through to the normal tool_result path so the
1053
- // failure reason surfaces to the user.
1054
- const diffInput = editDiffInputs.get(b.tool_use_id);
1055
- if (diffInput && !isError) {
1056
- await emitEditDiff({
1057
- toolUseId: b.tool_use_id,
1058
- toolName: diffInput.toolName,
1059
- filePath: diffInput.filePath,
1060
- oldString: diffInput.oldString,
1061
- newString: diffInput.newString,
1062
- });
1063
- continue;
1064
- }
1065
- const text = extractToolResultText(b.content);
1066
- await emitToolResult({
1067
- toolUseId: b.tool_use_id,
1068
- toolName: toolUseIdToName.get(b.tool_use_id),
1069
- input: toolUseIdToInput.get(b.tool_use_id),
1070
- content: text,
1071
- isError,
1072
- });
1073
- }
1074
- }
1075
- }
1076
- else if (responseMessage.type === 'tool_progress') {
1077
- logAt('verbose', `[Claude] Tool progress: ${responseMessage.tool_name}`, responseMessage);
1078
- }
1079
- else if (responseMessage.type === 'tool_use_summary') {
1080
- logAt('verbose', '[Claude] Tool use summary', responseMessage);
1081
- // Notify tool end for terminal UI (summary doesn't include tool name)
1082
- toolEnd();
1083
- }
1084
- else if (responseMessage.type === 'auth_status') {
1085
- logAt('basic', '[Claude] Auth status', responseMessage);
1086
- }
1087
- else if (responseMessage.type === 'stream_event') {
1088
- logAt('trace', '[Claude] Stream event', responseMessage.event);
1089
- // The main thread's text as it is typed; a sub-agent's and a sub-turn's
1090
- // are not part of the reply.
1091
- const event = responseMessage.event;
1092
- if (!inSubTurn && responseMessage.parent_tool_use_id === null) {
1093
- if (event.type === 'content_block_start') {
1094
- partialText = '';
1095
- }
1096
- else if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
1097
- partialText += event.delta.text;
1098
- const separator = pendingTextSeparator && fullText.length > 0 ? '\n\n───\n\n' : '';
1099
- progress(fullText + separator + partialText);
1100
- }
1101
- }
1102
- }
1103
- else if (responseMessage.type === 'result') {
1104
- if (promptQueued && !promptStarted) {
1105
- shared.costSoFar = responseMessage.total_cost_usd ?? shared.costSoFar;
1106
- logAt('verbose', `[Claude] Result of a turn queued ahead of this prompt, session:${sessionKey}`);
1107
- continue;
1108
- }
1109
- watchdog?.stop();
1110
- // SDK ≥ v0.2.91 exposes terminal_reason on result messages; surface it
1111
- // at basic log level when non-`completed` so post-mortem grep can
1112
- // distinguish e.g. `aborted_streaming` / `aborted_tools` / `max_turns`
1113
- // / `model_error` from a normal completion. See
1114
- // docs/debugging/interrupted-by-user-misattribution.md.
1115
- const terminalReason = responseMessage.terminal_reason;
1116
- if (terminalReason && terminalReason !== 'completed') {
1117
- logAt('basic', `[Claude] TERMINAL_REASON: ${terminalReason} (session:${sessionKey}, ${getTimingReport(timer)})`);
1118
- }
1119
- else {
1120
- logAt('basic', `[Claude] Query completed: ${getTimingReport(timer)}`);
1121
- }
1122
- logAt('verbose', '[Claude] Result:', JSON.stringify(responseMessage, null, 2).substring(0, 500));
1123
- gotResult = true;
1124
- // A /cancel stops the turn, not the background work it started: a
1125
- // second /cancel, with no turn running, stops that.
1126
- if (shared.liveTasks.size === 0 || controller.signal.aborted) {
1127
- releaseInput();
1128
- }
1129
- else {
1130
- shared.waitingOnTasks = true;
1131
- holdAfterResult = !detached;
1132
- logAt('basic', `[Claude] Keeping the query open for ${shared.liveTasks.size} background task(s): ${[...shared.liveTasks].join(', ')}`);
1133
- }
1134
- // Flush any sub-turn text accumulated during this turn as its own
1135
- // chat message (monitor events, post-completion commentary, etc.).
1136
- // Its result text is that same reply, so it stays out of fullText.
1137
- const subTurnResult = inSubTurn;
1138
- if (inSubTurn) {
1139
- const subTurnText = subTurnBuffer.trim();
1140
- if (subTurnText) {
1141
- await emitSubTurnResponse(subTurnText);
1142
- }
1143
- inSubTurn = false;
1144
- subTurnBuffer = '';
1145
- }
1146
- // Extract usage data from result. The query's total_cost_usd counts
1147
- // every turn it has answered; this turn's spend is what it added.
1148
- const resultMsg = responseMessage;
1149
- const turnCostUsd = Math.max(0, (resultMsg.total_cost_usd ?? 0) - shared.costSoFar);
1150
- shared.costSoFar = resultMsg.total_cost_usd ?? shared.costSoFar;
1151
- if (resultMsg.modelUsage) {
1152
- const modelKey = lastMainCall
1153
- ? findModelUsageKey(resultMsg.modelUsage, lastMainCall.model)
1154
- : Object.keys(resultMsg.modelUsage)[0];
1155
- if (modelKey && resultMsg.modelUsage[modelKey]) {
1156
- const mu = resultMsg.modelUsage[modelKey];
1157
- const call = lastMainCall?.usage;
1158
- const tokens = (key, fallback) => call ? (typeof call[key] === 'number' ? call[key] : 0) : fallback;
1159
- const usage = {
1160
- inputTokens: tokens('input_tokens', mu.inputTokens),
1161
- outputTokens: tokens('output_tokens', mu.outputTokens),
1162
- cacheReadTokens: tokens('cache_read_input_tokens', mu.cacheReadInputTokens),
1163
- cacheWriteTokens: tokens('cache_creation_input_tokens', mu.cacheCreationInputTokens),
1164
- totalCostUsd: turnCostUsd,
1165
- // Filled in below, once the turn is known to have completed.
1166
- sessionCostUsd: 0,
1167
- sessionCostTurns: 0,
1168
- contextWindow: mu.contextWindow,
1169
- numTurns: resultMsg.num_turns,
1170
- model: modelKey,
1171
- };
1172
- // A sub-turn after the reply went out is spend of its own.
1173
- if (detached)
1174
- recordUsage(usage);
1175
- else
1176
- resultUsage = usage;
1177
- }
1178
- }
1179
- if (responseMessage.subtype === 'success') {
1180
- // Only store session_id on successful results (not on error_during_execution)
1181
- if ('session_id' in responseMessage && responseMessage.session_id) {
1182
- chatSessionIds.set(sessionKey, responseMessage.session_id);
1183
- sessionManager.setClaudeSessionId(sessionKey, responseMessage.session_id, providerName);
1184
- logAt('basic', `[Claude] Stored session ${responseMessage.session_id} for session ${sessionKey}`);
1185
- }
1186
- // Append final result text if different from accumulated
1187
- if (!subTurnResult && responseMessage.result && !fullText.includes(responseMessage.result)) {
1188
- if (fullText.length > 0) {
1189
- fullText += '\n\n';
1190
- }
1191
- fullText += responseMessage.result;
1192
- progress(fullText);
1193
- }
1194
- }
1195
- else if (responseMessage.subtype === 'error_during_execution' && isCancelled(sessionKey)) {
1196
- // Interrupted via /cancel - show clean cancellation message
1197
- fullText = '✅ Successfully cancelled - no tools or agents in process.';
1198
- progress(fullText);
1199
- }
1200
- else if (!silenceTimedOut) {
1201
- // error_max_turns or unexpected error_during_execution
1202
- // Try to extract a Max usage-limit signal from the upstream text so
1203
- // the bot can offer a CCR fallback prompt. The SDK surfaces the raw
1204
- // error in `result` even on error subtypes.
1205
- const upstreamText = 'result' in responseMessage && typeof responseMessage.result === 'string'
1206
- ? responseMessage.result
1207
- : undefined;
1208
- throttleInfo = parseThrottle(upstreamText);
1209
- // Preserve the session on a throttle (so a retry via the same chat
1210
- // resumes properly), otherwise clear it — stale session_ids cause
1211
- // hard failures on subsequent attempts.
1212
- if (!throttleInfo) {
1213
- chatSessionIds.delete(sessionKey);
1214
- const session = sessionManager.getSession(sessionKey);
1215
- if (session) {
1216
- session.claudeSessionId = undefined;
1217
- }
1218
- logAt('basic', `[Claude] Cleared stale session for session ${sessionKey} due to ${responseMessage.subtype}`);
1219
- }
1220
- else {
1221
- logAt('basic', `[Claude] Throttle detected for session ${sessionKey}: ${throttleInfo.message.substring(0, 120)}`);
1222
- }
1223
- fullText = throttleInfo
1224
- ? `⚠️ ${throttleInfo.message}`
1225
- : isClaudeAuthError(upstreamText)
1226
- ? `🔑 ${CLAUDE_NOT_LOGGED_IN_REPLY}`
1227
- : `Error: ${responseMessage.subtype}`;
1228
- progress(fullText);
1229
- }
1230
- }
1231
- if (holdAfterResult) {
1232
- holdAfterResult = false;
1233
- detach();
1234
- }
1235
- }
1236
- }
1237
- catch (error) {
1238
- watchdog?.stop();
1239
- // If cancelled via /cancel or /reset, return clean message
1240
- if (isCancelled(sessionKey)) {
1241
- return {
1242
- text: '✅ Successfully cancelled - no tools or agents in process.',
1243
- toolsUsed,
1244
- };
1245
- }
1246
- // Stale tool timeout — preserve session for recovery
1247
- if (staleToolTimedOut) {
1248
- return {
1249
- text: `⏱️ A tool appears stuck (no progress for ${formatDuration(config.AGENT_STALE_TOOL_TIMEOUT_MS)}). Your session has been preserved — send another message to continue.`,
1250
- toolsUsed,
1251
- };
1252
- }
1253
- // Silence timeout — preserve session for recovery
1254
- if (silenceTimedOut) {
1255
- return {
1256
- text: `⏱️ The query stalled (no activity for ${formatDuration(config.AGENT_SILENCE_TIMEOUT_MS)}). Your session has been preserved — send another message to continue.`,
1257
- toolsUsed,
1258
- };
1259
- }
1260
- // Watchdog timeout (not user-initiated)
1261
- if (abortController?.signal.aborted) {
1262
- return {
1263
- text: '⏱️ Request timed out — the query took too long and was automatically stopped. Try a simpler prompt or break it into smaller steps.',
1264
- toolsUsed,
1265
- };
1266
- }
1267
- if (error instanceof ClaudeNotLoggedInError)
1268
- throw error;
1269
- // If we got a result, ignore process exit errors (SDK quirk)
1270
- if (gotResult && error instanceof Error && error.message.includes('exited with code')) {
1271
- console.log('[Claude] Ignoring exit code error after successful result');
1272
- }
1273
- else {
1274
- console.error('[Claude] Full error:', error);
1275
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
1276
- throw new Error(`Claude error: ${errorMessage}`);
1277
- }
1278
- }
1279
- finally {
1280
- clearInterval(previewFlushTimer);
1281
- watchdog?.stop();
1282
- // A detached call's turn has ended already, and the query may be the next
1283
- // turn's now.
1284
- if (!detached) {
1285
- releaseInput();
1286
- clearActiveQuery(sessionKey);
1287
- }
1288
- }
1289
- return undefined;
1290
- })();
1291
- const outcome = await Promise.race([consume, replyReady.then(() => 'held')]);
1292
- if (outcome === 'held') {
1293
- consume.catch((err) => console.error('[Claude] Query kept open for background work failed:', err));
1294
- }
1295
- else if (outcome) {
1296
- return outcome;
1297
- }
1298
- // Report a manual /compact. The CLI answers it with an empty result and,
1299
- // on success, a compact_boundary carrying the numbers — so the confirmation
1300
- // is synthesized here rather than relayed. Mirrors what the PTY provider
1301
- // reports for the same command, down to the wording.
1302
- if (manualCompact && !abortController?.signal.aborted) {
1303
- if (compactionEvent) {
1304
- fullText = formatCompactionConfirmation({
1305
- preTokens: compactionEvent.preTokens,
1306
- postTokens: compactionPostTokens,
1307
- });
1308
- // The confirmation already carries the token detail; drop the separate
1309
- // generic notification so the user gets one clean message.
1310
- compactionEvent = undefined;
1311
- }
1312
- else if (compactError) {
1313
- // The CLI's reason is already a complete user-facing sentence
1314
- // ("Not enough messages to compact."), so relay it rather than wrapping
1315
- // it in a prefix that repeats it.
1316
- fullText = `ℹ️ ${compactError.endsWith('.') ? compactError : compactError + '.'}`;
1317
- }
1318
- }
1319
- // Add assistant response to history
1320
- if (fullText && !abortController?.signal.aborted) {
1321
- history.push({
1322
- role: 'assistant',
1323
- content: fullText,
1324
- });
1325
- }
1326
- conversationHistory.set(sessionKey, history);
1327
- // Update session history with Claude's response for restore preview
1328
- if (fullText && !isCancelled(sessionKey)) {
1329
- const preview = stripReasoningSummary(fullText);
1330
- if (preview) {
1331
- sessionManager.updateLastAssistantMessage(sessionKey, preview);
1332
- }
1333
- }
1334
- if (resultUsage)
1335
- recordUsage(resultUsage);
1336
- return {
1337
- text: stripReasoningSummary(fullText) || 'No response from Claude.',
1338
- toolsUsed,
1339
- usage: resultUsage,
1340
- compaction: compactionEvent,
1341
- sessionInit: initEvent,
1342
- throttle: throttleInfo,
1343
- };
1344
- }
1345
- export async function sendLoopToAgent(sessionKey, message, options = {}) {
1346
- const { onProgress, abortController, maxIterations = config.MAX_LOOP_ITERATIONS, onIterationComplete, } = options;
1347
- const session = sessionManager.getSession(sessionKey);
1348
- if (!session) {
1349
- throw new Error('No active session. Use /project to set working directory.');
1350
- }
1351
- // Wrap the prompt with loop instructions
1352
- const loopPrompt = `${message}
1353
-
1354
- IMPORTANT: When you have fully completed this task, respond with the word "DONE" on its own line at the end of your response. If you need to continue working, do not say "DONE".`;
1355
- let iteration = 0;
1356
- let combinedText = '';
1357
- const allToolsUsed = [];
1358
- let isComplete = false;
1359
- let throttleInfo;
1360
- while (iteration < maxIterations && !isComplete) {
1361
- iteration++;
1362
- // Check for abort
1363
- if (abortController?.signal.aborted) {
1364
- return {
1365
- text: '🛑 Loop cancelled.',
1366
- toolsUsed: allToolsUsed,
1367
- };
1368
- }
1369
- const iterationPrefix = `\n\n--- Iteration ${iteration}/${maxIterations} ---\n\n`;
1370
- combinedText += iterationPrefix;
1371
- onProgress?.(combinedText);
1372
- // For subsequent iterations, prompt Claude to continue
1373
- const currentPrompt = iteration === 1 ? loopPrompt : 'Continue the task. Say "DONE" when complete.';
1374
- try {
1375
- const response = await sendToAgent(sessionKey, currentPrompt, {
1376
- onProgress: (text) => {
1377
- onProgress?.(combinedText + text);
1378
- },
1379
- onToolResult: options.onToolResult,
1380
- onEditDiff: options.onEditDiff,
1381
- abortController,
1382
- model: options.model,
1383
- telegramCtx: options.telegramCtx,
1384
- executableOverride: options.executableOverride,
1385
- providerName: options.providerName,
1386
- });
1387
- combinedText += response.text;
1388
- allToolsUsed.push(...response.toolsUsed);
1389
- onIterationComplete?.(iteration, response.text);
1390
- // Surface throttle from any iteration so the caller can prompt the
1391
- // user. Abort the loop — continuing would just hit the same wall.
1392
- if (response.throttle) {
1393
- throttleInfo = response.throttle;
1394
- break;
1395
- }
1396
- // Check if Claude said DONE
1397
- if (response.text.includes('DONE')) {
1398
- isComplete = true;
1399
- combinedText += '\n\n✅ Loop completed.';
1400
- }
1401
- else if (iteration >= maxIterations) {
1402
- combinedText += `\n\n⚠️ Max iterations (${maxIterations}) reached.`;
1403
- }
1404
- onProgress?.(combinedText);
1405
- }
1406
- catch (error) {
1407
- if (abortController?.signal.aborted) {
1408
- return {
1409
- text: combinedText + '\n\n🛑 Loop cancelled.',
1410
- toolsUsed: allToolsUsed,
1411
- };
1412
- }
1413
- throw error;
1414
- }
1415
- }
1416
- return {
1417
- text: stripReasoningSummary(combinedText),
1418
- toolsUsed: allToolsUsed,
1419
- throttle: throttleInfo,
1420
- };
1421
- }
1422
- export function clearConversation(sessionKey) {
1423
- conversationHistory.delete(sessionKey);
1424
- chatSessionIds.delete(sessionKey);
1425
- chatUsageCache.delete(sessionKey);
1426
- clearSessionCost(sessionKey);
1427
- forgetTurnContext(sessionKey);
1428
- taskTracker.clear(sessionKey);
1429
- }
1430
- // Model and effort are read from the preferences on every call: they are held
1431
- // in memory already, and a cache here would go stale for the threads that fall
1432
- // back to a chat-wide value when that value changes.
1433
- export function setModel(scope, model) {
1434
- userPreferences.setModel(scope, model);
1435
- }
1436
- export function getModel(scope) {
1437
- return userPreferences.getModel(scope) || 'opus';
1438
- }
1439
- export function clearModel(scope) {
1440
- userPreferences.clearModel(scope);
1441
- }
1442
- const VALID_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
1443
- export function setEffort(scope, effort) {
1444
- userPreferences.setEffort(scope, effort);
1445
- }
1446
- export function getEffort(scope) {
1447
- return userPreferences.getEffort(scope);
1448
- }
1449
- export function clearEffort(scope) {
1450
- userPreferences.clearEffort(scope);
1451
- }
1452
- export function isValidEffortLevel(level) {
1453
- return VALID_EFFORT_LEVELS.includes(level);
1454
- }
1455
- export function isDangerousMode() {
1456
- return config.DANGEROUS_MODE;
1457
- }
1458
- //# sourceMappingURL=agent.js.map