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
@@ -91,8 +91,8 @@ export function setMonitorRelayBot(bot) {
91
91
  setBackgroundCardBot(bot);
92
92
  }
93
93
  /**
94
- * Kind → the `taskType` string /tasks groups on. Keeps the PTY-mode buckets
95
- * identical to the SDK-mode ones so the command renders the same either way.
94
+ * Kind → the `taskType` string /tasks groups on: Claude Code's own names for
95
+ * the kinds of task.
96
96
  */
97
97
  const TASK_TYPE_BY_KIND = {
98
98
  monitor: 'monitor_mcp',
@@ -145,7 +145,7 @@ export function movedToBackground(toolName, toolInput, toolResponse) {
145
145
  * `startedAt` is for a task that was already running when it was armed — see
146
146
  * movedToBackground.
147
147
  */
148
- export function onAsyncToolArmed(kind, sessionKey, cwd, claudeSessionId, description, toolUseId, startedAt = Date.now()) {
148
+ export function onAsyncToolArmed(kind, sessionKey, cwd, claudeSessionId, description, toolUseId, startedAt = Date.now(), command) {
149
149
  let state = states.get(sessionKey);
150
150
  if (!state) {
151
151
  state = {
@@ -186,20 +186,51 @@ export function onAsyncToolArmed(kind, sessionKey, cwd, claudeSessionId, descrip
186
186
  description,
187
187
  startedAt,
188
188
  });
189
- taskTracker.handleEvent(sessionKey, {
190
- type: 'started',
189
+ taskTracker.start(sessionKey, {
191
190
  taskId: toolUseId,
192
191
  toolUseId,
193
192
  description,
193
+ ...(command !== undefined ? { command } : {}),
194
194
  taskType: TASK_TYPE_BY_KIND[kind],
195
- // Everything routed through this relay is backgrounded by definition —
196
- // that's the property that made it need a relay in the first place.
197
- isBackgrounded: true,
198
195
  startedAt,
199
196
  });
200
197
  }
201
198
  noteTaskArmed(sessionKey, kind, description, toolUseId, startedAt);
202
199
  }
200
+ /**
201
+ * The launching call has returned claude's own id for a backgrounded task
202
+ * (`backgroundTaskId` in a Bash response). Remember it: TaskStop names the
203
+ * task by that id, and the tool_use_id everything else is keyed by is not in
204
+ * its input.
205
+ */
206
+ export function noteClaudeTaskId(sessionKey, toolUseId, claudeTaskId) {
207
+ const armed = states.get(sessionKey)?.armedTasks.get(toolUseId);
208
+ if (armed)
209
+ armed.claudeTaskId = claudeTaskId;
210
+ taskTracker.setClaudeTaskId(sessionKey, toolUseId, claudeTaskId);
211
+ }
212
+ /**
213
+ * Claude called TaskStop on a task. The task is killed, but claude writes no
214
+ * task-notification for a task it stopped itself, so the completion path
215
+ * never fires and the entry would stay "running" until the bot restarts, the
216
+ * footer saying so under every reply. Retire it here instead, as stopped.
217
+ *
218
+ * Returns false for a task this relay never armed (one claude started between
219
+ * turns, or before the last restart), which has nothing to retire.
220
+ */
221
+ export function onTaskStopped(sessionKey, claudeTaskId) {
222
+ const state = states.get(sessionKey);
223
+ if (!state)
224
+ return false;
225
+ const entry = [...state.armedTasks].find(([, armed]) => armed.claudeTaskId === claudeTaskId);
226
+ if (!entry)
227
+ return false;
228
+ const [toolUseId, armed] = entry;
229
+ state.armedTasks.delete(toolUseId);
230
+ taskTracker.remove(sessionKey, toolUseId);
231
+ noteTaskFinished(sessionKey, toolUseId, { kind: armed.kind, description: armed.description, status: 'stopped', elapsedMs: Date.now() - armed.startedAt });
232
+ return true;
233
+ }
203
234
  export function markTurnStart(sessionKey) {
204
235
  const state = states.get(sessionKey);
205
236
  if (state) {
@@ -285,6 +316,69 @@ function statesFor(sessionKey) {
285
316
  export function hasSelfStartedTurn(sessionKey) {
286
317
  return statesFor(sessionKey).some((state) => state.selfTurnOpen || state.reply.length > 0);
287
318
  }
319
+ /**
320
+ * How long claude must sit at its prompt, with its log not growing, before a
321
+ * turn it started itself counts as over though the log never closed it.
322
+ */
323
+ export const STALE_SELF_TURN_MS = 2 * 60_000;
324
+ /** Per open self-started turn: since when claude was seen idle at its prompt, and the log's size then. */
325
+ const atPromptSince = new Map();
326
+ /**
327
+ * Close the turns claude started itself that are plainly over, though nothing
328
+ * in the log closed them. A turn opens on a record the watcher reads and only
329
+ * a record closes it, so any record that opens one by mistake, with no turn
330
+ * behind it, holds it open until the bot restarts: /botrebuild's "when idle"
331
+ * waits on it, the idle reaper spares its claude, and a message waits behind
332
+ * it. Idle compaction did that on 11-23, and two bots sat "answering a
333
+ * background task" for two days.
334
+ *
335
+ * So a self-started turn whose claude has sat at its input box, generating
336
+ * nothing and asking nothing, with the log not growing, for STALE_SELF_TURN_MS
337
+ * is closed here, and whatever it wrote goes out. Called every so often with
338
+ * a check of claude's screen; returns the sessions it closed.
339
+ */
340
+ export function closeStaleSelfTurns(isAtPrompt, now = Date.now()) {
341
+ for (const key of atPromptSince.keys()) {
342
+ if (!states.get(key)?.selfTurnOpen)
343
+ atPromptSince.delete(key);
344
+ }
345
+ const closed = [];
346
+ for (const state of states.values()) {
347
+ if (!state.selfTurnOpen || state.inTurn)
348
+ continue;
349
+ const key = state.sessionKey;
350
+ if (!isAtPrompt(key)) {
351
+ atPromptSince.delete(key);
352
+ continue;
353
+ }
354
+ let logSize;
355
+ try {
356
+ logSize = fs.statSync(sessionJsonlPath(state.cwd, state.claudeSessionId)).size;
357
+ }
358
+ catch {
359
+ continue;
360
+ }
361
+ const seen = atPromptSince.get(key);
362
+ if (!seen || seen.logSize !== logSize) {
363
+ atPromptSince.set(key, { since: now, logSize });
364
+ continue;
365
+ }
366
+ if (now - seen.since < STALE_SELF_TURN_MS)
367
+ continue;
368
+ atPromptSince.delete(key);
369
+ // Whatever the watcher hasn't read yet first: a close in there ends the
370
+ // turn the ordinary way.
371
+ drain(state);
372
+ if (!state.selfTurnOpen)
373
+ continue;
374
+ console.warn(`[Monitor] ${key}: closing a turn claude started itself that the log never closed — `
375
+ + `claude has sat at its prompt for ${Math.round((now - seen.since) / 1000)}s`);
376
+ state.selfTurnOpen = false;
377
+ void sendReply(state, true);
378
+ closed.push(key);
379
+ }
380
+ return closed;
381
+ }
288
382
  /** Resolves once every reply already handed on is in its chat. */
289
383
  export async function whenRepliesSent(sessionKey) {
290
384
  await Promise.all(statesFor(sessionKey).map((state) => state.replySent));
@@ -301,9 +395,9 @@ export function teardown(sessionKey) {
301
395
  void sendReply(state);
302
396
  states.delete(sessionKey);
303
397
  clearCard(sessionKey);
304
- // This relay owns the PTY-side tracker entries, and teardown is PTY-only
305
- // (_cleanupSession is its sole caller). Drop them with the session so a
306
- // respawned one doesn't inherit tasks that died with the old process.
398
+ // This relay owns the tracker entries (_cleanupSession is teardown's sole
399
+ // caller). Drop them with the session so a respawned one doesn't inherit
400
+ // tasks that died with the old process.
307
401
  taskTracker.clear(sessionKey);
308
402
  }
309
403
  function startWatching(state) {
@@ -330,6 +424,18 @@ function startWatching(state) {
330
424
  console.error(`[Monitor] failed to watch JSONL for ${state.sessionKey}:`, err);
331
425
  }
332
426
  }
427
+ /**
428
+ * Watch the session's log in its new directory: Claude Code's /cd moved it
429
+ * there (session-move.ts). What was appended in between isn't read again.
430
+ */
431
+ export function onSessionMoved(sessionKey, cwd) {
432
+ const state = states.get(sessionKey);
433
+ if (!state || state.cwd === cwd)
434
+ return;
435
+ state.cwd = cwd;
436
+ stopWatcher(state);
437
+ startWatching(state);
438
+ }
333
439
  function stopWatcher(state) {
334
440
  if (state.watcher) {
335
441
  try {
@@ -402,6 +508,11 @@ function handleChange(state, closes = true) {
402
508
  }
403
509
  continue;
404
510
  }
511
+ // The summary a compaction leaves, filed as a user record too. When
512
+ // claude compacts an idle session by itself ("Compacted while idle")
513
+ // no turn follows, so nothing would ever close one opened here.
514
+ if (typed.isCompactSummary)
515
+ continue;
405
516
  if (!state.inTurn)
406
517
  state.selfTurnOpen = true;
407
518
  const notif = parseTaskNotification(typed);
@@ -498,7 +609,11 @@ async function postReply(sessionKey, text) {
498
609
  // pty-provider at module scope, where every eager edge is a chance to
499
610
  // close a cycle back through it.
500
611
  const { messageSender } = await import('../telegram/message-sender.js');
501
- await messageSender.sendMessage(ctx, text);
612
+ const lastMessageId = await messageSender.sendMessage(ctx, text);
613
+ // A reply like any other, so it branches like any other: the button goes
614
+ // under its last message, as the turn pipeline puts it under a reply of
615
+ // TeleCoder's.
616
+ await messageSender.attachBranchButton(ctx, sessionKey, lastMessageId);
502
617
  }
503
618
  catch (err) {
504
619
  console.error('[Monitor] reply send failed:', err instanceof Error ? err.message : err);
@@ -565,9 +680,9 @@ function handleTerminalNotification(state, notif) {
565
680
  if (!armed)
566
681
  return false;
567
682
  state.armedTasks.delete(notif.toolUseId);
568
- // Retire the tracker entry before any chat I/O, mirroring the SDK path's
569
- // remove-after-notification. /tasks filters to running/pending, so dropping
570
- // it outright is equivalent to recording a terminal status.
683
+ // Retire the tracker entry before any chat I/O. /tasks filters to
684
+ // running/pending, so dropping it outright is equivalent to recording a
685
+ // terminal status.
571
686
  taskTracker.remove(state.sessionKey, notif.toolUseId);
572
687
  const elapsedMs = Date.now() - armed.startedAt;
573
688
  const isError = notif.status === 'failed' || notif.status === 'killed';
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Claude Code's own slash commands and their aliases, as the installed CLI
3
+ * has them (2.1.326), for telling one from a typo of a bot command.
4
+ *
5
+ * The probe in available-commands.ts reads the list a headless `claude -p`
6
+ * reports, which holds only what works headless: interactive-only commands
7
+ * (`/export`, `/hooks`, `/theme`, `/cd`…) and every alias (`/rc`, `/peers`)
8
+ * are missing from it, and the typo fallback took them for a misspelt bot
9
+ * command (`/export` → "did you mean /effort"). This list fills that gap. A
10
+ * name it lacks still reaches Claude Code, through the fallback's "as typed"
11
+ * button, so a stale list costs a tap, not the command.
12
+ *
13
+ * Refresh it from the binary (`readlink -f "$(command -v claude)"`): the name
14
+ * and aliases of every command object in it, `{type:"local"|"local-jsx"|
15
+ * "prompt", name:"…", description:"…"}`, in either key order.
16
+ */
17
+ export const CLAUDE_CODE_COMMAND_NAMES = new Set([
18
+ 'add-dir', 'advisor', 'agents', 'allowed-tools', 'android', 'app',
19
+ 'artifacts', 'auto-mode-setup', 'autocompact', 'autofix-pr', 'background',
20
+ 'bashes', 'bg', 'branch', 'break-reminder', 'breaks', 'brief', 'btw', 'bug',
21
+ 'cd', 'checkpoint', 'clear', 'cloud-plugins', 'color', 'compact', 'config',
22
+ 'context', 'continue', 'copy', 'cost', 'daemon', 'design-consent',
23
+ 'design-login', 'design-revoke', 'desktop', 'doctor', 'downtime', 'effort',
24
+ 'exit', 'export', 'extra-usage', 'feedback', 'focus', 'fork', 'goal',
25
+ 'heapdump', 'help', 'hooks', 'ide', 'import', 'insights', 'install',
26
+ 'install-github-app', 'install-slack-app', 'ios', 'keybindings',
27
+ 'list-agents', 'login', 'logout', 'loop', 'loops', 'marketplace', 'mcp',
28
+ 'memory', 'mobile', 'model', 'name', 'new', 'output-style', 'peers',
29
+ 'permissions', 'plan', 'plugin', 'plugins', 'powerup', 'privacy-settings',
30
+ 'pro-trial-expired', 'proactive', 'project', 'quit', 'radio',
31
+ 'rate-limit-options', 'rc', 'recap', 'release-notes', 'reload-plugins',
32
+ 'reload-skills', 'remote', 'remote-control', 'remote-env', 'rename', 'reset',
33
+ 'resume', 'review', 'rewind', 'scroll-speed', 'session', 'settings',
34
+ 'setup-bedrock', 'setup-vertex', 'share', 'skill-doctor', 'skills', 'stats',
35
+ 'status', 'statusline', 'stickers', 'stop', 'subtask', 'tasks',
36
+ 'team-onboarding', 'teleport', 'terminal-setup', 'theme', 'tp', 'tui',
37
+ 'undo', 'upgrade', 'usage', 'usage-credits', 'use-case', 'version', 'voice',
38
+ 'web-setup', 'wellbeing', 'workflow-launch-exec', 'workflows',
39
+ ]);
40
+ //# sourceMappingURL=native-commands.js.map
@@ -1,12 +1,12 @@
1
1
  /**
2
- * Pending-fork storage. When a user forks a conversation from Bot A to Bot B,
2
+ * Pending-branch storage. When a user branches a conversation from Bot A to Bot B,
3
3
  * Bot A writes the truncated transcript here keyed by Bot B's id. Bot B picks
4
4
  * it up on the next user message and offers accept/decline.
5
5
  *
6
- * File: ~/.telecoder/pending-forks-<targetBotId>.json
7
- * Structure: { users: { [userId]: PendingFork } } — keyed by the Telegram
6
+ * File: ~/.telecoder/pending-branches-<targetBotId>.json
7
+ * Structure: { users: { [userId]: PendingBranch } } — keyed by the Telegram
8
8
  * user id, not the chatId, because each bot has its own private DM with the
9
- * user (different chatId per bot). Routing by user id lets a fork from a
9
+ * user (different chatId per bot). Routing by user id lets a branch from a
10
10
  * DM with Bot A land in the DM with Bot B without either side knowing the
11
11
  * other's chatId. The target bot's chat resolves when the user actually
12
12
  * messages it — wherever they message from, that's where the offer shows up.
@@ -19,10 +19,10 @@ import * as path from 'path';
19
19
  import { z } from 'zod';
20
20
  import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
21
21
  const HISTORY_DIR = getStateDir();
22
- const pendingForkSchema = z.object({
22
+ const pendingBranchSchema = z.object({
23
23
  fromBotName: z.string(),
24
24
  fromBotId: z.string(),
25
- /** Source chat the fork was created in — informational, not used for routing. */
25
+ /** Source chat the branch was created in — informational, not used for routing. */
26
26
  fromChatId: z.number().optional(),
27
27
  projectPath: z.string(),
28
28
  // The truncated JSONL content, inline. JSONL is small (<1 MB even for very
@@ -38,41 +38,41 @@ const pendingForkSchema = z.object({
38
38
  offered: z.boolean().optional(),
39
39
  });
40
40
  const fileSchema = z.object({
41
- users: z.record(z.string(), pendingForkSchema),
41
+ users: z.record(z.string(), pendingBranchSchema),
42
42
  });
43
43
  function pathFor(botId) {
44
- return path.join(HISTORY_DIR, `pending-forks-${botId}.json`);
44
+ return path.join(HISTORY_DIR, `pending-branches-${botId}.json`);
45
45
  }
46
46
  function loadFile(botId) {
47
- return readJsonFile(pathFor(botId), fileSchema, 'PendingForks') ?? { users: {} };
47
+ return readJsonFile(pathFor(botId), fileSchema, 'PendingBranches') ?? { users: {} };
48
48
  }
49
- // rethrow: callers confirm "Forked." to the user immediately after writing, so
49
+ // rethrow: callers confirm "Branched." to the user immediately after writing, so
50
50
  // a swallowed failure would report a handoff that never landed on disk.
51
51
  function saveFile(botId, data) {
52
- ensureStateDir(HISTORY_DIR, 'PendingForks');
53
- writeJsonFile(pathFor(botId), data, 'PendingForks', { rethrow: true });
52
+ ensureStateDir(HISTORY_DIR, 'PendingBranches');
53
+ writeJsonFile(pathFor(botId), data, 'PendingBranches', { rethrow: true });
54
54
  }
55
- /** Write a pending fork to the target bot's file, replacing any existing one for this user. */
56
- export function putPendingFork(targetBotId, userId, fork) {
55
+ /** Write a pending branch to the target bot's file, replacing any existing one for this user. */
56
+ export function putPendingBranch(targetBotId, userId, branch) {
57
57
  const data = loadFile(targetBotId);
58
- data.users[String(userId)] = fork;
58
+ data.users[String(userId)] = branch;
59
59
  saveFile(targetBotId, data);
60
60
  }
61
- /** Read the pending fork for this (target bot, user), if any. */
62
- export function getPendingFork(targetBotId, userId) {
61
+ /** Read the pending branch for this (target bot, user), if any. */
62
+ export function getPendingBranch(targetBotId, userId) {
63
63
  const data = loadFile(targetBotId);
64
64
  return data.users[String(userId)];
65
65
  }
66
- /** Remove the pending fork for this (target bot, user). No-op if missing. */
67
- export function removePendingFork(targetBotId, userId) {
66
+ /** Remove the pending branch for this (target bot, user). No-op if missing. */
67
+ export function removePendingBranch(targetBotId, userId) {
68
68
  const data = loadFile(targetBotId);
69
69
  if (!(String(userId) in data.users))
70
70
  return;
71
71
  delete data.users[String(userId)];
72
72
  saveFile(targetBotId, data);
73
73
  }
74
- /** Flag a fork as already-offered so the proactive watcher won't re-send it. */
75
- export function markForkOffered(targetBotId, userId) {
74
+ /** Flag a branch as already-offered so the proactive watcher won't re-send it. */
75
+ export function markBranchOffered(targetBotId, userId) {
76
76
  const data = loadFile(targetBotId);
77
77
  const entry = data.users[String(userId)];
78
78
  if (!entry)
@@ -82,12 +82,12 @@ export function markForkOffered(targetBotId, userId) {
82
82
  data.users[String(userId)] = { ...entry, offered: true };
83
83
  saveFile(targetBotId, data);
84
84
  }
85
- /** Return all pending forks for a bot, keyed by userId (string). */
86
- export function listPendingForks(targetBotId) {
85
+ /** Return all pending branches for a bot, keyed by userId (string). */
86
+ export function listPendingBranches(targetBotId) {
87
87
  return loadFile(targetBotId).users;
88
88
  }
89
- /** Path that contains pending forks for this bot — useful for file watching. */
90
- export function pendingForksPathFor(targetBotId) {
89
+ /** Path that contains pending branches for this bot — useful for file watching. */
90
+ export function pendingBranchesPathFor(targetBotId) {
91
91
  return pathFor(targetBotId);
92
92
  }
93
- //# sourceMappingURL=pending-forks.js.map
93
+ //# sourceMappingURL=pending-branches.js.map
@@ -14,10 +14,13 @@ import { sanitizeError } from '../utils/sanitize.js';
14
14
  * (destructive bash patterns, force-pushes, DROP TABLE, etc.) trigger a Telegram
15
15
  * approval prompt before executing. On approve, the hook returns the allow
16
16
  * marker and claude proceeds; on deny or timeout, claude sees a tool-blocked
17
- * error. The PTY transport's hook returns the markers (consumed by the shell
18
- * wrapper in pty-spawn-config.ts, which blocks on anything else too); the SDK
19
- * transport's (sdk-permission-gate.ts) a deny decision. Both go through
20
- * gateToolCall.
17
+ * error. The markers are consumed by the shell wrapper in
18
+ * pty-spawn-config.ts, which blocks on anything else too. The hook's handler
19
+ * goes through gateToolCall.
20
+ *
21
+ * A message that starts with `!` is a command too, but not a tool call: Claude
22
+ * Code runs it in shell mode and raises no hook for it. Those come here before
23
+ * they are typed into the pty (shell-mode-gate.ts).
21
24
  *
22
25
  * Soft by design: hooks can't override --disallowedTools deny rules, and the
23
26
  * patterns list is intentionally conservative — false positives are worse here
@@ -147,7 +150,7 @@ export async function evaluateToolCall(req) {
147
150
  }]);
148
151
  const { text, entities } = buildPromptMessage({
149
152
  reason: pattern.reason,
150
- toolName: req.toolName,
153
+ toolName: req.toolLabel ?? req.toolName,
151
154
  toolInput: req.toolInput,
152
155
  requester: describeRequester(ctx),
153
156
  responders,
@@ -195,12 +198,10 @@ export async function evaluateToolCall(req) {
195
198
  : `An approver denied: ${pattern.reason}`,
196
199
  };
197
200
  }
198
- return { block: false, reason: '' };
201
+ return { block: false, reason: '', approvedByPerson: true };
199
202
  }
200
203
  /**
201
- * The gate as a transport's PreToolUse hook calls it: the PTY's IPC handler
202
- * and the SDK's in-process hook both go through here, so the two can't drift
203
- * apart in what they check or how they fail.
204
+ * The gate as the PreToolUse hook's IPC handler calls it.
204
205
  *
205
206
  * Fails closed. A gate that let a call through because it broke while judging
206
207
  * it would be no gate on exactly the calls it exists for.
@@ -327,7 +328,7 @@ function matchDangerousPattern(toolName, toolInput) {
327
328
  }
328
329
  return null;
329
330
  }
330
- /** List the dangerous patterns surfaced via /permissions. */
331
+ /** List the dangerous patterns surfaced via /gate. */
331
332
  export function listDangerousPatterns() {
332
333
  return DANGEROUS_BASH_PATTERNS.map((p) => ({
333
334
  reason: p.reason,
@@ -1,21 +1,18 @@
1
1
  /**
2
2
  * The permission mode a chat runs claude in.
3
3
  *
4
- * Claude Code's modes differ in how much it asks before acting, and until now
5
- * this bot had no say in it: the SDK transport hard-coded `acceptEdits` and
6
- * the pty spawned with `--dangerously-skip-permissions`, so every chat on
7
- * every project ran at whatever those two happened to be. `/plan` was the one
8
- * escape hatch, and only for a single turn.
4
+ * Claude Code's modes differ in how much it asks before acting, and this bot
5
+ * used to have no say in it: the pty spawned with
6
+ * `--dangerously-skip-permissions`, so every chat on every project ran in
7
+ * bypass.
9
8
  *
10
9
  * The five modes below are claude's own, described in its own words from the
11
10
  * shift+tab lesson text. Only the first four are offered as choices a person
12
11
  * cycles through; bypass is here because it is what the pty has always
13
12
  * launched in, and a chat that leaves it needs a way back.
14
13
  *
15
- * Two names for one thing, which is the trap this table exists to close: the
16
- * CLI flag spells the ask-every-time mode `manual` and the SDK spells it
17
- * `default`, and each rejects the other's word. Anything crossing into either
18
- * transport goes through `cli` or `sdk` here, never through the id.
14
+ * `cli` is the word `--permission-mode` takes for a mode. Anything handed to
15
+ * the pty goes through it, never through the id.
19
16
  */
20
17
  import { tailLines } from './tui-state.js';
21
18
  export const PERMISSION_MODES = [
@@ -23,40 +20,30 @@ export const PERMISSION_MODES = [
23
20
  id: 'manual',
24
21
  label: 'Manual',
25
22
  description: 'ask before every edit',
26
- cli: 'manual',
27
- sdk: 'default',
28
23
  tuiPhrase: 'manual mode',
29
24
  },
30
25
  {
31
26
  id: 'acceptEdits',
32
27
  label: 'Accept edits',
33
28
  description: 'edit freely, ask for commands',
34
- cli: 'acceptEdits',
35
- sdk: 'acceptEdits',
36
29
  tuiPhrase: 'accept edits',
37
30
  },
38
31
  {
39
32
  id: 'plan',
40
33
  label: 'Plan',
41
34
  description: 'research and propose, never touch files',
42
- cli: 'plan',
43
- sdk: 'plan',
44
35
  tuiPhrase: 'plan mode',
45
36
  },
46
37
  {
47
38
  id: 'auto',
48
39
  label: 'Auto',
49
40
  description: 'Claude decides what is safe',
50
- cli: 'auto',
51
- sdk: 'auto',
52
41
  tuiPhrase: 'auto mode',
53
42
  },
54
43
  {
55
44
  id: 'bypassPermissions',
56
45
  label: 'Bypass',
57
46
  description: 'never ask — what the pty ran in before auto',
58
- cli: 'bypassPermissions',
59
- sdk: 'bypassPermissions',
60
47
  tuiPhrase: 'bypass permissions',
61
48
  },
62
49
  ];
@@ -70,34 +57,22 @@ export function isPermissionModeId(value) {
70
57
  return PERMISSION_MODES.some((m) => m.id === value);
71
58
  }
72
59
  /**
73
- * The mode a chat runs in when it has chosen none.
74
- *
75
- * "Default" means "leave it to the transport", and the transports disagree, so
76
- * this is where the disagreement is written down — beside the table, rather
77
- * than in either transport, so the answer /mode prints and the answer a turn
78
- * runs in cannot drift apart.
79
- *
80
- * The pty answers `auto`, which is also what claude itself launches in when
81
- * nobody passes a flag. It ran bypassed for as long as it had no way to answer
82
- * a permission prompt; now that dialogs reach the chat mid-turn, the mode that
83
- * never asks is a choice rather than the only thing that worked. `/mode bypass`
84
- * is still one tap away for a chat that wants it back.
85
- *
86
- * DANGEROUS_MODE has no say here, exactly as it never had one on the pty: it
87
- * predates all of this, describes itself as an SDK-side auto-approve, and a
88
- * config flag quietly re-loosening a default the transport just tightened is
89
- * the kind of surprise this whole function exists to prevent.
60
+ * The mode a chat runs in until it picks one with /mode: `auto`, which is also
61
+ * what claude itself launches in when nobody passes a flag. The pty ran
62
+ * bypassed for as long as it had no way to answer a permission prompt; now
63
+ * that dialogs reach the chat mid-turn, the mode that never asks is a choice
64
+ * rather than the only thing that worked. `/mode bypass` is one tap away for a
65
+ * chat that wants it back. /mode prints this through permissionModeInfo, so
66
+ * the menu cannot describe a mode a turn would not run in.
90
67
  */
91
- export function transportDefaultMode(method, dangerousMode) {
92
- if (method === 'pty')
93
- return 'auto';
94
- return dangerousMode ? 'bypassPermissions' : 'acceptEdits';
68
+ export function defaultPermissionMode() {
69
+ return 'auto';
95
70
  }
96
71
  /**
97
72
  * Resolve what someone typed into a mode id, so `/mode plan` works alongside
98
- * the buttons. Accepts the id, the label, and the CLI spelling — `manual` and
99
- * `default` both land on manual, since which word is right depends on which
100
- * transport you last read about.
73
+ * the buttons. Accepts the id and the label. `manual` and `default` both land
74
+ * on manual: the TUI calls the mode manual, and Claude Code's settings and
75
+ * flags have called it default.
101
76
  */
102
77
  export function parsePermissionModeArg(arg) {
103
78
  const norm = arg.trim().toLowerCase().replace(/[\s_-]+/g, '');
@@ -106,8 +81,7 @@ export function parsePermissionModeArg(arg) {
106
81
  if (norm === 'bypass' || norm === 'yolo')
107
82
  return 'bypassPermissions';
108
83
  const hit = PERMISSION_MODES.find((m) => norm === m.id.toLowerCase()
109
- || norm === m.label.toLowerCase().replace(/[\s_-]+/g, '')
110
- || norm === m.cli.toLowerCase());
84
+ || norm === m.label.toLowerCase().replace(/[\s_-]+/g, ''));
111
85
  return hit?.id ?? null;
112
86
  }
113
87
  /** Rows from the bottom holding the mode indicator, which sits under the input box. */
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Starting a chat's claude before its first message.
3
+ *
4
+ * Claude Code takes a few seconds to come up, longer when it replays a
5
+ * resumed conversation, and a chat used to pay that on the first message
6
+ * after picking a project. But the pick is the tell: /dir, /clear and
7
+ * /resume all end with a conversation chosen and no claude running, and the
8
+ * next thing the chat does is almost always a prompt. So the claude is started
9
+ * then, and the prompt finds it waiting — or, sent quickly, waits out only
10
+ * what is left of the startup.
11
+ *
12
+ * It is a guess, so it costs nobody anything when wrong: no question is asked
13
+ * and nothing is reaped to make room for it (memory-guard.ts), a failure is a
14
+ * log line, and a claude nobody ends up using goes the way of any idle one
15
+ * (pty-idle-reaper.ts). Claude Code writes no transcript before its first
16
+ * prompt, so an unused one leaves nothing behind either.
17
+ */
18
+ import { config } from '../config.js';
19
+ import { getPtyProvider } from '../providers/claude-provider.js';
20
+ import { getActiveProviderName } from '../providers/provider-router.js';
21
+ import { ensureCcrRunning } from '../providers/ccr-health.js';
22
+ import { getCcrShimPath } from './ccr-shim.js';
23
+ import { allowPrewarm } from './memory-guard.js';
24
+ import { isProcessing } from './request-queue.js';
25
+ import { sessionManager } from './session-manager.js';
26
+ import { sanitizeError } from '../utils/sanitize.js';
27
+ /**
28
+ * Start `sessionKey`'s claude in the background if it has a project and no
29
+ * claude yet. Call it last, once the handler has settled which conversation
30
+ * the chat is in: the claude is spawned for the session as it stands. Never
31
+ * throws and never waits; resolves to whether a claude was started.
32
+ */
33
+ export async function prewarmClaude(ctx, sessionKey) {
34
+ try {
35
+ if (!config.PREWARM_CLAUDE)
36
+ return false;
37
+ if (!sessionManager.getSession(sessionKey))
38
+ return false;
39
+ const pty = getPtyProvider();
40
+ // A turn in flight starts its own, with its own callbacks.
41
+ if (pty.hasLiveSession(sessionKey) || isProcessing(sessionKey))
42
+ return false;
43
+ // The backend the first message will run on, or that message respawns it.
44
+ const providerName = getActiveProviderName(sessionKey);
45
+ let executableOverride;
46
+ if (providerName === 'ccr') {
47
+ const ccr = await ensureCcrRunning();
48
+ if (ccr.status !== 'ok' && ccr.status !== 'started')
49
+ return false;
50
+ executableOverride = getCcrShimPath();
51
+ // That took a moment; a message may have got there first.
52
+ if (pty.hasLiveSession(sessionKey) || isProcessing(sessionKey))
53
+ return false;
54
+ }
55
+ if (!allowPrewarm(sessionKey)) {
56
+ console.log(`[Prewarm] ${sessionKey}: memory is short, leaving claude for the first message to start`);
57
+ return false;
58
+ }
59
+ return pty.prewarm(sessionKey, {
60
+ providerName,
61
+ ...(executableOverride ? { executableOverride } : {}),
62
+ ...(ctx ? { telegramCtx: ctx } : {}),
63
+ });
64
+ }
65
+ catch (err) {
66
+ console.warn(`[Prewarm] ${sessionKey}: couldn't start claude early: ${sanitizeError(err)}`);
67
+ return false;
68
+ }
69
+ }
70
+ //# sourceMappingURL=prewarm.js.map