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
@@ -23,6 +23,7 @@
23
23
  import * as crypto from 'crypto';
24
24
  import { config } from '../config.js';
25
25
  import { buildLetteredKeyboard, letteredOptionLines, } from '../telegram/lettered-options.js';
26
+ import { TYPED_ANSWER_HINT } from './typed-answer.js';
26
27
  /**
27
28
  * Max characters of `context` we render into the question message. Keeps the
28
29
  * whole message comfortably under Telegram's 4096-char limit even alongside a
@@ -46,9 +47,8 @@ export function questionTimeoutMs() {
46
47
  return questionTimeoutMinutes() * 60 * 1000;
47
48
  }
48
49
  /**
49
- * Build the plain-text body for an ask_user Telegram message, shared by SDK
50
- * mode (mcp-tools.ts) and PTY/IPC mode (mcp-bridge.ts) so both render
51
- * identically.
50
+ * Build the plain-text body for an ask_user Telegram message, for the IPC
51
+ * handler in mcp-bridge.ts.
52
52
  *
53
53
  * Layout:
54
54
  * ❓ <question>
@@ -57,6 +57,8 @@ export function questionTimeoutMs() {
57
57
  *
58
58
  * A. Label — description ← every option, keyed by its letter
59
59
  *
60
+ * ✏️ Or reply with your own answer.
61
+ *
60
62
  * The `context` block is the fix for the "user is asked to choose before the
61
63
  * explanation is shown" bug: prose the model emits *before* calling ask_user
62
64
  * isn't delivered until end-of-turn (after the tap), so decision-relevant
@@ -77,12 +79,13 @@ export function buildAskUserMessageText(question, options, context) {
77
79
  // it.
78
80
  lines.push('');
79
81
  lines.push(...letteredOptionLines(options));
82
+ lines.push('');
83
+ lines.push(TYPED_ANSWER_HINT);
80
84
  return lines.join('\n');
81
85
  }
82
86
  /**
83
- * The inline keyboard for a question, shared by SDK mode (mcp-tools.ts) and
84
- * PTY/IPC mode (mcp-bridge.ts) so both render identically — and with every
85
- * other lettered picker, through {@link buildLetteredKeyboard}.
87
+ * The inline keyboard for a question, for the IPC handler in mcp-bridge.ts —
88
+ * rendered like every other lettered picker, through {@link buildLetteredKeyboard}.
86
89
  */
87
90
  export function buildAskUserKeyboard(id, options) {
88
91
  return buildLetteredKeyboard(options.map((o, idx) => ({ label: o.label, callbackData: `q:${id}:${idx}` })));
@@ -116,12 +119,32 @@ function appendFooter(original, footer) {
116
119
  return appended.length > MAX_MESSAGE_LEN ? null : appended;
117
120
  }
118
121
  /**
119
- * The line an ask_user question ends on once it expires — shared by SDK mode
120
- * and PTY/IPC mode, like the rest of the message.
122
+ * The line an ask_user question ends on once it expires.
121
123
  */
122
124
  export function buildAskUserExpiredNote() {
123
125
  return `No answer within ${questionTimeoutMinutes()} min, so Claude carried on without one.`;
124
126
  }
127
+ /**
128
+ * Wait for a question's answer, or for the tool call that asked it to hang up:
129
+ * claude cancelled the call, as it does when its turn is stopped, or its pty
130
+ * went away. `'hung-up'` then, and the caller withdraws the question and
131
+ * closes its message, which would otherwise wait out the clock looking live
132
+ * and take the next message typed for its answer.
133
+ */
134
+ export function answerOrHangUp(answer, signal) {
135
+ if (!signal)
136
+ return answer;
137
+ if (signal.aborted)
138
+ return Promise.resolve('hung-up');
139
+ return new Promise((resolve) => {
140
+ const onAbort = () => resolve('hung-up');
141
+ signal.addEventListener('abort', onAbort, { once: true });
142
+ void answer.then((value) => {
143
+ signal.removeEventListener('abort', onAbort);
144
+ resolve(value);
145
+ });
146
+ });
147
+ }
125
148
  /**
126
149
  * Close a question nobody answered in time: take its keyboard down and say
127
150
  * what happened where the answer would have gone.
@@ -137,8 +160,21 @@ export function buildAskUserExpiredNote() {
137
160
  * edit Telegram refuses still gets the keyboard taken down on its own.
138
161
  */
139
162
  export async function closeExpiredQuestion(api, message, text, note, entities) {
163
+ await closeQuestion(api, message, appendExpiredFooter(text, note), entities);
164
+ }
165
+ /**
166
+ * Close a question answered by something other than a tap, which bot.ts
167
+ * closes itself: a typed answer. Same fallbacks as {@link closeExpiredQuestion}.
168
+ */
169
+ export async function closeAnsweredQuestion(api, message, text, label, entities) {
170
+ await closeQuestion(api, message, appendAnsweredFooter(text, label), entities);
171
+ }
172
+ /** Close a question claude stopped waiting on (see {@link answerOrHangUp}). Same fallbacks. */
173
+ export async function closeWithdrawnQuestion(api, message, text) {
174
+ await closeQuestion(api, message, appendFooter(text, '🚫 Claude stopped waiting for an answer.'));
175
+ }
176
+ async function closeQuestion(api, message, closed, entities) {
140
177
  const chatId = message.chat.id;
141
- const closed = appendExpiredFooter(text, note);
142
178
  if (closed !== null) {
143
179
  try {
144
180
  await api.editMessageText(chatId, message.message_id, closed, entities ? { entities } : undefined);
@@ -155,7 +191,7 @@ export async function closeExpiredQuestion(api, message, text, note, entities) {
155
191
  catch (err) {
156
192
  // Nothing left to try here. A tap on it still gets the expired answer,
157
193
  // and the tap handler strips the keyboard then.
158
- console.warn('[AskUser] could not close an expired question:', err instanceof Error ? err.message : err);
194
+ console.warn('[AskUser] could not close a question:', err instanceof Error ? err.message : err);
159
195
  }
160
196
  }
161
197
  /**
@@ -172,9 +208,9 @@ export function buildAnswerConfirmation(label, opts) {
172
208
  return `✅ ${who} picked: ${label}`;
173
209
  }
174
210
  const pending = new Map();
175
- // Per-sessionKey pending counter — read by the agent watchdog so it can
176
- // pause its stale-tool/silence timeouts while we're legitimately waiting on
177
- // the user. Counter (not boolean) supports rare overlapping asks per session.
211
+ // Per-sessionKey pending counter: the status bubble reads it to say the turn
212
+ // is waiting on the user. A counter, not a boolean, for the rare overlapping
213
+ // asks in one session.
178
214
  const pendingBySession = new Map();
179
215
  function clearPending(id) {
180
216
  const entry = pending.get(id);
@@ -195,7 +231,7 @@ function clearPending(id) {
195
231
  * Register a new pending question. Returns a short id (hex) and a promise
196
232
  * that resolves with the user's selected option, or `null` on timeout.
197
233
  */
198
- export function createPendingQuestion(optionLabels, timeoutMs = questionTimeoutMs(), sessionKey, allowedResponderIds) {
234
+ export function createPendingQuestion(optionLabels, timeoutMs = questionTimeoutMs(), sessionKey, allowedResponderIds, opts) {
199
235
  const id = crypto.randomBytes(4).toString('hex');
200
236
  let resolveFn;
201
237
  const promise = new Promise((resolve) => {
@@ -212,12 +248,22 @@ export function createPendingQuestion(optionLabels, timeoutMs = questionTimeoutM
212
248
  optionLabels,
213
249
  sessionKey,
214
250
  ...(allowedResponderIds && allowedResponderIds.length > 0 ? { allowedResponderIds } : {}),
251
+ ...(opts?.ownerCloses ? { ownerCloses: true } : {}),
215
252
  });
216
253
  if (sessionKey) {
217
254
  pendingBySession.set(sessionKey, (pendingBySession.get(sessionKey) ?? 0) + 1);
218
255
  }
219
256
  return { id, promise };
220
257
  }
258
+ /**
259
+ * Take a question back without answering it: its promise never settles, and a
260
+ * later tap gets the expired toast. For an asker that stopped needing the
261
+ * answer — the memory guard whose wait found room before anyone tapped, or
262
+ * an ask_user call claude cancelled.
263
+ */
264
+ export function withdrawPendingQuestion(id) {
265
+ clearPending(id);
266
+ }
221
267
  /**
222
268
  * Resolve a pending question with the user's selection. Called by the
223
269
  * Telegram callback-query dispatcher on button tap.
@@ -228,6 +274,31 @@ export function createPendingQuestion(optionLabels, timeoutMs = questionTimeoutM
228
274
  * reopen the question to everyone.
229
275
  */
230
276
  export function resolvePendingQuestion(id, optionIndex, responderId) {
277
+ const entry = claimPending(id, responderId);
278
+ if (typeof entry === 'string')
279
+ return entry;
280
+ const label = entry.optionLabels[optionIndex];
281
+ if (label === undefined) {
282
+ entry.resolve(null);
283
+ return 'resolved';
284
+ }
285
+ entry.resolve({ label, index: optionIndex });
286
+ return 'resolved';
287
+ }
288
+ /**
289
+ * Resolve a pending question with an answer the user typed instead of tapping
290
+ * (see typed-answer.ts). Same outcomes, and the same responder check, as
291
+ * {@link resolvePendingQuestion}.
292
+ */
293
+ export function resolvePendingQuestionWithText(id, text, responderId) {
294
+ const entry = claimPending(id, responderId);
295
+ if (typeof entry === 'string')
296
+ return entry;
297
+ entry.resolve({ label: text, index: -1, typed: true });
298
+ return 'resolved';
299
+ }
300
+ /** Take a question off the books for this responder to answer, or say why they can't. */
301
+ function claimPending(id, responderId) {
231
302
  const entry = pending.get(id);
232
303
  if (!entry)
233
304
  return 'expired';
@@ -238,13 +309,11 @@ export function resolvePendingQuestion(id, optionIndex, responderId) {
238
309
  return 'forbidden';
239
310
  }
240
311
  clearPending(id);
241
- const label = entry.optionLabels[optionIndex];
242
- if (label === undefined) {
243
- entry.resolve(null);
244
- return 'resolved';
245
- }
246
- entry.resolve({ label, index: optionIndex });
247
- return 'resolved';
312
+ return entry;
313
+ }
314
+ /** Whether the asker closes this question's message itself (see PendingEntry.ownerCloses). Read before resolving: resolving drops the entry. */
315
+ export function questionOwnerCloses(id) {
316
+ return pending.get(id)?.ownerCloses === true;
248
317
  }
249
318
  /**
250
319
  * The full label of one option on a pending question — what the model wrote,
@@ -266,9 +335,8 @@ export function getQuestionResponders(id) {
266
335
  }
267
336
  /**
268
337
  * Count a wait on the user that isn't a button question, such as a secret
269
- * request, as one: the watchdog pauses for it and the status bubble says
270
- * the turn is waiting on them. Returns the call that ends the wait, which is
271
- * safe to make more than once.
338
+ * request, as one: the status bubble says the turn is waiting on them.
339
+ * Returns the call that ends the wait, which is safe to make more than once.
272
340
  */
273
341
  export function noteAwaitingUser(sessionKey) {
274
342
  pendingBySession.set(sessionKey, (pendingBySession.get(sessionKey) ?? 0) + 1);
@@ -286,8 +354,8 @@ export function noteAwaitingUser(sessionKey) {
286
354
  }
287
355
  /**
288
356
  * True when there's an outstanding ask-user question for this sessionKey.
289
- * The agent watchdog uses this to pause its timeouts so legitimate waits
290
- * for a button tap don't get force-closed as a "stale tool".
357
+ * The status bubble uses this to say the turn is parked on the user, where
358
+ * it would otherwise go on animating "Thinking…".
291
359
  */
292
360
  export function hasPendingQuestionForSession(sessionKey) {
293
361
  return (pendingBySession.get(sessionKey) ?? 0) > 0;
@@ -63,7 +63,24 @@ function buildInstructions(previousTopic, project) {
63
63
  * meta/acknowledgment messages, and the project's folder name so GENERAL
64
64
  * isn't just that.
65
65
  */
66
+ let callsInFlight = 0;
67
+ /**
68
+ * Side-calls still running. For /botrebuild's "when idle": a restart over
69
+ * one loses the topic it was about to set, and the thread name with it.
70
+ */
71
+ export function topicCallsInFlight() {
72
+ return callsInFlight;
73
+ }
66
74
  export async function summarizeTopicWithHaiku(userMessage, previousTopic, project) {
75
+ callsInFlight++;
76
+ try {
77
+ return await summarize(userMessage, previousTopic, project);
78
+ }
79
+ finally {
80
+ callsInFlight--;
81
+ }
82
+ }
83
+ async function summarize(userMessage, previousTopic, project) {
67
84
  const trimmed = userMessage.trim();
68
85
  if (trimmed.length < 3)
69
86
  return undefined;
@@ -1,32 +1,32 @@
1
1
  /**
2
2
  * What slash commands and skills a working directory actually offers.
3
3
  *
4
- * Claude Code reports this on the SDK init message — `slash_commands` (every
5
- * name the CLI will accept, built-ins and plugin commands and
6
- * `.claude/commands/` alike) and `skills` (the subset backed by a skill, e.g.
7
- * `code-review`). There is no CLI flag that prints either list, and the
8
- * session JSONL doesn't carry them, so the init message is the only source.
9
- *
10
- * SDK-mode turns record it for free. PTY-mode sessions never produce an init
11
- * message, so `probeAvailableCommands` spawns a throwaway headless process to
12
- * fetch one. The probe runs `/usage` — a command the CLI answers locally, with
13
- * no model call and no cost — and we kill the process the moment init arrives.
4
+ * Claude Code reports this on the init message of a headless run —
5
+ * `slash_commands` (every name the CLI will accept, built-ins and plugin
6
+ * commands and `.claude/commands/` alike) and `skills` (the subset backed by a
7
+ * skill, e.g. `code-review`). There is no CLI flag that prints either list,
8
+ * and the session JSONL doesn't carry them, so `probeAvailableCommands` spawns
9
+ * a throwaway headless process to fetch one. The probe runs `/usage` — a
10
+ * command the CLI answers locally, with no model call and no cost — and we
11
+ * kill the process the moment init arrives.
14
12
  */
15
13
  import { spawn } from 'child_process';
16
14
  import { sanitizeError } from '../utils/sanitize.js';
15
+ import { loadsUserSetup, userSetupIsolationArgs } from './pty-spawn-config.js';
17
16
  /**
18
17
  * Cached per (binary, working directory) rather than per session: the answer
19
18
  * depends on the project's `.claude/`, its plugins and the CLI build, none of
20
- * which vary between two chats pointed at the same directory — but the two
21
- * modes do not share a binary. SDK mode runs the bundled CLI from
22
- * node_modules, PTY mode runs whatever `claude` is on PATH, and their command
23
- * sets drift apart between releases (2.1.140 has no `/code-review`; 2.1.241
24
- * does). Listing one mode's commands while the other is active would name
25
- * commands that do not exist.
19
+ * which vary between two chats pointed at the same directory. The binary is
20
+ * part of the key because command sets drift between releases (2.1.140 has no
21
+ * `/code-review`; 2.1.241 does), and a snapshot from another install would
22
+ * name commands that do not exist here.
26
23
  */
27
24
  const cache = new Map();
28
25
  function cacheKey(executable, workingDirectory) {
29
- return `${executable}\u0000${workingDirectory}`;
26
+ // The user setup brings commands and skills of its own (~/.claude, plugins),
27
+ // and whether a chat's claude has it follows the roster, so it is part of
28
+ // what a snapshot is a snapshot of.
29
+ return `${executable}\u0000${workingDirectory}\u0000${loadsUserSetup() ? 'user' : 'project'}`;
30
30
  }
31
31
  /** Re-probe rather than serve a snapshot older than this. */
32
32
  const STALE_AFTER_MS = 30 * 60 * 1000;
@@ -34,7 +34,7 @@ const STALE_AFTER_MS = 30 * 60 * 1000;
34
34
  const PROBE_TIMEOUT_MS = 20_000;
35
35
  /** In-flight probes, so N concurrent /projectcommands spawn one process. */
36
36
  const inFlight = new Map();
37
- /** Record what an SDK init message reported for `workingDirectory`. */
37
+ /** Record what a probe's init message reported for `workingDirectory`. */
38
38
  export function recordAvailableCommands(workingDirectory, executable, slashCommands, skills) {
39
39
  if (!workingDirectory || !Array.isArray(slashCommands))
40
40
  return;
@@ -89,7 +89,10 @@ async function probeAvailableCommands(workingDirectory, executable) {
89
89
  catch { /* already gone */ }
90
90
  resolve(result);
91
91
  };
92
- const child = spawn(executable, ['-p', '/usage', '--output-format', 'stream-json', '--verbose'], { cwd: workingDirectory, stdio: ['ignore', 'pipe', 'ignore'] });
92
+ const child = spawn(executable,
93
+ // With the user setup or without it, as the chats' own claude runs, so
94
+ // the list names what a chat can actually type.
95
+ ['-p', '/usage', '--output-format', 'stream-json', '--verbose', ...userSetupIsolationArgs()], { cwd: workingDirectory, stdio: ['ignore', 'pipe', 'ignore'] });
93
96
  const timer = setTimeout(() => {
94
97
  console.warn(`[AvailableCommands] probe timed out after ${PROBE_TIMEOUT_MS}ms`);
95
98
  finish(undefined);
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Claude Code's "run in background" hint, read off the rendered screen.
3
+ *
4
+ * While a shell command or subagent has been running in the foreground for a
5
+ * couple of seconds, Claude Code draws a line under it that names the key
6
+ * which moves it to the background:
7
+ *
8
+ * ● Bash(npm test)
9
+ * ⎿ tick 5
10
+ * … +3 lines (7s)
11
+ * (ctrl+b to run in background)
12
+ *
13
+ * The turn then carries on without waiting for the command, and the command
14
+ * reports back when it ends, the way one started with run_in_background does.
15
+ * In a terminal that is Ctrl+B; a chat has no such key, so the bot presses it
16
+ * for whoever sends /ctrlb.
17
+ *
18
+ * The hint is the whole test for whether the key does anything. Without a
19
+ * foreground task the same key moves the cursor in the input box, so the bot
20
+ * presses it only while the hint is on screen, and presses the key the hint
21
+ * names: `task:background` can be rebound in keybindings.json.
22
+ *
23
+ * A line that ends in "to background" without the "run in" is a different
24
+ * offer on the same key, to send the whole session to the background and free
25
+ * the terminal. That one is left alone: the bot's pty is the terminal.
26
+ *
27
+ * Only the rows on screen are read. The hint is drawn in the live block at the
28
+ * bottom and redrawn in place, so a copy in scrollback would be a line of the
29
+ * conversation that happens to read the same.
30
+ */
31
+ /** A key as Claude Code spells one: `ctrl+b`, `alt+shift+b`. */
32
+ const KEY = '[a-z0-9]+(?:\\+[a-z0-9]+)+';
33
+ /**
34
+ * The hint, in the three places Claude Code draws it: in brackets of its own
35
+ * under a running command, among other hints joined by ` · `, and alone on a
36
+ * row under the spinner. Group 1 is the key, or the keys of a chord.
37
+ *
38
+ * A row of its own has to start with the key, or any indented sentence that
39
+ * ends in these words would pass for one.
40
+ */
41
+ const HINT_RE = new RegExp(`(?:\\(|· |^\\s+)(${KEY}(?: ${KEY})*)(?: \\(twice\\))? to run in background(?=\\)| ·|\\s*$)`, 'u');
42
+ /** `ctrl+b`, the one kind of key the bot presses here. */
43
+ const CTRL_KEY_RE = /^ctrl\+([a-z])$/u;
44
+ /**
45
+ * The key the hint in `rows` names, or null when no hint is among them.
46
+ *
47
+ * Inside tmux, Claude Code names the key twice (`ctrl+b ctrl+b (twice)`, or
48
+ * just `ctrl+b ctrl+b`): tmux takes the first press as its own prefix. The
49
+ * binding is still the one key, and the bot's pty has no tmux in front of it
50
+ * even when the bot itself was started from one, so a key named twice over is
51
+ * pressed once.
52
+ */
53
+ export function findBackgroundHint(rows) {
54
+ for (let i = rows.length - 1; i >= 0; i--) {
55
+ const m = HINT_RE.exec(rows[i]);
56
+ if (!m)
57
+ continue;
58
+ const keys = m[1].split(' ');
59
+ return keys.length === 2 && keys[0] === keys[1] ? keys[0] : keys.join(' ');
60
+ }
61
+ return null;
62
+ }
63
+ /**
64
+ * What to write to the pty for a key as the hint spells it: `ctrl+b`, or a
65
+ * chord of such keys (`ctrl+x ctrl+b`). Null for anything else, which the bot
66
+ * doesn't guess at.
67
+ */
68
+ export function backgroundKeystroke(key) {
69
+ let out = '';
70
+ for (const part of key.split(' ')) {
71
+ const m = CTRL_KEY_RE.exec(part);
72
+ if (!m)
73
+ return null;
74
+ out += String.fromCharCode(m[1].charCodeAt(0) - 96);
75
+ }
76
+ return out || null;
77
+ }
78
+ /** The rows on screen now, top to bottom. */
79
+ function screenRows(xterm) {
80
+ const buf = xterm.buffer.active;
81
+ const rows = [];
82
+ for (let i = Math.max(0, buf.length - xterm.rows); i < buf.length; i++) {
83
+ rows.push(buf.getLine(i)?.translateToString(true) ?? '');
84
+ }
85
+ return rows;
86
+ }
87
+ /** The key Claude Code offers right now for moving the running task to the background, or null. */
88
+ export function scrapeBackgroundHint(xterm) {
89
+ return findBackgroundHint(screenRows(xterm));
90
+ }
91
+ //# sourceMappingURL=background-hint.js.map
@@ -1,13 +1,13 @@
1
1
  /**
2
- * The fork tree: every transcript that grew out of one conversation, arranged
2
+ * The branch tree: every transcript that grew out of one conversation, arranged
3
3
  * by where each one split off.
4
4
  *
5
- * Nothing records that tree, and nothing has to. A fork is a copy of its
6
- * source's transcript up to the fork point with every record id intact —
7
- * loadFork rewrites only the session id — so transcripts that start with the
5
+ * Nothing records that tree, and nothing has to. A branch is a copy of its
6
+ * source's transcript up to the branch point with every record id intact —
7
+ * loadBranch rewrites only the session id — so transcripts that start with the
8
8
  * same record grew out of the same conversation, and the last record two of
9
9
  * them share is where they split. Reading the tree off the transcripts covers
10
- * forks made before this module existed, forks handed between bots (they all
10
+ * branches made before this module existed, branches handed between bots (they all
11
11
  * write under the one ~/.claude/projects), and branches that fell out of every
12
12
  * /resume list long ago but are still on disk.
13
13
  *
@@ -156,10 +156,10 @@ function mtimeMsOf(file) {
156
156
  }
157
157
  }
158
158
  /**
159
- * Conversations in the project that have been forked — more than one
159
+ * Conversations in the project that have been branched — more than one
160
160
  * transcript starting from the same record — most recently active first.
161
161
  */
162
- export function forkedConversations(projectPath) {
162
+ export function branchedConversations(projectPath) {
163
163
  const dir = transcriptDir(projectPath);
164
164
  const out = [];
165
165
  for (const [rootId, sessionIds] of conversationsIn(projectPath)) {
@@ -307,7 +307,7 @@ function buildTree(projectPath, rootId, sessionIds) {
307
307
  transcripts,
308
308
  };
309
309
  }
310
- /** The tree the transcript `sessionId` belongs to — just itself, if it was never forked. */
310
+ /** The tree the transcript `sessionId` belongs to — just itself, if it was never branched. */
311
311
  export function treeOf(projectPath, sessionId) {
312
312
  const rootId = rootOf(sessionJsonlPath(projectPath, sessionId));
313
313
  if (!rootId)
@@ -390,4 +390,4 @@ export function transcriptUpTo(tree, node) {
390
390
  }
391
391
  return undefined;
392
392
  }
393
- //# sourceMappingURL=fork-tree.js.map
393
+ //# sourceMappingURL=branch-tree.js.map
@@ -3,8 +3,6 @@
3
3
  * conversation can't go on in its own session — a provider switch, or a
4
4
  * /resume of a session another backend wrote — and the next turn has to start
5
5
  * a fresh one. It carries no thinking blocks, so any backend can take it.
6
- *
7
- * Its own module so both the SDK agent and the PTY provider can take from it.
8
6
  */
9
7
  import { BoundedMap } from '../utils/bounded-map.js';
10
8
  const pendingCarryOver = new BoundedMap(1000);
@@ -1,7 +1,7 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { config } from '../config.js';
4
- import { resolveActiveClaudeExecutable } from '../utils/resolve-claude-bin.js';
4
+ import { resolvePtyClaudeBin } from '../utils/resolve-claude-bin.js';
5
5
  import { ensureStateDir, getStateDir } from '../utils/json-store.js';
6
6
  const SHIM_DIR = getStateDir();
7
7
  const SHIM_PATH = path.join(SHIM_DIR, 'claude-via-ccr.sh');
@@ -11,19 +11,15 @@ function shellSingleQuote(value) {
11
11
  }
12
12
  /**
13
13
  * Generate (or refresh) the wrapper script that exports CCR env vars and
14
- * execs the real `claude` binary. Returning the path lets the SDK launch
15
- * `claude` with CCR redirection without ever mutating `process.env` in the
16
- * TeleCoder process — keeping concurrent queries race-free.
14
+ * execs the `claude` the ptys run. Spawning the script in claude's place
15
+ * redirects one pty without ever mutating `process.env` in the TeleCoder
16
+ * process — the chats on Claude keep going to Anthropic.
17
17
  */
18
18
  export function getCcrShimPath() {
19
19
  if (!config.CCR_ENABLED) {
20
20
  throw new Error('CCR is not enabled (set CCR_ENABLED=true)');
21
21
  }
22
- if (cachedShim && fs.existsSync(cachedShim)) {
23
- return cachedShim;
24
- }
25
- ensureStateDir(SHIM_DIR, 'CcrShim');
26
- const realClaude = resolveActiveClaudeExecutable();
22
+ const realClaude = resolvePtyClaudeBin();
27
23
  const baseUrl = shellSingleQuote(config.CCR_BASE_URL);
28
24
  const authToken = shellSingleQuote(config.CCR_AUTH_TOKEN);
29
25
  const target = shellSingleQuote(realClaude);
@@ -35,8 +31,14 @@ export ANTHROPIC_AUTH_TOKEN=${authToken}
35
31
  unset ANTHROPIC_API_KEY
36
32
  exec ${target} "$@"
37
33
  `;
34
+ // Rewritten when the target or the proxy settings changed, not on every
35
+ // turn: the script is read at each spawn.
36
+ if (cachedShim?.script === script && fs.existsSync(SHIM_PATH)) {
37
+ return SHIM_PATH;
38
+ }
39
+ ensureStateDir(SHIM_DIR, 'CcrShim');
38
40
  fs.writeFileSync(SHIM_PATH, script, { mode: 0o700 });
39
- cachedShim = SHIM_PATH;
41
+ cachedShim = { path: SHIM_PATH, script };
40
42
  return SHIM_PATH;
41
43
  }
42
44
  /** Force-regenerate the shim on next call (e.g. after config change). */
@@ -1,16 +1,12 @@
1
1
  /**
2
2
  * Recognising "Claude Code isn't logged in", and saying so in the chat.
3
3
  *
4
- * On a machine where nobody has signed in, the bundled CLI answers every
5
- * prompt with `Not logged in · Please run /login`. Over the SDK that arrives as
6
- * an error result, and the query then throws "Claude Code returned an error
7
- * result: Not logged in · Please run /login" — which reached the chat as
8
- * `❌ Error: Claude error: Claude Code returned an error result: …`, telling the
9
- * person on their phone to run a command they can't. Over the PTY a fresh
10
- * install never gets that far: the interactive CLI opens its first-run
11
- * onboarding (theme picker, then "Select login method"), which is no place to
12
- * relay to a chat — signing in wants a browser on, or a terminal at, the bot's
13
- * machine.
4
+ * On a machine where nobody has signed in, the CLI answers every prompt with
5
+ * `Not logged in · Please run /login`, which relayed as it is tells the person
6
+ * on their phone to run a command they can't. A fresh install doesn't even
7
+ * get that far: the interactive CLI opens its first-run onboarding (theme
8
+ * picker, then "Select login method"), which is no place to relay to a chat —
9
+ * signing in wants a browser on, or a terminal at, the bot's machine.
14
10
  *
15
11
  * Kept free of config imports so tests can call it directly.
16
12
  */