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
@@ -6,24 +6,17 @@
6
6
  * status block. They live here so the domain modules depend on one small
7
7
  * shared surface instead of on each other.
8
8
  */
9
- import * as fs from 'fs';
10
- import * as path from 'path';
11
9
  import { sessionManager } from '../../../claude/session-manager.js';
12
- import { getModel, getEffort, isDangerousMode, getActiveProviderName, } from '../../../providers/provider-router.js';
10
+ import { envFilePath } from '../../../config.js';
11
+ import { getModel, getEffort, getActiveProviderName, } from '../../../providers/provider-router.js';
13
12
  import { EntityText } from '../../../telegram/entities.js';
14
13
  import { replyMarkdown } from '../../../telegram/send.js';
15
14
  import { fitsOnButton } from '../../../telegram/button-text.js';
16
- import { userPreferences } from '../../../providers/user-preferences.js';
17
- import { getPtyProvider } from '../../../providers/claude-provider.js';
18
- import { getSessionKeyFromCtx, parseSessionKey } from '../../../utils/session-key.js';
15
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
19
16
  import { formatTimeAgo } from '../../../utils/format.js';
20
17
  import { PACKAGE_ROOT } from '../../../utils/install-mode.js';
21
18
  /** Repo root (the package root, in an npm install). */
22
19
  export const PROJECT_ROOT = PACKAGE_ROOT;
23
- export const BOTCTL_PATH = path.join(PROJECT_ROOT, 'scripts', 'telecoder-botctl.sh');
24
- export function botctlExists() {
25
- return fs.existsSync(BOTCTL_PATH);
26
- }
27
20
  /**
28
21
  * Reply with standard markdown, sent as entities. For static text only: a
29
22
  * dynamic part (a path, a name, an error) goes through an {@link EntityText}
@@ -54,6 +47,24 @@ export function buildFeatureDisabledMessage(feature) {
54
47
  export async function replyFeatureDisabled(ctx, feature) {
55
48
  await ctx.reply(buildFeatureDisabledMessage(feature));
56
49
  }
50
+ /**
51
+ * What a voice note gets when no Groq key is set: how to turn
52
+ * transcription on, instead of a "Transcribing..." ack followed by a raw
53
+ * "GROQ_API_KEY not configured" error. Declining voice in `telecoder init` is
54
+ * the common case, so this is where most people learn how to add it later.
55
+ */
56
+ export function buildVoiceNotSetUpMessage() {
57
+ return [
58
+ '🎤 Voice transcription is off: no Groq API key is set.',
59
+ '',
60
+ 'To turn it on, get a key at https://console.groq.com/keys (Groq has a free tier), then either:',
61
+ '• run `telecoder init` again — it keeps your other answers and asks for the key, or',
62
+ `• add GROQ_API_KEY=gsk_... to ${envFilePath} and /botrestart.`,
63
+ ].join('\n');
64
+ }
65
+ export async function replyVoiceNotSetUp(ctx) {
66
+ await ctx.reply(buildVoiceNotSetUpMessage());
67
+ }
57
68
  export const EFFORT_LEVELS = [
58
69
  { id: 'low', label: '🐇 Low', description: 'Minimal thinking, fastest' },
59
70
  { id: 'medium', label: '⚖️ Medium', description: 'Balanced speed/quality' },
@@ -66,14 +77,22 @@ export function getEffortLabel(scope) {
66
77
  const effort = getEffort(scope);
67
78
  if (!effort)
68
79
  return undefined;
69
- return EFFORT_LEVELS.find((l) => l.id === effort)?.label;
80
+ return effortLevelLabel(effort);
81
+ }
82
+ /**
83
+ * The label for an effort level by name, for the one the session log reports
84
+ * when the chat set none itself. The CLI logs the API's four levels, so
85
+ * 'xhigh' never comes from there; a level this list doesn't know is shown as
86
+ * it was logged rather than dropped.
87
+ */
88
+ export function effortLevelLabel(effort) {
89
+ return EFFORT_LEVELS.find((l) => l.id === effort)?.label
90
+ ?? `🧠 ${effort.charAt(0).toUpperCase()}${effort.slice(1)}`;
70
91
  }
71
92
  /** Build status lines appended to project confirmation messages. */
72
93
  export function projectStatusSuffix(sessionKey) {
73
- const { chatId } = parseSessionKey(sessionKey);
74
94
  const model = getModel(sessionKey);
75
95
  const provider = getActiveProviderName(sessionKey);
76
- const dangerous = isDangerousMode() ? '⚠️ ENABLED' : 'Disabled';
77
96
  const session = sessionManager.getSession(sessionKey);
78
97
  const created = session?.createdAt
79
98
  ? new Date(session.createdAt).toLocaleString()
@@ -85,7 +104,6 @@ export function projectStatusSuffix(sessionKey) {
85
104
  .add('\n• ').bold('Model:').add(` ${model}`)
86
105
  .add('\n• ').bold('Effort:').add(` ${effortLabel}`)
87
106
  .add('\n• ').bold('Created:').add(` ${created}`)
88
- .add('\n• ').bold('Dangerous Mode:').add(` ${dangerous}`)
89
107
  .add('\n• ').bold('Session ID:').add(' ');
90
108
  if (sessionId) {
91
109
  suffix.code(sessionId);
@@ -181,27 +199,6 @@ export function withBackToPrevious(text, sessionKey, excludeConversationId) {
181
199
  },
182
200
  };
183
201
  }
184
- /**
185
- * Settings that are read at PTY spawn time only take effect on a fresh spawn.
186
- * Clearing the conversation makes the next message respawn with the new value,
187
- * keeping the conversation itself intact. No-op for non-PTY providers.
188
- */
189
- export function restartPtyForSettingChange(sessionKey) {
190
- if (!needsPtyRestart(sessionKey))
191
- return false;
192
- getPtyProvider().clearConversation(sessionKey);
193
- return true;
194
- }
195
- /**
196
- * Whether a spawn-time setting change would need a pty restart here —
197
- * the same test restartPtyForSettingChange makes, without doing it. For
198
- * rebuilding a confirmation whose restart already happened.
199
- */
200
- export function needsPtyRestart(scope) {
201
- if (getActiveProviderName(scope) !== 'claude')
202
- return false;
203
- return userPreferences.getMethod(scope) === 'pty';
204
- }
205
202
  /** Note appended when a pty restart is pending. */
206
203
  export const PTY_RESTART_NOTE = new EntityText()
207
204
  .add('\n\n')
@@ -2,14 +2,14 @@
2
2
  * /tasks and /shells — inspecting what the agent is running.
3
3
  *
4
4
  * Grouped because both are read-only views over live process state with the
5
- * same list/detail inline-keyboard shape: /tasks over the SDK task tracker,
5
+ * same list/detail inline-keyboard shape: /tasks over the task tracker,
6
6
  * /shells over the pty's real child processes.
7
7
  */
8
8
  import { EntityText } from '../../../telegram/entities.js';
9
9
  import { replyFormatted, editCallbackMessage } from '../../../telegram/send.js';
10
10
  import { taskTracker } from '../../../telegram/task-tracker.js';
11
11
  import { getPtyProvider } from '../../../providers/claude-provider.js';
12
- import { scrapeTasksOverlay } from '../../../claude/tasks-overlay-scraper.js';
12
+ import { scrapeTasksOverlay, parseTaskRows, parseTaskDetail, } from '../../../claude/tasks-overlay-scraper.js';
13
13
  import { bringCardDown, hasRunningTasks } from '../../../telegram/background-activity-card.js';
14
14
  import { getDirectChildren, describeProcess, isDescendantOf, killTree, } from '../../../utils/proc-children.js';
15
15
  import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
@@ -60,16 +60,16 @@ function formatDuration(ms) {
60
60
  return `${minutes}m ${seconds % 60}s`;
61
61
  }
62
62
  function formatTaskElapsed(task) {
63
- return formatDuration((task.endedAt ?? Date.now()) - task.startedAt);
63
+ return formatDuration(Date.now() - task.startedAt);
64
64
  }
65
65
  function formatTaskSilence(task) {
66
66
  return formatDuration(Date.now() - task.lastActivityAt);
67
67
  }
68
68
  /**
69
- * How long a task may go without any SDK event before /tasks flags it as
70
- * probably-finished. A completion `notification` removes the entry outright,
71
- * so an entry still listed after a long silence usually means that event
72
- * never arrived (restart mid-task, dropped notification).
69
+ * How long a task may go unheard from before /tasks flags it as
70
+ * probably-finished. The notification that ends a task removes the entry
71
+ * outright, so an entry still listed after a long silence usually means that
72
+ * notification never arrived (restart mid-task, dropped notification).
73
73
  *
74
74
  * Deliberately generous: this only annotates, never hides, but a false
75
75
  * positive on a slow-but-live agent is still noise.
@@ -85,13 +85,10 @@ function isPossiblyStale(task) {
85
85
  return false;
86
86
  return Date.now() - task.lastActivityAt > STALE_AFTER_MS;
87
87
  }
88
- function getActiveTasks(sessionKey) {
89
- return taskTracker.getTasks(sessionKey).filter(t => t.status === 'running' || t.status === 'pending');
90
- }
91
88
  function renderTasksList(sessionKey, tasks) {
92
89
  if (tasks.length === 0) {
93
- // Cross-pointer: a `Bash(run_in_background=true)` shell can outlive its SDK
94
- // task entry (npm release scripts, deploys), so the statusline's 🔍 counter
90
+ // Cross-pointer: a `Bash(run_in_background=true)` shell can outlive its
91
+ // task entry (npm release scripts, deploys), so the status line's 🔍 counter
95
92
  // may show > 0 while /tasks is empty. Surface that here so users know
96
93
  // where to look next.
97
94
  const claudePid = getPtyProvider().getSessionPid(sessionKey);
@@ -150,13 +147,18 @@ function renderTasksList(sessionKey, tasks) {
150
147
  { text: '🔄 Refresh', callback_data: 'tasks:refresh' },
151
148
  { text: '🔎 Ask claude', callback_data: 'tasks:ask' },
152
149
  ]);
153
- // PTY-only: the live card is how that mode shows background work.
150
+ // The live card is where background work shows as it runs.
154
151
  if (hasRunningTasks(sessionKey)) {
155
152
  keyboard.push([{ text: '📍 Show live card here', callback_data: 'tasks:card' }]);
156
153
  }
157
154
  return { message: b.build(), keyboard };
158
155
  }
159
- function renderTaskDetail(task) {
156
+ /**
157
+ * `canShowOutput`: there is a live pty to ask, so the detail offers the task's
158
+ * output (see "📄 Output" below). Without one, the output only arrives with
159
+ * the task's notification, which the relay posts when it lands.
160
+ */
161
+ function renderTaskDetail(task, canShowOutput = false) {
160
162
  const groupHint = (() => {
161
163
  switch (task.taskType) {
162
164
  case 'monitor_mcp': return '📡 Monitor';
@@ -171,8 +173,6 @@ function renderTaskDetail(task) {
171
173
  const b = new EntityText().add(`${groupHint}: `).bold(task.description).newline();
172
174
  /** A `• Label: ` bullet on a line of its own; the caller appends the value. */
173
175
  const field = (label) => b.newline().add('• ').bold(`${label}:`).add(' ');
174
- field('Status').add(task.status);
175
- field('Backgrounded').add(task.isBackgrounded ? 'yes' : 'no');
176
176
  field('Started').add(`${formatTaskElapsed(task)} ago`);
177
177
  if (isPossiblyStale(task)) {
178
178
  field('Last update').add(`${formatTaskSilence(task)} ago ⚠️`);
@@ -180,31 +180,23 @@ function renderTaskDetail(task) {
180
180
  if (task.taskType) {
181
181
  field('Type').code(task.taskType);
182
182
  }
183
- if (task.lastProgress?.lastToolName) {
184
- field('Last tool').code(task.lastProgress.lastToolName);
185
- }
186
- if (task.lastProgress?.usage) {
187
- const u = task.lastProgress.usage;
188
- field('Tokens').add(`${u.totalTokens} · `).bold('Tool uses:').add(` ${u.toolUses}`);
189
- }
190
- if (task.lastProgress?.summary) {
191
- const summary = task.lastProgress.summary.length > 300
192
- ? task.lastProgress.summary.substring(0, 297) + '...'
193
- : task.lastProgress.summary;
194
- b.newline(2).bold('Latest progress:').newline().quote(summary);
195
- }
196
- if (task.error) {
197
- b.newline(2).add(`⚠️ ${task.error}`);
198
- }
199
- return {
200
- message: b.build(),
201
- keyboard: [
202
- [
203
- { text: '← Back to list', callback_data: 'tasks:back' },
204
- { text: '🔄 Refresh', callback_data: `tasks:view:${task.id}` },
205
- ],
183
+ if (!canShowOutput && task.taskType !== 'monitor_mcp') {
184
+ b.newline(2).italic('Its output arrives with the result when it finishes.');
185
+ }
186
+ const keyboard = [
187
+ [
188
+ { text: '← Back to list', callback_data: 'tasks:back' },
189
+ { text: '🔄 Refresh', callback_data: `tasks:view:${task.id}` },
206
190
  ],
207
- };
191
+ ];
192
+ if (canShowOutput) {
193
+ keyboard.push([{ text: '📄 Output', callback_data: `tasks:out:${task.id}` }]);
194
+ }
195
+ return { message: b.build(), keyboard };
196
+ }
197
+ /** Whether this chat has a live pty whose `/tasks` overlay can be driven. */
198
+ function hasLivePty(sessionKey) {
199
+ return getPtyProvider().getSessionPid(sessionKey) !== undefined;
208
200
  }
209
201
  export async function handleTasks(ctx) {
210
202
  const keyInfo = getSessionKeyFromCtx(ctx);
@@ -212,7 +204,7 @@ export async function handleTasks(ctx) {
212
204
  await ctx.reply('❌ Could not determine chat context for /tasks.');
213
205
  return;
214
206
  }
215
- const tasks = getActiveTasks(keyInfo.sessionKey);
207
+ const tasks = taskTracker.getTasks(keyInfo.sessionKey);
216
208
  const { message, keyboard } = renderTasksList(keyInfo.sessionKey, tasks);
217
209
  await replyFormatted(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
218
210
  }
@@ -225,7 +217,7 @@ export async function handleTasksCallback(ctx) {
225
217
  }
226
218
  const { sessionKey } = keyInfo;
227
219
  if (data === 'tasks:refresh' || data === 'tasks:back') {
228
- const tasks = getActiveTasks(sessionKey);
220
+ const tasks = taskTracker.getTasks(sessionKey);
229
221
  const { message, keyboard } = renderTasksList(sessionKey, tasks);
230
222
  await ctx.answerCallbackQuery().catch(() => { });
231
223
  try {
@@ -250,12 +242,44 @@ export async function handleTasksCallback(ctx) {
250
242
  await handleAskClaude(ctx, sessionKey);
251
243
  return;
252
244
  }
245
+ if (data === 'tasks:claude') {
246
+ await showClaudeView(ctx, sessionKey, { edit: true });
247
+ return;
248
+ }
249
+ if (data.startsWith('tasks:claude:')) {
250
+ const row = Number.parseInt(data.substring('tasks:claude:'.length), 10);
251
+ if (!Number.isFinite(row) || row < 1) {
252
+ await ctx.answerCallbackQuery().catch(() => { });
253
+ return;
254
+ }
255
+ await showClaudeView(ctx, sessionKey, {
256
+ edit: true,
257
+ pick: (rows) => (row <= rows.length ? row - 1 : undefined),
258
+ refresh: data,
259
+ back: 'tasks:claude',
260
+ });
261
+ return;
262
+ }
263
+ if (data.startsWith('tasks:out:')) {
264
+ const taskId = data.substring('tasks:out:'.length);
265
+ const task = taskTracker.getTask(sessionKey, taskId);
266
+ await showClaudeView(ctx, sessionKey, {
267
+ edit: true,
268
+ pick: (rows) => (task ? matchTaskRow(task, rows) : undefined),
269
+ unmatchedNote: task
270
+ ? "Couldn't tell which of these is that task — tap the one it is."
271
+ : undefined,
272
+ refresh: data,
273
+ back: task ? `tasks:view:${taskId}` : 'tasks:back',
274
+ });
275
+ return;
276
+ }
253
277
  if (data.startsWith('tasks:view:')) {
254
278
  const taskId = data.substring('tasks:view:'.length);
255
279
  const task = taskTracker.getTask(sessionKey, taskId);
256
280
  if (!task) {
257
281
  // Task finished or was cleared between renders — go back to the list.
258
- const tasks = getActiveTasks(sessionKey);
282
+ const tasks = taskTracker.getTasks(sessionKey);
259
283
  const { message, keyboard } = renderTasksList(sessionKey, tasks);
260
284
  await ctx.answerCallbackQuery({ text: 'Task no longer active.' }).catch(() => { });
261
285
  try {
@@ -264,7 +288,7 @@ export async function handleTasksCallback(ctx) {
264
288
  catch { /* ignore */ }
265
289
  return;
266
290
  }
267
- const { message, keyboard } = renderTaskDetail(task);
291
+ const { message, keyboard } = renderTaskDetail(task, hasLivePty(sessionKey));
268
292
  await ctx.answerCallbackQuery().catch(() => { });
269
293
  try {
270
294
  await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
@@ -287,62 +311,208 @@ export async function handleTasksCallback(ctx) {
287
311
  export const _isPossiblyStale = isPossiblyStale;
288
312
  export const _renderTasksList = renderTasksList;
289
313
  export const _renderTaskDetail = renderTaskDetail;
290
- // ---------------------------------------------------------------------------
291
- // "🔎 Ask claude" — relay claude's own /tasks overlay
292
- // ---------------------------------------------------------------------------
314
+ export const _matchTaskRow = matchTaskRow;
315
+ export const _renderClaudeList = renderClaudeList;
316
+ export const _renderClaudeDetail = renderClaudeDetail;
317
+ const DOWN = '\x1b[B';
318
+ const ENTER = '\r';
293
319
  /**
294
- * The tracker above is reconstructed from tool-arm and task-notification
295
- * events, so it only knows about work TeleCoder saw start. Claude's own
296
- * `/tasks` overlay is the live process's view: it also covers shells claude
297
- * backgrounded on its own initiative, and everything armed before the last bot
298
- * restart (relay state doesn't persist). This button asks it directly.
299
- *
300
- * PTY-only — there is no TUI to drive in SDK mode, where the tracker is fed
301
- * from the event stream and is already authoritative.
320
+ * Open the overlay and, if `pick` names a row of the list it opens on, press
321
+ * ↓ that many times and Enter. The overlay opens straight on the detail when
322
+ * only one task runs, in which case there is nothing to pick.
302
323
  */
303
- async function handleAskClaude(ctx, sessionKey) {
324
+ async function readClaudeTasks(sessionKey, pick) {
325
+ const result = await getPtyProvider().runOverlayCommand(sessionKey, '/tasks', (screen) => {
326
+ if (!pick)
327
+ return undefined;
328
+ const overlay = scrapeTasksOverlay(screen);
329
+ if (!overlay)
330
+ return undefined;
331
+ const rows = parseTaskRows(overlay.text);
332
+ const index = rows.length > 0 ? pick(rows) : undefined;
333
+ if (index === undefined)
334
+ return undefined;
335
+ return [...Array(index).fill(DOWN), ENTER];
336
+ });
337
+ if (!result.ok)
338
+ return { kind: 'miss', reason: result.reason };
339
+ const overlay = scrapeTasksOverlay(result.screen);
340
+ if (!overlay)
341
+ return { kind: 'unreadable' };
342
+ if (overlay.empty)
343
+ return { kind: 'empty' };
344
+ const detail = parseTaskDetail(overlay.text);
345
+ if (detail)
346
+ return { kind: 'detail', detail };
347
+ return { kind: 'list', rows: parseTaskRows(overlay.text), text: overlay.text };
348
+ }
349
+ /** Collapse whitespace so a command wrapped by the TUI compares as typed. */
350
+ function squash(text) {
351
+ return text.replace(/\s+/g, ' ').trim();
352
+ }
353
+ /**
354
+ * The index of the one row in claude's list that is this task, or undefined
355
+ * when none or several are. A row shows the shell's command, or a description
356
+ * for other kinds, cut short with `…` when long; the task has both, so either
357
+ * may match. Two shells running the same command stay ambiguous on purpose:
358
+ * opening the wrong one's output would read as the right one's.
359
+ */
360
+ function matchTaskRow(task, rows) {
361
+ const candidates = [task.command, task.description]
362
+ .filter((c) => typeof c === 'string' && c.trim().length > 0)
363
+ .map(squash);
364
+ const hits = [];
365
+ rows.forEach((row, i) => {
366
+ const label = squash(row.label);
367
+ if (!label)
368
+ return;
369
+ const hit = candidates.some((c) => (row.truncated ? c.startsWith(label) : c === label));
370
+ if (hit)
371
+ hits.push(i);
372
+ });
373
+ return hits.length === 1 ? hits[0] : undefined;
374
+ }
375
+ function explainOverlayMiss(reason) {
376
+ switch (reason) {
377
+ case 'turn-active':
378
+ return 'Claude is mid-turn — the TUI keyboard is busy. Try again once it finishes.';
379
+ case 'not-ready':
380
+ return 'The Claude TUI is not at a prompt right now. Try again in a moment.';
381
+ case 'no-session':
382
+ return 'No live Claude session for this chat.';
383
+ }
384
+ }
385
+ /** Every answer below opens with the same heading. */
386
+ function claudeHeading() {
387
+ return new EntityText().add('🔎 ').bold("Claude's background view").newline(2);
388
+ }
389
+ function renderClaudeList(view, nav, note) {
390
+ const b = claudeHeading();
391
+ if (note)
392
+ b.italic(note).newline(2);
393
+ const body = view.text.length > 3000 ? view.text.slice(0, 2997) + '...' : view.text;
394
+ b.pre(body);
395
+ const keyboard = [];
396
+ if (view.rows.length > 0) {
397
+ b.newline().italic('Tap a row number to see its output.');
398
+ let row = [];
399
+ view.rows.forEach((_, i) => {
400
+ row.push({ text: String(i + 1), callback_data: `tasks:claude:${i + 1}` });
401
+ if (row.length === 5 || i === view.rows.length - 1) {
402
+ keyboard.push(row);
403
+ row = [];
404
+ }
405
+ });
406
+ }
407
+ const last = [{ text: '🔄 Refresh', callback_data: nav.refresh }];
408
+ if (nav.back)
409
+ last.unshift({ text: '← Back', callback_data: nav.back });
410
+ keyboard.push(last);
411
+ return { message: b.build(), keyboard };
412
+ }
413
+ /** The output pane is the point; keep its tail when the whole won't fit. */
414
+ const OUTPUT_MAX_CHARS = 3000;
415
+ function renderClaudeDetail(detail, nav) {
416
+ const b = claudeHeading().bold(detail.title);
417
+ for (const f of detail.fields) {
418
+ b.newline().add('• ').bold(`${f.label}:`).add(' ');
419
+ if (f.label === 'Command')
420
+ b.code(f.value);
421
+ else
422
+ b.add(f.value);
423
+ }
424
+ b.newline(2).bold('Output:').newline();
425
+ if (detail.output === null) {
426
+ b.italic('No output yet.');
427
+ }
428
+ else {
429
+ const out = detail.output.length > OUTPUT_MAX_CHARS
430
+ ? '…' + detail.output.slice(-(OUTPUT_MAX_CHARS - 1))
431
+ : detail.output;
432
+ b.pre(out);
433
+ if (detail.note)
434
+ b.newline().italic(detail.note);
435
+ }
436
+ const last = [{ text: '🔄 Refresh', callback_data: nav.refresh }];
437
+ if (nav.back)
438
+ last.unshift({ text: '← Back', callback_data: nav.back });
439
+ return { message: b.build(), keyboard: [last] };
440
+ }
441
+ /**
442
+ * Read claude's overlay and show what it says — the list with row buttons, a
443
+ * task's detail with its output, or why it couldn't be read. One function so
444
+ * that every entry point (the button under the tracker list, a row number,
445
+ * 📄 Output on a tracked task) renders the same way.
446
+ */
447
+ async function showClaudeView(ctx, sessionKey, opts) {
304
448
  await ctx.answerCallbackQuery({ text: 'Asking claude…' }).catch(() => { });
305
- // Every answer below opens with the same heading.
306
- const view = () => new EntityText().add('🔎 ').bold("Claude's background view").newline(2);
307
- const result = await getPtyProvider().runOverlayCommand(sessionKey, '/tasks');
308
- if (!result.ok) {
309
- const reason = result.reason === 'turn-active'
310
- ? 'Claude is mid-turn — the TUI keyboard is busy. Try again once it finishes.'
311
- : result.reason === 'not-ready'
312
- ? 'The Claude TUI is not at a prompt right now. Try again in a moment.'
313
- : 'No active PTY session for this chat. In SDK mode the list above is already authoritative.';
314
- await replyFormatted(ctx, view().add(reason).build());
315
- return;
449
+ const nav = { refresh: opts.refresh ?? 'tasks:claude', back: opts.back };
450
+ const view = await readClaudeTasks(sessionKey, opts.pick);
451
+ let rendered;
452
+ switch (view.kind) {
453
+ case 'detail':
454
+ rendered = renderClaudeDetail(view.detail, nav);
455
+ break;
456
+ case 'list':
457
+ rendered = renderClaudeList(view, nav, opts.pick ? opts.unmatchedNote : undefined);
458
+ break;
459
+ case 'empty': {
460
+ // A code block for one line of "nothing running" is noise. Worth saying
461
+ // out loud though: claude reporting empty while the tracker shows tasks
462
+ // means it is holding entries claude no longer knows about.
463
+ const tracked = taskTracker.getTasks(sessionKey).length;
464
+ const b = claudeHeading().add('Nothing running.');
465
+ if (tracked > 0) {
466
+ b.newline(2).italic(`The ${tracked} tracked task(s) are unknown to claude — likely finished already.`);
467
+ }
468
+ rendered = { message: b.build(), keyboard: [[{ text: '🔄 Refresh', callback_data: nav.refresh }]] };
469
+ break;
470
+ }
471
+ case 'unreadable':
472
+ // The overlay's layout is a Claude Code implementation detail and can
473
+ // move between releases — say so plainly rather than showing a mangled
474
+ // guess.
475
+ rendered = {
476
+ message: claudeHeading()
477
+ .add("Couldn't read the ")
478
+ .code('/tasks')
479
+ .add(' overlay — Claude Code may have changed its layout. The tracked list still works.')
480
+ .build(),
481
+ keyboard: [[{ text: '🔄 Refresh', callback_data: nav.refresh }]],
482
+ };
483
+ break;
484
+ case 'miss':
485
+ rendered = {
486
+ message: claudeHeading().add(explainOverlayMiss(view.reason)).build(),
487
+ keyboard: [[{ text: '🔄 Refresh', callback_data: nav.refresh }]],
488
+ };
489
+ break;
316
490
  }
317
- const overlay = scrapeTasksOverlay(result.screen);
318
- if (!overlay) {
319
- // The overlay's layout is a Claude Code implementation detail and can move
320
- // between releases — say so plainly rather than showing a mangled guess.
321
- await replyFormatted(ctx, view()
322
- .add("Couldn't read the ")
323
- .code('/tasks')
324
- .add(' overlay — Claude Code may have changed its layout. The list above still works.')
325
- .build());
491
+ if (nav.back && view.kind !== 'detail' && view.kind !== 'list') {
492
+ rendered.keyboard[0].unshift({ text: '← Back', callback_data: nav.back });
493
+ }
494
+ const markup = { reply_markup: { inline_keyboard: rendered.keyboard } };
495
+ if (!opts.edit) {
496
+ await replyFormatted(ctx, rendered.message, markup);
326
497
  return;
327
498
  }
328
- if (overlay.empty) {
329
- // A code block for one line of "nothing running" is noise. Worth saying
330
- // out loud though: claude reporting empty while the list above shows
331
- // tasks means our tracker is holding entries claude no longer knows about.
332
- const tracked = getActiveTasks(sessionKey).length;
333
- const b = view().add('Nothing running.');
334
- if (tracked > 0) {
335
- b.newline(2).italic(`The ${tracked} task(s) listed above are unknown to claude — likely finished already.`);
499
+ try {
500
+ await editCallbackMessage(ctx, rendered.message, markup);
501
+ }
502
+ catch (err) {
503
+ const msg = err instanceof Error ? err.message.toLowerCase() : '';
504
+ if (!msg.includes('message is not modified')) {
505
+ console.error("[Tasks] Failed to render claude's view:", err);
336
506
  }
337
- await replyFormatted(ctx, b.build());
338
- return;
339
507
  }
340
- const body = overlay.text.length > 3000 ? overlay.text.slice(0, 2997) + '...' : overlay.text;
341
- await replyFormatted(ctx, view().pre(body).build());
508
+ }
509
+ /** The button under the tracker's list: claude's view as a message of its own. */
510
+ async function handleAskClaude(ctx, sessionKey) {
511
+ await showClaudeView(ctx, sessionKey, { edit: false });
342
512
  }
343
513
  // ── /shells ─────────────────────────────────────────────────────
344
514
  // List OS-level child processes of the chat's PTY claude session and offer
345
- // a one-tap SIGTERM. Complements /tasks (which only sees SDK-tracked tasks)
515
+ // a one-tap SIGTERM. Complements /tasks (which only sees tracked tasks)
346
516
  // and rescues `Bash(run_in_background=true)` shells whose stop condition
347
517
  // will never fire.
348
518
  const BG_MCP_SERVER_MARKER = 'mcp-server.js';
@@ -396,21 +566,19 @@ function renderBgList(sessionKey, claudePid, procs) {
396
566
  return {
397
567
  message: heading()
398
568
  .newline(2)
399
- .italic('No active PTY session for this chat.')
400
- .newline(2)
401
- .add('In SDK mode, use /tasks to inspect tracked background tasks.')
569
+ .italic('No live Claude session for this chat.')
402
570
  .build(),
403
571
  keyboard: [],
404
572
  };
405
573
  }
406
574
  if (procs.length === 0) {
407
- // Cross-pointer to /tasks when SDK-tracked tasks (agents, monitors) are
575
+ // Cross-pointer to /tasks when tracked tasks (agents, monitors) are
408
576
  // running but no OS shells are.
409
- const taskCount = getActiveTasks(sessionKey).length;
577
+ const taskCount = taskTracker.getTasks(sessionKey).length;
410
578
  const b = heading().newline(2).add('None running.');
411
579
  if (taskCount > 0) {
412
580
  const noun = taskCount === 1 ? 'task' : 'tasks';
413
- b.newline(2).italic(`🔄 ${taskCount} SDK ${noun} still running — see /tasks.`);
581
+ b.newline(2).italic(`🔄 ${taskCount} ${noun} still running — see /tasks.`);
414
582
  }
415
583
  return {
416
584
  message: b.build(),