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
@@ -22,6 +22,7 @@ import * as os from 'os';
22
22
  import * as path from 'path';
23
23
  import { config } from '../config.js';
24
24
  import { getWorkspaceRoot } from '../utils/workspace-guard.js';
25
+ import { getUploadsRoot } from '../utils/uploads-dir.js';
25
26
  /** Tools whose input names a path we can check directly. */
26
27
  const PATH_FIELDS = {
27
28
  Read: ['file_path'],
@@ -96,7 +97,7 @@ export function isScopeGuardEnabled(gateEnabled) {
96
97
  * because every toolchain writes there and nothing durable lives there.
97
98
  */
98
99
  export function getAllowedRoots() {
99
- const roots = [getWorkspaceRoot(), os.tmpdir(), '/tmp', ...config.SCOPE_ALLOWED_PATHS];
100
+ const roots = [getWorkspaceRoot(), os.tmpdir(), '/tmp', getUploadsRoot(), ...config.SCOPE_ALLOWED_PATHS];
100
101
  return dedupe(roots.map((r) => path.resolve(r)));
101
102
  }
102
103
  /**
@@ -222,13 +223,17 @@ export function extractPathTokens(command) {
222
223
  }
223
224
  /**
224
225
  * Is this absolute path a credential or bot-state path? The same denylist the
225
- * tool-call check uses, for other ways of reaching a file — `/file` and
226
- * `/telegraph <path>` — so there is one list to keep current.
226
+ * tool-call check uses, for the other ways a file leaves the machine — `/file`
227
+ * and the send-file tool — so there is one list to keep current.
227
228
  */
228
229
  export function isSensitivePath(absolutePath) {
229
230
  return isSensitive(path.resolve(absolutePath));
230
231
  }
231
232
  function isSensitive(resolved) {
233
+ // The one corner of the bot's state that holds the user's own files: what
234
+ // they sent in the chat, saved there for Claude to read (utils/uploads-dir.ts).
235
+ if (within(getUploadsRoot(), resolved))
236
+ return false;
232
237
  const segments = resolved.split(path.sep).filter(Boolean);
233
238
  if (segments.some((s) => SENSITIVE_SEGMENTS.includes(s)))
234
239
  return true;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * How the screen is drawn, for the two things Claude Code says in colour only.
3
+ *
4
+ * Which tab of a dialog is open: `/permissions` and `/config` print every
5
+ * tab's name in one row and fill the open one's background. And which list
6
+ * holds the cursor: `/memory` has two, each with a `❯` of its own, and
7
+ * `/config` keeps its `❯` on screen while the keys go to the search box above
8
+ * it. The glyph that isn't taking keys is drawn grey. As plain text, each of
9
+ * those pairs reads the same.
10
+ *
11
+ * So the screen gets a second reading, the same shape as its text: one mark
12
+ * for every character, row for row, saying only what the dialog parser needs
13
+ * to know about it. Colours themselves stay out of it. Which blue a theme
14
+ * fills a tab with is no business of the parser's, and a test can write a
15
+ * row of marks by hand.
16
+ */
17
+ /** Drawn on a filled background, or in reverse video: the open tab. */
18
+ export const FILLED = '#';
19
+ /** Drawn grey or dim: a cursor glyph whose list isn't taking keys. */
20
+ export const MUTED = '.';
21
+ /** Anything else. */
22
+ export const PLAIN = ' ';
23
+ /** The 256-colour palette's grey ramp, and the two greys of the 16 before it. */
24
+ function greyInPalette(index) {
25
+ return index === 7 || index === 8 || (index >= 232 && index <= 255);
26
+ }
27
+ /** How far apart an RGB grey's channels may sit. */
28
+ const GREY_SPREAD = 12;
29
+ function greyRgb(color) {
30
+ const channels = [(color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff];
31
+ return Math.max(...channels) - Math.min(...channels) <= GREY_SPREAD;
32
+ }
33
+ function markFor(cell) {
34
+ if (cell.isInverse() || cell.isBgRGB() || cell.isBgPalette())
35
+ return FILLED;
36
+ if (cell.isDim())
37
+ return MUTED;
38
+ if (cell.isFgPalette() && greyInPalette(cell.getFgColor()))
39
+ return MUTED;
40
+ if (cell.isFgRGB() && greyRgb(cell.getFgColor()))
41
+ return MUTED;
42
+ return PLAIN;
43
+ }
44
+ /**
45
+ * The marks for every row of the terminal's buffer, scrollback included,
46
+ * joined by newlines: row `n` here is row `n` of the buffer read as text with
47
+ * `translateToString`, and character `k` of one is character `k` of the
48
+ * other. A row of marks runs the terminal's full width, so it is as long as
49
+ * its text or longer.
50
+ *
51
+ * Only the rows on screen are read. A dialog is drawn there and nowhere else,
52
+ * and the scrollback above can be thousands of rows, read cell by cell on
53
+ * every poll of a relay waiting for a key to land. Its rows come back empty,
54
+ * which reads as "nothing marked".
55
+ */
56
+ export function screenMarks(term) {
57
+ const buffer = term.buffer.active;
58
+ const rows = [];
59
+ let cell;
60
+ const onScreen = Math.max(0, buffer.length - term.rows);
61
+ for (let y = 0; y < buffer.length; y++) {
62
+ if (y < onScreen) {
63
+ rows.push('');
64
+ continue;
65
+ }
66
+ const line = buffer.getLine(y);
67
+ let row = '';
68
+ for (let x = 0; x < term.cols; x++) {
69
+ cell = line?.getCell(x, cell);
70
+ if (!cell) {
71
+ row += PLAIN;
72
+ continue;
73
+ }
74
+ // The second half of a wide character adds nothing to the text either.
75
+ if (cell.getWidth() === 0)
76
+ continue;
77
+ row += markFor(cell).repeat((cell.getChars() || ' ').length);
78
+ }
79
+ rows.push(row);
80
+ }
81
+ return rows.join('\n');
82
+ }
83
+ //# sourceMappingURL=screen-marks.js.map
@@ -0,0 +1,96 @@
1
+ /**
2
+ * A headless terminal's visible screen, as text another terminal can show.
3
+ *
4
+ * `telecoder watch` uses it on both ends: the bot turns a claude's screen into
5
+ * a snapshot for a watcher that has just joined, and the watcher paints its own
6
+ * copy of the screen row by row. Each row is written out cell by cell with its
7
+ * colours, so nothing depends on the watching terminal being the same size as
8
+ * claude's: a row never relies on wrapping or scrolling to land where it should.
9
+ */
10
+ const RESET = '\x1b[0m';
11
+ /** The SGR parameters for one cell's look; '' for plain text. */
12
+ function cellStyle(cell) {
13
+ const sgr = [];
14
+ if (cell.isBold())
15
+ sgr.push('1');
16
+ if (cell.isDim())
17
+ sgr.push('2');
18
+ if (cell.isItalic())
19
+ sgr.push('3');
20
+ if (cell.isUnderline())
21
+ sgr.push('4');
22
+ if (cell.isInverse())
23
+ sgr.push('7');
24
+ if (cell.isInvisible())
25
+ sgr.push('8');
26
+ if (cell.isStrikethrough())
27
+ sgr.push('9');
28
+ if (cell.isFgRGB()) {
29
+ const c = cell.getFgColor();
30
+ sgr.push(`38;2;${(c >> 16) & 0xff};${(c >> 8) & 0xff};${c & 0xff}`);
31
+ }
32
+ else if (cell.isFgPalette()) {
33
+ sgr.push(`38;5;${cell.getFgColor()}`);
34
+ }
35
+ if (cell.isBgRGB()) {
36
+ const c = cell.getBgColor();
37
+ sgr.push(`48;2;${(c >> 16) & 0xff};${(c >> 8) & 0xff};${c & 0xff}`);
38
+ }
39
+ else if (cell.isBgPalette()) {
40
+ sgr.push(`48;5;${cell.getBgColor()}`);
41
+ }
42
+ return sgr.join(';');
43
+ }
44
+ /**
45
+ * The visible rows, top to bottom, each exactly as wide as the screen (or
46
+ * `maxCols`), ending with its colours reset.
47
+ */
48
+ export function renderRows(term, { maxCols } = {}) {
49
+ const buffer = term.buffer.active;
50
+ const cols = Math.min(term.cols, maxCols ?? term.cols);
51
+ const rows = [];
52
+ for (let y = 0; y < term.rows; y++) {
53
+ const line = buffer.getLine(buffer.baseY + y);
54
+ let out = '';
55
+ let style = '';
56
+ let cell;
57
+ for (let x = 0; x < cols; x++) {
58
+ cell = line?.getCell(x, cell);
59
+ if (!cell) {
60
+ out += ' ';
61
+ continue;
62
+ }
63
+ const width = cell.getWidth();
64
+ // The second half of a wide character: its first half already drew it.
65
+ if (width === 0)
66
+ continue;
67
+ // A wide character that would stick out past the last column.
68
+ if (width === 2 && x + 1 >= cols) {
69
+ out += ' ';
70
+ continue;
71
+ }
72
+ const next = cellStyle(cell);
73
+ if (next !== style) {
74
+ out += (style ? RESET : '') + (next ? `\x1b[${next}m` : '');
75
+ style = next;
76
+ }
77
+ out += cell.getChars() || ' ';
78
+ }
79
+ rows.push(style ? out + RESET : out);
80
+ }
81
+ return rows;
82
+ }
83
+ /**
84
+ * The screen as one string that, written to a cleared terminal at least as
85
+ * large, shows the same picture with the cursor in the same place.
86
+ */
87
+ export function screenSnapshot(term) {
88
+ const buffer = term.buffer.active;
89
+ const rows = renderRows(term);
90
+ let out = '\x1b[0m\x1b[2J';
91
+ rows.forEach((row, y) => {
92
+ out += `\x1b[${y + 1};1H${row}`;
93
+ });
94
+ return `${out}\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}H`;
95
+ }
96
+ //# sourceMappingURL=screen-render.js.map
@@ -82,7 +82,7 @@ class SessionHistory {
82
82
  save() {
83
83
  writeJsonFile(this.historyFile, this.data, 'SessionHistory');
84
84
  }
85
- saveSession(sessionKey, conversationId, projectPath, lastMessagePreview = '', claudeSessionId, ownerProvider) {
85
+ saveSession(sessionKey, conversationId, projectPath, lastMessagePreview = '', claudeSessionId, ownerProvider, { touch = true } = {}) {
86
86
  if (!this.data.sessions[sessionKey]) {
87
87
  this.data.sessions[sessionKey] = [];
88
88
  }
@@ -103,7 +103,9 @@ class SessionHistory {
103
103
  createdAt: existingIndex >= 0
104
104
  ? history[existingIndex].createdAt
105
105
  : new Date().toISOString(),
106
- lastActivity: new Date().toISOString(),
106
+ // A restore isn't use: left to stamp the time, every restart made every
107
+ // thread restored look just used, and /threadcleanup never saw one go idle.
108
+ lastActivity: !touch && existingEntry ? existingEntry.lastActivity : new Date().toISOString(),
107
109
  };
108
110
  // The entry saved is always the conversation the chat is now in — a new
109
111
  // one, or one it went back to — so it goes to the front. Everything that
@@ -2,6 +2,7 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import * as os from 'os';
4
4
  import * as crypto from 'crypto';
5
+ import { tablesToLists } from '../telegram/table-lists.js';
5
6
  /** True if this record is the synthetic "API Error" stop record Claude Code writes when an in-flight request dies. */
6
7
  function isApiErrorRecord(rec) {
7
8
  return rec.isApiErrorMessage === true;
@@ -16,7 +17,7 @@ function isApiErrorRecord(rec) {
16
17
  * Boundary logic that only asks "is this a user record with prose?" then slices
17
18
  * the turn at the notification and hands back nothing but the tail the model
18
19
  * wrote after it — the whole answer above it is silently dropped. That is the
19
- * "reply arrives truncated, /recap shows the rest" bug, and it lands exactly
20
+ * "reply arrives truncated, /history shows the rest" bug, and it lands exactly
20
21
  * where the user least wants it: long turns that ran background work.
21
22
  *
22
23
  * Denylist rather than `origin.kind === 'human'` allowlist on purpose. Records
@@ -65,7 +66,7 @@ export function claudeSessionFileExists(workingDirectory, sessionId) {
65
66
  }
66
67
  /**
67
68
  * Mtime (ms since epoch) of the session's JSONL log, or 0 if it doesn't exist
68
- * yet. Used by PTY mode as an end-of-turn signal — claude flushes a fresh
69
+ * yet. Used by the pty provider as an end-of-turn signal — claude flushes a fresh
69
70
  * record to the log for every assistant message, tool call, system event,
70
71
  * compaction boundary, etc., so a moving mtime is reliable evidence that
71
72
  * claude actually did work for the current prompt (the prior bullet-count
@@ -92,6 +93,8 @@ export function sessionJsonlSize(workingDirectory, sessionId) {
92
93
  const LOCAL_COMMAND_OUTPUT = /<local-command-(stdout|stderr)>([\s\S]*?)<\/local-command-\1>/g;
93
94
  /** The colour codes a command's printed output can keep. */
94
95
  const ANSI_SGR = /\x1b\[[0-9;]*m/g;
96
+ /** A markdown copy of a command's report opens with a heading: `## Context Usage`. */
97
+ const MARKDOWN_COPY = /^\s*#{1,6} /;
95
98
  /**
96
99
  * What a slash command answered with, from the records it appended to the log
97
100
  * after `fromByte`, or undefined when it wrote nothing worth showing.
@@ -103,6 +106,11 @@ const ANSI_SGR = /\x1b\[[0-9;]*m/g;
103
106
  * on a user record or a system one depending on the line. Only the turn's own
104
107
  * records are read, because the latest reply in the log is, for a command
105
108
  * like that, the reply to whatever came before it.
109
+ *
110
+ * `/context` prints a drawing: a grid of ⛁ and ⛶ beside the legend, laid out
111
+ * for a terminal's fixed-width columns. Claude Code also logs the same report
112
+ * as markdown for the model, on a meta user record, and that copy is the
113
+ * answer instead, its tables as lists (see tablesToLists).
106
114
  */
107
115
  export function readCommandReply(workingDirectory, sessionId, fromByte) {
108
116
  let log;
@@ -121,6 +129,7 @@ export function readCommandReply(workingDirectory, sessionId, fromByte) {
121
129
  export function commandReplyIn(raw) {
122
130
  const prose = [];
123
131
  const printed = [];
132
+ const markdownCopies = [];
124
133
  for (const line of raw.split('\n')) {
125
134
  if (!line.trim())
126
135
  continue;
@@ -140,6 +149,10 @@ export function commandReplyIn(raw) {
140
149
  }
141
150
  else if (rec.type === 'user' || rec.type === 'system') {
142
151
  const text = typeof rec.content === 'string' ? rec.content : extractText(rec.message?.content);
152
+ if (rec.type === 'user' && rec.isMeta === true && MARKDOWN_COPY.test(text)) {
153
+ markdownCopies.push(text.trim());
154
+ continue;
155
+ }
143
156
  for (const match of text.matchAll(LOCAL_COMMAND_OUTPUT)) {
144
157
  const out = match[2].replace(ANSI_SGR, '').trim();
145
158
  if (out)
@@ -149,6 +162,10 @@ export function commandReplyIn(raw) {
149
162
  }
150
163
  if (prose.length > 0)
151
164
  return prose.join('\n\n');
165
+ // Only beside printed output: a custom command's expanded prompt is a meta
166
+ // record too, and can open with a heading, but prints nothing.
167
+ if (printed.length > 0 && markdownCopies.length > 0)
168
+ return markdownCopies.map(tablesToLists).join('\n\n');
152
169
  return printed.length > 0 ? printed.join('\n') : undefined;
153
170
  }
154
171
  /**
@@ -175,6 +192,11 @@ export function readLastUsageFromJsonl(workingDirectory, sessionId) {
175
192
  const lines = raw.split('\n');
176
193
  let numTurns = 0;
177
194
  let lastUsage;
195
+ // From the `api-request` record the CLI writes before each call: the effort
196
+ // and model that request went out with. /info shows the pair as what
197
+ // actually served the reply, with the reply's own model taking precedence.
198
+ let lastEffort = '';
199
+ let lastRequestModel = '';
178
200
  for (const line of lines) {
179
201
  if (!line)
180
202
  continue;
@@ -187,6 +209,16 @@ export function readLastUsageFromJsonl(workingDirectory, sessionId) {
187
209
  }
188
210
  if (rec.type === 'user')
189
211
  numTurns++;
212
+ if (rec.type === 'api-request') {
213
+ const params = rec.params;
214
+ const outputConfig = params?.output_config;
215
+ const effort = outputConfig?.effort ?? params?.effort;
216
+ if (typeof effort === 'string')
217
+ lastEffort = effort;
218
+ if (typeof params?.model === 'string')
219
+ lastRequestModel = params.model;
220
+ continue;
221
+ }
190
222
  // Skip the synthetic API-error record: its usage is all zeros and would
191
223
  // wipe out the legitimate cumulative totals from the real assistant turn
192
224
  // that ran just before it.
@@ -203,6 +235,7 @@ export function readLastUsageFromJsonl(workingDirectory, sessionId) {
203
235
  cacheReadTokens: 0,
204
236
  cacheWriteTokens: 0,
205
237
  model: lastUsage?.model ?? '',
238
+ effort: '',
206
239
  numTurns: 0,
207
240
  };
208
241
  }
@@ -218,12 +251,16 @@ export function readLastUsageFromJsonl(workingDirectory, sessionId) {
218
251
  cacheReadTokens: typeof usage.cache_read_input_tokens === 'number' ? usage.cache_read_input_tokens : 0,
219
252
  cacheWriteTokens: typeof usage.cache_creation_input_tokens === 'number' ? usage.cache_creation_input_tokens : 0,
220
253
  model: typeof msg?.model === 'string' ? msg.model : '',
254
+ effort: '',
221
255
  numTurns: 0, // filled in after the loop
222
256
  };
223
257
  }
224
258
  if (!lastUsage)
225
259
  return undefined;
226
260
  lastUsage.numTurns = numTurns;
261
+ lastUsage.effort = lastEffort;
262
+ if (!lastUsage.model)
263
+ lastUsage.model = lastRequestModel;
227
264
  return lastUsage;
228
265
  }
229
266
  /** First numeric value among `keys` on `obj`, or 0. Tolerates snake/camel drift. */
@@ -254,9 +291,9 @@ function compactionInfo(rec) {
254
291
  * Return the most recent `compact_boundary` record from a session log, or
255
292
  * undefined if the log has none. Claude Code appends one of these whenever the
256
293
  * context is compacted — manually (`/compact`) or automatically near the limit
257
- * — but renders no `●` glyph for it, so PTY-mode screen scraping can't see that
258
- * a compaction happened. Reading it back from the JSONL lets the PTY provider
259
- * surface the same "Context Compacted" feedback the SDK path already gives.
294
+ * — but renders no `●` glyph for it, so screen scraping can't see that a
295
+ * compaction happened. Reading it back from the JSONL is how the provider
296
+ * knows to send the "Context Compacted" notice.
260
297
  *
261
298
  * On-disk shape (Claude Code 2.1.x):
262
299
  * {"type":"system","subtype":"compact_boundary",
@@ -305,7 +342,7 @@ export function extractText(content) {
305
342
  }
306
343
  /**
307
344
  * Return the joined text of every assistant content block emitted since the
308
- * most recent `type:'user'` record. PTY-mode end-of-turn extraction uses this
345
+ * most recent `type:'user'` record. End-of-turn extraction uses this
309
346
  * instead of scraping the xterm buffer because a single turn can produce
310
347
  * multiple `●` text blocks interleaved with tool calls — screen-scrape only
311
348
  * picks the last `●`, silently dropping the earlier blocks. Returns undefined
@@ -320,7 +357,7 @@ export function readLastAssistantTurnText(workingDirectory, sessionId) {
320
357
  }
321
358
  /**
322
359
  * {@link readLastAssistantTurnText} over a transcript already in hand rather
323
- * than on disk — a fork's cut of one, which has no file until it is loaded.
360
+ * than on disk — a branch's cut of one, which has no file until it is loaded.
324
361
  */
325
362
  export function lastAssistantTurnText(raw) {
326
363
  // Walk forward; every real user prompt starts the collection over, so what
@@ -594,11 +631,23 @@ function turnsIn(raw) {
594
631
  });
595
632
  return turns;
596
633
  }
634
+ /** What a record that follows nothing is filed under, among the ids of the records others follow. */
635
+ const NO_PARENT = '';
597
636
  /**
598
637
  * Every record in a transcript that carries prose, each as a turn of its own:
599
638
  * what the user sent and what the assistant wrote back, in order. With them,
600
639
  * the line of the file's last record that has an id: where its conversation
601
640
  * stands.
641
+ *
642
+ * Turns a `/rewind` took back are left out. Claude Code doesn't delete them:
643
+ * the log is append-only, so they stay in the file and the next prompt is
644
+ * written after them, following the record the rewound prompt followed. Two
645
+ * things the user sent that follow the same record are therefore one that
646
+ * replaced the other, and everything from the first up to the second is no
647
+ * longer the conversation. Read in file order, /history and /prompts showed
648
+ * turns Claude no longer has. A prompt stopped before it got any reply is
649
+ * replaced the same way, and for the same reason: Claude Code takes it back
650
+ * out of the conversation and hands it to the input box.
602
651
  */
603
652
  function proseRecordsIn(raw) {
604
653
  const records = [];
@@ -637,7 +686,22 @@ function proseRecordsIn(raw) {
637
686
  // something the user said either.
638
687
  if (role === 'user' && userTextKind(text) === 'note')
639
688
  continue;
640
- records.push({ role, text, timestamp: rec.timestamp, uuid, line: i + 1, cutBefore });
689
+ // A conversation's first prompt follows nothing, and says so with a null.
690
+ // One sent after a rewind to before it follows nothing either.
691
+ const parentUuid = role !== 'user' ? undefined
692
+ : typeof rec.parentUuid === 'string' ? rec.parentUuid
693
+ : rec.parentUuid === null ? NO_PARENT : undefined;
694
+ const replaced = parentUuid === undefined ? -1 : records.findIndex((r) => r.parentUuid === parentUuid);
695
+ if (replaced === -1) {
696
+ records.push({ role, text, timestamp: rec.timestamp, uuid, parentUuid, line: i + 1, cutBefore });
697
+ continue;
698
+ }
699
+ // The exchange before the rewound stretch ends where that stretch began,
700
+ // not at the record above this one, which is the last of what was taken
701
+ // back. A branch cut there would end on it, and carry on from it.
702
+ const endsBefore = records[replaced].cutBefore;
703
+ records.length = replaced;
704
+ records.push({ role, text, timestamp: rec.timestamp, uuid, parentUuid, line: i + 1, cutBefore: endsBefore });
641
705
  }
642
706
  return { records, lastRecordLine };
643
707
  }
@@ -650,8 +714,8 @@ export function readRecentExchanges(workingDirectory, sessionId, n) {
650
714
  return pairExchanges(readTurns(workingDirectory, sessionId)).slice(-n);
651
715
  }
652
716
  /**
653
- * The last exchange of a transcript already in hand — a fork's, say — paired
654
- * the way /recap pairs them, so the two show the same thing.
717
+ * The last exchange of a transcript already in hand — a branch's, say — paired
718
+ * the way /history pairs them, so the two show the same thing.
655
719
  */
656
720
  export function lastExchangeIn(raw) {
657
721
  return pairExchanges(turnsIn(raw)).at(-1);
@@ -813,10 +877,57 @@ export function detectOwnerProvider(file) {
813
877
  * A transcript with every record's `sessionId` set to `newSessionId`. Claude
814
878
  * Code stamps the session's id into each record, and a resume can get
815
879
  * confused when a copy's filename and contents disagree.
880
+ *
881
+ * A plain text replace of the one id the records carry, read from the first
882
+ * record that has one: parsing and re-serializing every record took half a
883
+ * second of the event loop on a 54 MB transcript, during which no chat on the
884
+ * bot got a reply, where this takes a few milliseconds and leaves every other
885
+ * byte as it was. The id is replaced wherever that exact field text occurs, so
886
+ * a tool result that quoted a record of the transcript changes too, which is
887
+ * harmless. A transcript whose records carry more than one id — none Claude
888
+ * Code writes, but a hand-merged file could — takes the record-by-record path.
816
889
  */
817
890
  export function rewriteJsonlSessionId(jsonl, newSessionId) {
818
891
  if (!jsonl.trim())
819
892
  return jsonl;
893
+ const oldSessionId = firstSessionId(jsonl);
894
+ if (oldSessionId !== undefined) {
895
+ const rewritten = oldSessionId === newSessionId
896
+ ? jsonl
897
+ : jsonl.split(`"sessionId":"${oldSessionId}"`).join(`"sessionId":"${newSessionId}"`);
898
+ const leftover = new RegExp(`"sessionId"\\s*:\\s*"(?!${escapeRegExp(newSessionId)}")`);
899
+ if (!leftover.test(rewritten))
900
+ return rewritten;
901
+ }
902
+ return rewriteJsonlSessionIdPerRecord(jsonl, newSessionId);
903
+ }
904
+ /** The `sessionId` of the first record that has one, or undefined. */
905
+ function firstSessionId(jsonl) {
906
+ let start = 0;
907
+ while (start < jsonl.length) {
908
+ let end = jsonl.indexOf('\n', start);
909
+ if (end === -1)
910
+ end = jsonl.length;
911
+ const line = jsonl.slice(start, end);
912
+ start = end + 1;
913
+ if (!line.includes('"sessionId"'))
914
+ continue;
915
+ try {
916
+ const rec = JSON.parse(line);
917
+ if (typeof rec.sessionId === 'string')
918
+ return rec.sessionId;
919
+ }
920
+ catch {
921
+ // Not a record; keep looking.
922
+ }
923
+ }
924
+ return undefined;
925
+ }
926
+ function escapeRegExp(s) {
927
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
928
+ }
929
+ /** rewriteJsonlSessionId, one record at a time: exact, and slow on a large transcript. */
930
+ function rewriteJsonlSessionIdPerRecord(jsonl, newSessionId) {
820
931
  const lines = jsonl.split('\n');
821
932
  const out = [];
822
933
  for (const line of lines) {
@@ -849,7 +960,43 @@ function endsTurn(rec) {
849
960
  return rec.type === 'user' && /^\[Request interrupted/.test(extractText(rec.message?.content).trim());
850
961
  }
851
962
  /**
852
- * A transcript whose last turn is still running, as a fork that leaves that
963
+ * Whether the log has the end of the turn running in it: its last
964
+ * conversation record closes a turn (see endsTurn). Claude Code writes an
965
+ * assistant message's records only once the whole message is in, so while a
966
+ * reply is still being written the log ends on the prompt, or on the turn's
967
+ * last tool result. A log that can't be read answers true, since there is
968
+ * nothing in it to wait for.
969
+ */
970
+ export function readTurnEnded(workingDirectory, sessionId) {
971
+ let raw;
972
+ try {
973
+ raw = fs.readFileSync(sessionJsonlPath(workingDirectory, sessionId), 'utf-8');
974
+ }
975
+ catch {
976
+ return true;
977
+ }
978
+ return turnEndedIn(raw);
979
+ }
980
+ /** {@link readTurnEnded} over a transcript already in hand. */
981
+ export function turnEndedIn(raw) {
982
+ const lines = raw.split('\n');
983
+ for (let i = lines.length - 1; i >= 0; i--) {
984
+ if (!lines[i].trim())
985
+ continue;
986
+ let rec;
987
+ try {
988
+ rec = JSON.parse(lines[i]);
989
+ }
990
+ catch {
991
+ continue;
992
+ }
993
+ if (rec.type === 'user' || rec.type === 'assistant')
994
+ return endsTurn(rec);
995
+ }
996
+ return true;
997
+ }
998
+ /**
999
+ * A transcript whose last turn is still running, as a branch that leaves that
853
1000
  * turn out but knows it's under way: everything up to the last turn that
854
1001
  * ended, then what opened the running one (the prompt, or a background task
855
1002
  * reporting back), then `note` as the reply to it.
@@ -857,14 +1004,14 @@ function endsTurn(rec) {
857
1004
  * The running turn's own records stay out because half a turn doesn't resume:
858
1005
  * a tool call with no result is one the API turns down. The prompt goes in as
859
1006
  * its own record, copied whole, rather than quoted in the next message, so
860
- * however long it is nothing blurs it into what's sent next, and the fork
1007
+ * however long it is nothing blurs it into what's sent next, and the branch
861
1008
  * remembers it through a resume. The reply has no thinking block, since one
862
1009
  * needs a signature only the API can make.
863
1010
  *
864
1011
  * Without anything on disk yet for the running turn, there's nothing to answer
865
- * with the note, and the fork is the transcript up to the last turn that ended.
1012
+ * with the note, and the branch is the transcript up to the last turn that ended.
866
1013
  */
867
- export function forkPastRunningTurn(raw, note) {
1014
+ export function branchPastRunningTurn(raw, note) {
868
1015
  const lines = raw.split('\n').filter((line) => line.trim());
869
1016
  const records = lines.map((line) => {
870
1017
  try {
@@ -905,7 +1052,7 @@ export function forkPastRunningTurn(raw, note) {
905
1052
  stop_reason: 'end_turn',
906
1053
  stop_sequence: null,
907
1054
  // The context as it stood before the running prompt, near enough for the
908
- // status line until the fork's first turn reports its own.
1055
+ // status line until the branch's first turn reports its own.
909
1056
  usage: template?.message?.usage ?? { input_tokens: 0, output_tokens: 0 },
910
1057
  },
911
1058
  type: 'assistant',
@@ -38,7 +38,7 @@ class SessionManager {
38
38
  // sessionKey. Compared against the JSONL's latest assistant turn to detect
39
39
  // gaps introduced by extractor edge cases (pure tool-call turns, lossy
40
40
  // screen-scrape fallback, early end-of-turn before JSONL flush). In-memory
41
- // only — after a restart we assume "caught up to nothing" so /sync will
41
+ // only — after a restart we assume "caught up to nothing" so /resend will
42
42
  // surface the most recent turn, which is the safer default.
43
43
  lastRelayedAssistantText = new Map();
44
44
  getSession(sessionKey) {
@@ -94,19 +94,39 @@ class SessionManager {
94
94
  sessionHistory.saveSession(sessionKey, existing.conversationId, directory, '', existing.claudeSessionId);
95
95
  return existing;
96
96
  }
97
- // Different directory: start a new conversation. The Agent SDK session
97
+ // Different directory: start a new conversation. The Claude Code session
98
98
  // is bound to the original cwd, so we mint a fresh conversationId and
99
99
  // leave the prior history entry intact for "back to previous project".
100
100
  return this.createSession(sessionKey, directory);
101
101
  }
102
102
  return this.createSession(sessionKey, directory);
103
103
  }
104
+ /**
105
+ * The same conversation, now under `directory`: Claude Code's /cd moved the
106
+ * session there (session-move.ts). Unlike setWorkingDirectory, which starts
107
+ * a new conversation in another project, nothing else changes.
108
+ */
109
+ moveSession(sessionKey, directory) {
110
+ const existing = this.sessions.get(sessionKey);
111
+ if (!existing)
112
+ return undefined;
113
+ existing.workingDirectory = directory;
114
+ const entry = sessionHistory.getSessionByConversationId(sessionKey, existing.conversationId);
115
+ sessionHistory.saveSession(sessionKey, existing.conversationId, directory, entry?.lastMessagePreview ?? '', existing.claudeSessionId, existing.ownerProvider, { touch: false });
116
+ return existing;
117
+ }
104
118
  clearSession(sessionKey) {
105
119
  this.sessions.delete(sessionKey);
106
120
  this.lastRelayedAssistantText.delete(sessionKey);
107
121
  // Note: We don't clear history here - history is for resuming past sessions
108
122
  }
109
- resumeSession(sessionKey, conversationId) {
123
+ /**
124
+ * Make a conversation in history the thread's live one again. `touch: false`
125
+ * restores it without counting as use, so its last-activity time stays put:
126
+ * restarts and the restore before a message do that, while going back to a
127
+ * conversation with /resume moves it on.
128
+ */
129
+ resumeSession(sessionKey, conversationId, { touch = true } = {}) {
110
130
  const historyEntry = sessionHistory.getSessionByConversationId(sessionKey, conversationId);
111
131
  if (!historyEntry) {
112
132
  return undefined;
@@ -121,20 +141,21 @@ class SessionManager {
121
141
  lastActivity: new Date(),
122
142
  };
123
143
  this.sessions.set(sessionKey, session);
124
- // Update history activity (with resolved path)
125
- sessionHistory.saveSession(sessionKey, conversationId, resolvedPath, historyEntry.lastMessagePreview, historyEntry.claudeSessionId);
144
+ // Moves it to the front of the history, with the resolved path.
145
+ sessionHistory.saveSession(sessionKey, conversationId, resolvedPath, historyEntry.lastMessagePreview, historyEntry.claudeSessionId, undefined, { touch });
126
146
  return session;
127
147
  }
148
+ /** Restore the thread's most recent conversation, without counting that as use. */
128
149
  resumeLastSession(sessionKey) {
129
150
  const lastEntry = sessionHistory.getLastSession(sessionKey);
130
151
  if (!lastEntry) {
131
152
  return undefined;
132
153
  }
133
- return this.resumeSession(sessionKey, lastEntry.conversationId);
154
+ return this.resumeSession(sessionKey, lastEntry.conversationId, { touch: false });
134
155
  }
135
156
  /** Return the in-memory session if present; otherwise transparently restore
136
157
  * the last session from disk if it's recent enough. Lets handlers recover
137
- * from unplanned restarts without forcing the user to type /continue. */
158
+ * from unplanned restarts without forcing the user to type /resume. */
138
159
  getOrRestoreSession(sessionKey, maxAgeMs = RESTORE_MAX_IDLE_MS) {
139
160
  const existing = this.sessions.get(sessionKey);
140
161
  if (existing)
@@ -167,7 +188,7 @@ class SessionManager {
167
188
  /**
168
189
  * Start a fresh conversation in the same project, preserving the prior
169
190
  * entry in session history so the user can return to it. Used by /clear,
170
- * which must actually sever the SDK session — the existing
191
+ * which must actually sever the Claude session — the existing
171
192
  * `claudeSessionId` would otherwise be re-used on the next message and the
172
193
  * Anthropic-side conversation history would persist server-side.
173
194
  */