telecoder 0.0.0-stage → 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 (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Out-of-band topic summarizer using Haiku.
3
+ *
4
+ * Fires alongside the main agent turn to derive a two-part topic phrase
5
+ * for the status line: a stable GENERAL part (the broader feature/area)
6
+ * and a CURRENT part (the specific task in this turn). The previous
7
+ * GENERAL is fed back into the prompt so Haiku can keep it sticky
8
+ * across consecutive messages and only change it when the user pivots.
9
+ *
10
+ * Runs isolated (see side-call-options.ts): no plugins, MCP servers, hooks,
11
+ * or the bot's own folder's memory and git status — making it immune to the SDK's
12
+ * tool-deferral mode that can degrade the existing model-driven
13
+ * auto-topic mechanism when many user-level tools are loaded.
14
+ *
15
+ * Auth piggybacks on the same Claude executable the main bot uses, so no
16
+ * extra API key, account, or subscription is required.
17
+ */
18
+ import { query } from '@anthropic-ai/claude-agent-sdk';
19
+ import { sideCallOptions } from './side-call-options.js';
20
+ const TOPIC_TIMEOUT_MS = 10_000;
21
+ const MAX_INPUT_CHARS = 1500;
22
+ // Display delimiter between GENERAL and CURRENT in the stored topic.
23
+ // The status line renders the topic as-is, so this also doubles as the
24
+ // rendered separator. Kept in sync with the prompt below.
25
+ export const TOPIC_PART_SEPARATOR = ' · ';
26
+ // Trivial replies that don't carry topical content. Skip the Haiku call so we
27
+ // don't overwrite a perfectly good prior topic with garbage like "ok".
28
+ const TRIVIAL_MESSAGE_RE = /^(ok|okay|yes|yeah|yep|yup|no|nope|nah|thanks|thx|ty|cool|sure|nice|great|sounds good|got it|alright|done|next|continue|go|stop|wait|hmm|huh|lol|haha|👍|👌|✅|🙏|❤️|🎉)[.!?]*$/i;
29
+ function buildInstructions(previousTopic, project) {
30
+ // The project is shown next to the topic (in a thread's name, the status
31
+ // line), so a GENERAL that only repeats it says nothing.
32
+ const projectLine = project
33
+ ? `The project is "${project}" and is already shown next to the topic. GENERAL must name the feature/area within it, never just the project name.\n\n`
34
+ : '';
35
+ const previousLine = previousTopic
36
+ ? `Previous topic was: "${previousTopic}"\n` +
37
+ '- Keep GENERAL the same unless the user has clearly pivoted to a different feature/area.\n' +
38
+ '- If the latest message is a meta-question, acknowledgment, or has no concrete task, keep the previous CURRENT too.\n\n'
39
+ : '';
40
+ return ('You are a topic summarizer. Output format is strict: "GENERAL | CURRENT".\n' +
41
+ '- GENERAL: the broader feature/area being worked on. Stable across messages. Concise.\n' +
42
+ '- CURRENT: the specific task in this latest message. Be as descriptive as needed.\n' +
43
+ 'Output ONLY the topic line. NO chat, NO acknowledgment, NO explanation, NO quotes, NO prefix.\n' +
44
+ 'The pipe character "|" MUST appear exactly once, separating the two parts.\n\n' +
45
+ 'Good output:\n' +
46
+ 'Dark mode | Fixing toggle animation glitch\n' +
47
+ 'Auth bug | Adding rate limit to login endpoint\n' +
48
+ 'PR review | Reading test coverage report\n\n' +
49
+ 'Bad output (do NOT do any of these):\n' +
50
+ '"Understood, I\'ll continue with..." (chat reply)\n' +
51
+ 'Dark mode (missing CURRENT)\n' +
52
+ 'Fixing the bug. (missing GENERAL and pipe)\n\n' +
53
+ projectLine +
54
+ previousLine +
55
+ 'User message:\n');
56
+ }
57
+ /**
58
+ * Summarize a user message into a two-part topic via Haiku.
59
+ * Returns the combined "general · current" string. Returns undefined if
60
+ * Haiku doesn't follow the format — caller keeps the prior topic in that
61
+ * case rather than overwriting it with garbage. Pass the full previous
62
+ * topic so Haiku can keep GENERAL stable and reuse CURRENT for
63
+ * meta/acknowledgment messages, and the project's folder name so GENERAL
64
+ * isn't just that.
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
+ }
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) {
84
+ const trimmed = userMessage.trim();
85
+ if (trimmed.length < 3)
86
+ return undefined;
87
+ if (TRIVIAL_MESSAGE_RE.test(trimmed))
88
+ return undefined;
89
+ const input = trimmed.length > MAX_INPUT_CHARS ? trimmed.slice(0, MAX_INPUT_CHARS) : trimmed;
90
+ const controller = new AbortController();
91
+ const timer = setTimeout(() => controller.abort(), TOPIC_TIMEOUT_MS);
92
+ try {
93
+ const response = query({
94
+ prompt: buildInstructions(previousTopic, project) + input,
95
+ options: sideCallOptions('You are a topic summarizer.', controller),
96
+ });
97
+ let collected = '';
98
+ for await (const message of response) {
99
+ if (message.type === 'assistant') {
100
+ for (const block of message.message.content) {
101
+ if (block.type === 'text')
102
+ collected += block.text;
103
+ }
104
+ }
105
+ if (message.type === 'result')
106
+ break;
107
+ }
108
+ return sanitizeTwoPartTopic(collected);
109
+ }
110
+ catch (err) {
111
+ if (controller.signal.aborted)
112
+ return undefined;
113
+ console.debug('[AutoTopic] Haiku side-call failed:', err instanceof Error ? err.message : err);
114
+ return undefined;
115
+ }
116
+ finally {
117
+ clearTimeout(timer);
118
+ }
119
+ }
120
+ function cleanPart(raw) {
121
+ const cleaned = raw
122
+ .trim()
123
+ .replace(/^["'`*_]+|["'`*_]+$/g, '')
124
+ .replace(/[.!?,:;]+$/g, '')
125
+ .trim();
126
+ return cleaned || undefined;
127
+ }
128
+ function sanitizeTwoPartTopic(raw) {
129
+ const firstLine = raw.trim().split(/\n/)[0]?.trim() ?? '';
130
+ if (!firstLine)
131
+ return undefined;
132
+ // Strict: require the pipe. If Haiku didn't follow the format we'd rather
133
+ // skip this turn (keeping the prior topic) than render conversational prose.
134
+ const pipeIdx = firstLine.indexOf('|');
135
+ if (pipeIdx < 0)
136
+ return undefined;
137
+ const general = cleanPart(firstLine.slice(0, pipeIdx));
138
+ const current = cleanPart(firstLine.slice(pipeIdx + 1));
139
+ if (!general || !current)
140
+ return undefined;
141
+ return `${general}${TOPIC_PART_SEPARATOR}${current}`;
142
+ }
143
+ //# sourceMappingURL=auto-topic-haiku.js.map
@@ -0,0 +1,156 @@
1
+ /**
2
+ * What slash commands and skills a working directory actually offers.
3
+ *
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.
12
+ */
13
+ import { spawn } from 'child_process';
14
+ import { sanitizeError } from '../utils/sanitize.js';
15
+ import { loadsUserSetup, userSetupIsolationArgs } from './pty-spawn-config.js';
16
+ /**
17
+ * Cached per (binary, working directory) rather than per session: the answer
18
+ * depends on the project's `.claude/`, its plugins and the CLI build, none of
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.
23
+ */
24
+ const cache = new Map();
25
+ function cacheKey(executable, 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
+ }
31
+ /** Re-probe rather than serve a snapshot older than this. */
32
+ const STALE_AFTER_MS = 30 * 60 * 1000;
33
+ /** How long to wait for the probe's init line before giving up. */
34
+ const PROBE_TIMEOUT_MS = 20_000;
35
+ /** In-flight probes, so N concurrent /projectcommands spawn one process. */
36
+ const inFlight = new Map();
37
+ /** Record what a probe's init message reported for `workingDirectory`. */
38
+ export function recordAvailableCommands(workingDirectory, executable, slashCommands, skills) {
39
+ if (!workingDirectory || !Array.isArray(slashCommands))
40
+ return;
41
+ cache.set(cacheKey(executable, workingDirectory), {
42
+ slashCommands: [...slashCommands],
43
+ skills: Array.isArray(skills) ? [...skills] : [],
44
+ recordedAtMs: Date.now(),
45
+ });
46
+ }
47
+ /** Cached snapshot for `workingDirectory` under `executable`, if recent. */
48
+ export function getCachedAvailableCommands(workingDirectory, executable) {
49
+ const hit = cache.get(cacheKey(executable, workingDirectory));
50
+ if (!hit)
51
+ return undefined;
52
+ return Date.now() - hit.recordedAtMs > STALE_AFTER_MS ? undefined : hit;
53
+ }
54
+ /**
55
+ * The cached snapshot, probing for one if the cache is cold or stale.
56
+ * Resolves to undefined when the probe fails — callers fall back to whatever
57
+ * they can list without it.
58
+ */
59
+ export async function getAvailableCommands(workingDirectory, executable) {
60
+ const cached = getCachedAvailableCommands(workingDirectory, executable);
61
+ if (cached)
62
+ return cached;
63
+ const key = cacheKey(executable, workingDirectory);
64
+ const existing = inFlight.get(key);
65
+ if (existing)
66
+ return existing;
67
+ const probe = probeAvailableCommands(workingDirectory, executable)
68
+ .finally(() => inFlight.delete(key));
69
+ inFlight.set(key, probe);
70
+ return probe;
71
+ }
72
+ /**
73
+ * Spawn a headless CLI, read the init message, kill it. Costs nothing: the
74
+ * prompt is a locally-handled slash command, and we send SIGTERM as soon as
75
+ * the first line parses.
76
+ */
77
+ async function probeAvailableCommands(workingDirectory, executable) {
78
+ return new Promise((resolve) => {
79
+ let settled = false;
80
+ let buffer = '';
81
+ const finish = (result) => {
82
+ if (settled)
83
+ return;
84
+ settled = true;
85
+ clearTimeout(timer);
86
+ try {
87
+ child.kill('SIGTERM');
88
+ }
89
+ catch { /* already gone */ }
90
+ resolve(result);
91
+ };
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'] });
96
+ const timer = setTimeout(() => {
97
+ console.warn(`[AvailableCommands] probe timed out after ${PROBE_TIMEOUT_MS}ms`);
98
+ finish(undefined);
99
+ }, PROBE_TIMEOUT_MS);
100
+ child.stdout.on('data', (chunk) => {
101
+ buffer += chunk.toString('utf-8');
102
+ let newline = buffer.indexOf('\n');
103
+ while (newline !== -1) {
104
+ const line = buffer.slice(0, newline).trim();
105
+ buffer = buffer.slice(newline + 1);
106
+ newline = buffer.indexOf('\n');
107
+ if (!line)
108
+ continue;
109
+ let msg;
110
+ try {
111
+ msg = JSON.parse(line);
112
+ }
113
+ catch {
114
+ continue; // not our line — the CLI can print other things first
115
+ }
116
+ if (msg.subtype !== 'init')
117
+ continue;
118
+ recordAvailableCommands(workingDirectory, executable, msg.slash_commands, msg.skills);
119
+ finish(getCachedAvailableCommands(workingDirectory, executable));
120
+ return;
121
+ }
122
+ });
123
+ child.on('error', (err) => {
124
+ console.warn(`[AvailableCommands] probe failed to spawn: ${sanitizeError(err)}`);
125
+ finish(undefined);
126
+ });
127
+ child.on('close', () => finish(undefined));
128
+ });
129
+ }
130
+ /**
131
+ * Split a snapshot into the groups worth showing separately.
132
+ *
133
+ * `slash_commands` is a flat list; `skills` marks which of them are skills,
134
+ * and a `plugin:command` name marks a plugin's. Whatever is left is a CLI
135
+ * built-in (`clear`, `compact`, `model`, …).
136
+ */
137
+ export function groupAvailableCommands(snapshot) {
138
+ const skillSet = new Set(snapshot.skills);
139
+ const skills = [];
140
+ const plugins = [];
141
+ const builtIns = [];
142
+ for (const name of snapshot.slashCommands) {
143
+ if (name.includes(':'))
144
+ plugins.push(name);
145
+ else if (skillSet.has(name))
146
+ skills.push(name);
147
+ else
148
+ builtIns.push(name);
149
+ }
150
+ return {
151
+ skills: skills.sort(),
152
+ plugins: plugins.sort(),
153
+ builtIns: builtIns.sort(),
154
+ };
155
+ }
156
+ //# sourceMappingURL=available-commands.js.map
@@ -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