telecoder 0.0.0-stage → 1.2.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 (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -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 +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * Debug utility for testing long-running agent queries with watchdog.
4
+ *
5
+ * Usage:
6
+ * # Basic test with default project
7
+ * CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts
8
+ *
9
+ * # Test with specific project directory
10
+ * CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts /path/to/project
11
+ *
12
+ * # Test with shorter warning threshold
13
+ * AGENT_WATCHDOG_WARN_SECONDS=10 CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts
14
+ *
15
+ * # Test with hard timeout
16
+ * AGENT_QUERY_TIMEOUT_MS=60000 CLAUDE_SDK_LOG_LEVEL=basic npx tsx src/utils/debug-agent.ts
17
+ */
18
+ import { query } from '@anthropic-ai/claude-agent-sdk';
19
+ import { config } from '../config.js';
20
+ import { AgentWatchdog } from '../claude/agent-watchdog.js';
21
+ import { createAgentTimer, recordMessage, formatDuration, getElapsedMs, getTimingReport, } from './agent-timer.js';
22
+ const TEST_PROMPTS = {
23
+ quick: 'What is 2 + 2?',
24
+ medium: 'List the files in the current directory and describe what this project does.',
25
+ long: 'Explore this codebase thoroughly. Find all TypeScript files, identify the main entry points, and explain the architecture. Use the Task tool with subagents if needed to parallelize your exploration.',
26
+ subagent: 'Use the Task tool to spawn an explore agent that finds all configuration files in this project.',
27
+ };
28
+ async function main() {
29
+ const projectDir = process.argv[2] || process.cwd();
30
+ const promptKey = process.argv[3] || 'medium';
31
+ const prompt = TEST_PROMPTS[promptKey] || TEST_PROMPTS.medium;
32
+ console.log('=== Debug Agent Test ===');
33
+ console.log(`Project: ${projectDir}`);
34
+ console.log(`Prompt: ${promptKey} — "${prompt.substring(0, 80)}..."`);
35
+ console.log(`Watchdog enabled: ${config.AGENT_WATCHDOG_ENABLED}`);
36
+ console.log(`Watchdog warn after: ${config.AGENT_WATCHDOG_WARN_SECONDS}s`);
37
+ console.log(`Watchdog log interval: ${config.AGENT_WATCHDOG_LOG_SECONDS}s`);
38
+ console.log(`Query timeout: ${config.AGENT_QUERY_TIMEOUT_MS}ms (0 = disabled)`);
39
+ console.log('========================\n');
40
+ const timer = createAgentTimer();
41
+ const controller = new AbortController();
42
+ // Initialize watchdog
43
+ const watchdog = config.AGENT_WATCHDOG_ENABLED
44
+ ? new AgentWatchdog({
45
+ chatId: '0', // Debug session
46
+ warnAfterSeconds: config.AGENT_WATCHDOG_WARN_SECONDS,
47
+ logIntervalSeconds: config.AGENT_WATCHDOG_LOG_SECONDS,
48
+ timeoutMs: config.AGENT_QUERY_TIMEOUT_MS > 0 ? config.AGENT_QUERY_TIMEOUT_MS : undefined,
49
+ onWarning: (sinceMsg, total) => {
50
+ console.log(`[DEBUG] WATCHDOG WARNING: No messages for ${formatDuration(sinceMsg)} (total: ${formatDuration(total)})`);
51
+ },
52
+ onTimeout: () => {
53
+ console.log('[DEBUG] WATCHDOG TIMEOUT: Aborting query');
54
+ controller.abort();
55
+ },
56
+ })
57
+ : null;
58
+ watchdog?.start();
59
+ try {
60
+ const response = query({
61
+ prompt,
62
+ options: {
63
+ cwd: projectDir,
64
+ tools: ['Bash', 'Read', 'Glob', 'Grep', 'Task'],
65
+ allowedTools: ['Bash', 'Read', 'Glob', 'Grep', 'Task'],
66
+ permissionMode: 'acceptEdits',
67
+ abortController: controller,
68
+ model: 'opus',
69
+ },
70
+ });
71
+ let messageCount = 0;
72
+ for await (const message of response) {
73
+ recordMessage(timer);
74
+ watchdog?.recordActivity(message.type);
75
+ messageCount++;
76
+ const elapsed = formatDuration(getElapsedMs(timer));
77
+ if (message.type === 'assistant') {
78
+ for (const block of message.message.content) {
79
+ if (block.type === 'text') {
80
+ console.log(`[${elapsed}] TEXT: ${block.text.substring(0, 200)}...`);
81
+ }
82
+ else if (block.type === 'tool_use') {
83
+ const toolInput = 'input' in block ? block.input : {};
84
+ console.log(`[${elapsed}] TOOL: ${block.name}`);
85
+ if (block.name === 'Task') {
86
+ console.log(` └─ SUBAGENT: ${toolInput.subagent_type || 'unknown'} — ${String(toolInput.description || toolInput.prompt || '').substring(0, 80)}`);
87
+ }
88
+ }
89
+ }
90
+ }
91
+ else if (message.type === 'result') {
92
+ console.log(`\n[${elapsed}] RESULT: ${message.subtype}`);
93
+ if (message.subtype === 'success') {
94
+ console.log(` └─ ${message.result?.substring(0, 200)}...`);
95
+ }
96
+ }
97
+ else if (message.type === 'tool_use_summary') {
98
+ console.log(`[${elapsed}] TOOL_SUMMARY`);
99
+ }
100
+ else if (message.type === 'system') {
101
+ console.log(`[${elapsed}] SYSTEM: ${message.subtype}`);
102
+ }
103
+ }
104
+ console.log(`\n=== Query Complete ===`);
105
+ console.log(`${getTimingReport(timer)}`);
106
+ console.log(`Raw messages: ${messageCount}`);
107
+ }
108
+ catch (error) {
109
+ console.error('\n=== Query Error ===');
110
+ console.error(error instanceof Error ? error.message : error);
111
+ }
112
+ finally {
113
+ watchdog?.stop();
114
+ }
115
+ }
116
+ main().catch(console.error);
117
+ //# sourceMappingURL=debug-agent.js.map
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * Reproduction harness for watchdog-vs-Monitor / backgrounded-task hangs.
4
+ *
5
+ * Goal: prove or disprove whether the AgentWatchdog fires `controller.abort()`
6
+ * during a quiet period after a backgrounded tool call, which the SDK then
7
+ * reports as "Request interrupted by user for tool use".
8
+ *
9
+ * Usage:
10
+ * npx tsx src/utils/debug-watchdog.ts # default 20s timeouts, Monitor prompt
11
+ * SILENCE_MS=10000 npx tsx src/utils/debug-watchdog.ts
12
+ * PROMPT=bgsleep npx tsx src/utils/debug-watchdog.ts # background bash + idle wait
13
+ */
14
+ import { query } from '@anthropic-ai/claude-agent-sdk';
15
+ import { AgentWatchdog } from '../claude/agent-watchdog.js';
16
+ import { formatDuration } from './agent-timer.js';
17
+ import { resolveBundledClaudeBin } from './resolve-claude-bin.js';
18
+ const SILENCE_MS = parseInt(process.env.SILENCE_MS || '20000', 10);
19
+ const STALE_MS = parseInt(process.env.STALE_MS || '20000', 10);
20
+ const PROMPT_KEY = process.env.PROMPT || 'monitor';
21
+ const PROMPTS = {
22
+ // Try to force a Monitor call after a backgrounded bash.
23
+ monitor: `Run \`sleep 45\` as a background bash command with run_in_background:true. Then use the Monitor tool to wait until that background task completes. Do NOT call BashOutput or any other tool while waiting — only Monitor. Once the sleep finishes, briefly report the result.`,
24
+ // Plain backgrounded bash with no follow-up tool calls.
25
+ bgsleep: `Run \`sleep 45\` as a background bash command with run_in_background:true. Then sit idle until it finishes — do not call any tools or write any text until you see the task complete. Then say "done".`,
26
+ };
27
+ const prompt = PROMPTS[PROMPT_KEY] || PROMPTS.monitor;
28
+ console.log('=== Watchdog Repro Harness ===');
29
+ console.log(`Silence timeout : ${SILENCE_MS}ms`);
30
+ console.log(`Stale timeout : ${STALE_MS}ms`);
31
+ console.log(`Prompt : ${PROMPT_KEY}`);
32
+ console.log(`Prompt text : ${prompt.substring(0, 100)}...`);
33
+ console.log('==============================\n');
34
+ const start = Date.now();
35
+ const elapsed = () => formatDuration(Date.now() - start);
36
+ const controller = new AbortController();
37
+ let watchdogFired = null;
38
+ const watchdog = new AgentWatchdog({
39
+ chatId: 'repro',
40
+ warnAfterSeconds: 5,
41
+ logIntervalSeconds: 2,
42
+ silenceTimeoutMs: SILENCE_MS,
43
+ staleToolTimeoutMs: STALE_MS,
44
+ onWarning: (sinceMsg, total) => {
45
+ console.log(`[${elapsed()}] !! WATCHDOG WARNING: ${formatDuration(sinceMsg)} since last meaningful msg (total ${formatDuration(total)})`);
46
+ },
47
+ onSilenceTimeout: () => {
48
+ watchdogFired = 'silence';
49
+ console.log(`[${elapsed()}] !! WATCHDOG SILENCE TIMEOUT — aborting`);
50
+ controller.abort();
51
+ },
52
+ onStaleToolTimeout: () => {
53
+ watchdogFired = 'stale-tool';
54
+ console.log(`[${elapsed()}] !! WATCHDOG STALE-TOOL TIMEOUT — aborting`);
55
+ controller.abort();
56
+ },
57
+ });
58
+ watchdog.start();
59
+ const messageTypeCounts = {};
60
+ let lastLoggedMs = 0;
61
+ try {
62
+ const bundled = resolveBundledClaudeBin();
63
+ const response = query({
64
+ prompt,
65
+ options: {
66
+ cwd: process.cwd(),
67
+ permissionMode: 'bypassPermissions',
68
+ allowDangerouslySkipPermissions: true,
69
+ settingSources: ['project'],
70
+ abortController: controller,
71
+ model: 'claude-opus-4-8',
72
+ ...(bundled ? { pathToClaudeCodeExecutable: bundled } : {}),
73
+ },
74
+ });
75
+ for await (const message of response) {
76
+ watchdog.recordActivity(message.type);
77
+ messageTypeCounts[message.type] = (messageTypeCounts[message.type] || 0) + 1;
78
+ const now = Date.now();
79
+ if (now - lastLoggedMs >= 500 || message.type === 'assistant' || message.type === 'result') {
80
+ const typeLabel = 'subtype' in message ? `${message.type}/${message.subtype}` : message.type;
81
+ console.log(`[${elapsed()}] msg: ${typeLabel}`);
82
+ lastLoggedMs = now;
83
+ }
84
+ if (controller.signal.aborted) {
85
+ console.log(`[${elapsed()}] aborted, breaking loop`);
86
+ break;
87
+ }
88
+ if (message.type === 'assistant') {
89
+ for (const block of message.message.content) {
90
+ if (block.type === 'tool_use') {
91
+ console.log(`[${elapsed()}] → tool: ${block.name}`);
92
+ }
93
+ else if (block.type === 'text') {
94
+ console.log(`[${elapsed()}] → text: ${block.text.substring(0, 120).replace(/\n/g, ' ')}`);
95
+ }
96
+ }
97
+ }
98
+ if (message.type === 'result') {
99
+ console.log(`[${elapsed()}] result subtype: ${message.subtype}`);
100
+ // Match production behaviour (agent.ts:942) — stop watchdog on result.
101
+ // Without this, the harness's watchdog keeps running and fires falsely
102
+ // during the post-result silence while backgrounded tasks are armed.
103
+ console.log(`[${elapsed()}] (stopping watchdog — production-faithful)`);
104
+ watchdog.stop();
105
+ }
106
+ }
107
+ }
108
+ catch (err) {
109
+ console.error(`[${elapsed()}] ERROR:`, err instanceof Error ? err.message : err);
110
+ }
111
+ finally {
112
+ watchdog.stop();
113
+ }
114
+ console.log('\n=== Summary ===');
115
+ console.log(`Total elapsed : ${elapsed()}`);
116
+ console.log(`Watchdog fired : ${watchdogFired ?? 'no'}`);
117
+ console.log(`Message types :`);
118
+ for (const [t, n] of Object.entries(messageTypeCounts)) {
119
+ console.log(` ${t}: ${n}`);
120
+ }
121
+ //# sourceMappingURL=debug-watchdog.js.map
@@ -0,0 +1,111 @@
1
+ import * as fs from 'fs';
2
+ import { Readable } from 'stream';
3
+ import { pipeline } from 'stream/promises';
4
+ import { redactSecrets } from './sanitize.js';
5
+ /** Attempts per download: one try plus three retries, as curl's `--retry 3` did. */
6
+ const MAX_ATTEMPTS = 4;
7
+ /** Pause between attempts. */
8
+ const RETRY_DELAY_MS = 2_000;
9
+ /** Ceiling on a single attempt, connect through last byte. */
10
+ const ATTEMPT_TIMEOUT_MS = 30_000;
11
+ /** Ceiling on the whole download, retries included. */
12
+ const TOTAL_TIMEOUT_MS = 60_000;
13
+ /**
14
+ * Is this URL safe to download from?
15
+ *
16
+ * Only http(s), and nothing that could smuggle a second line into a request or
17
+ * a log: no CR, LF or NUL. Telegram file URLs are https; plain http is kept
18
+ * for a local Bot API server, which listens on localhost.
19
+ */
20
+ export function isValidDownloadUrl(url) {
21
+ if (typeof url !== 'string' || /[\r\n\0]/.test(url))
22
+ return false;
23
+ let parsed;
24
+ try {
25
+ parsed = new URL(url);
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ return parsed.protocol === 'https:' || parsed.protocol === 'http:';
31
+ }
32
+ /** An HTTP status worth retrying: server trouble, rate limits, timeouts. */
33
+ function isRetryableStatus(status) {
34
+ return status >= 500 || status === 429 || status === 408;
35
+ }
36
+ class DownloadError extends Error {
37
+ retryable;
38
+ constructor(message, retryable) {
39
+ super(message);
40
+ this.retryable = retryable;
41
+ }
42
+ }
43
+ function sleep(ms) {
44
+ return new Promise((resolve) => setTimeout(resolve, ms));
45
+ }
46
+ async function attemptDownload(fileUrl, destPath, signal) {
47
+ let res;
48
+ try {
49
+ res = await fetch(fileUrl, { signal, redirect: 'follow' });
50
+ }
51
+ catch (error) {
52
+ // Network failure or timeout. The message from undici never carries the
53
+ // URL, but redact anyway: this is the one place the token is in play.
54
+ const msg = error instanceof Error ? (error.cause instanceof Error ? error.cause.message : error.message) : String(error);
55
+ throw new DownloadError(redactSecrets(msg), true);
56
+ }
57
+ if (!res.ok || !res.body) {
58
+ // Drain so the connection can be reused; ignore failures doing so.
59
+ await res.body?.cancel().catch(() => { });
60
+ throw new DownloadError(`HTTP ${res.status}`, isRetryableStatus(res.status));
61
+ }
62
+ try {
63
+ await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(destPath));
64
+ }
65
+ catch (error) {
66
+ fs.rmSync(destPath, { force: true });
67
+ const msg = error instanceof Error ? error.message : String(error);
68
+ throw new DownloadError(redactSecrets(msg), true);
69
+ }
70
+ }
71
+ /**
72
+ * Download a file from a URL to `destPath`.
73
+ *
74
+ * Uses Node's own fetch, so the URL — which for Telegram files embeds the bot
75
+ * token — never appears in a process argument list (`ps`) or in an error
76
+ * message. Retries transient failures up to three times, two seconds apart,
77
+ * within an overall one-minute budget; a 4xx other than 408/429 fails at once.
78
+ */
79
+ export async function downloadFileSecure(fileUrl, destPath) {
80
+ if (!isValidDownloadUrl(fileUrl)) {
81
+ throw new Error('Invalid URL for download');
82
+ }
83
+ const deadline = Date.now() + TOTAL_TIMEOUT_MS;
84
+ let lastError;
85
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
86
+ const remaining = deadline - Date.now();
87
+ if (remaining <= 0)
88
+ break;
89
+ try {
90
+ await attemptDownload(fileUrl, destPath, AbortSignal.timeout(Math.min(ATTEMPT_TIMEOUT_MS, remaining)));
91
+ return;
92
+ }
93
+ catch (error) {
94
+ lastError = error instanceof DownloadError ? error : new DownloadError(redactSecrets(String(error)), false);
95
+ if (!lastError.retryable || attempt === MAX_ATTEMPTS)
96
+ break;
97
+ if (deadline - Date.now() <= RETRY_DELAY_MS)
98
+ break;
99
+ await sleep(RETRY_DELAY_MS);
100
+ }
101
+ }
102
+ throw new Error(`Failed to download file: ${lastError?.message ?? 'timed out'}`);
103
+ }
104
+ /**
105
+ * Build a Telegram file download URL from the bot token and file path.
106
+ * The result contains the token: pass it to downloadFileSecure, never log it.
107
+ */
108
+ export function getTelegramFileUrl(botToken, filePath) {
109
+ return `https://api.telegram.org/file/bot${botToken}/${filePath}`;
110
+ }
111
+ //# sourceMappingURL=download.js.map
@@ -0,0 +1,48 @@
1
+ import { isMainThread } from 'worker_threads';
2
+ /**
3
+ * The exit code a launcher worker uses when its configuration stops it — a
4
+ * missing setting, or a token Telegram rejected. 78 is EX_CONFIG from
5
+ * sysexits.h.
6
+ *
7
+ * The launcher reads it as "restarting won't help": it stops the bot with the
8
+ * message the bot printed, instead of respawning it into the same error four
9
+ * times. A bot run on its own exits 1, which is what process managers and
10
+ * shells expect from a failed start — unless a unit from `telecoder service
11
+ * install` runs it, see configErrorExitCode().
12
+ */
13
+ export const EXIT_CONFIG = 78;
14
+ /**
15
+ * Set in the environment by the units `telecoder service install` writes, so
16
+ * the bot knows which service manager answers its exit code.
17
+ */
18
+ export const SERVICE_MANAGER_ENV = 'TELECODER_SERVICE';
19
+ export function getServiceManager(env = process.env) {
20
+ const value = env[SERVICE_MANAGER_ENV];
21
+ return value === 'systemd' || value === 'launchd' ? value : null;
22
+ }
23
+ /**
24
+ * The code to exit with on a configuration problem — whichever code makes the
25
+ * thing that started us stand down instead of starting us into the same error
26
+ * again.
27
+ *
28
+ * - A launcher worker: 78, which the launcher reads as "don't respawn".
29
+ * - Under our systemd unit: 78, named in its RestartPreventExitStatus=.
30
+ * - Under our launchd agent: 0. KeepAlive can only tell zero from non-zero
31
+ * (SuccessfulExit), not one code from another, so a clean exit is the only
32
+ * way to keep launchd from restarting a bot that can't start.
33
+ * - Anything else (a terminal, pm2): 1, as for any failed start.
34
+ */
35
+ export function configErrorExitCode(mainThread = isMainThread, manager = getServiceManager()) {
36
+ if (!mainThread)
37
+ return EXIT_CONFIG;
38
+ if (manager === 'systemd')
39
+ return EXIT_CONFIG;
40
+ if (manager === 'launchd')
41
+ return 0;
42
+ return 1;
43
+ }
44
+ /** Exit for a configuration problem, with the code that fits how we were started. */
45
+ export function exitForConfigError() {
46
+ process.exit(configErrorExitCode());
47
+ }
48
+ //# sourceMappingURL=exit-codes.js.map
@@ -0,0 +1,149 @@
1
+ import * as fs from 'fs';
2
+ /**
3
+ * Common image file magic bytes (signatures)
4
+ */
5
+ const IMAGE_SIGNATURES = [
6
+ // JPEG
7
+ { bytes: [0xFF, 0xD8, 0xFF], extension: '.jpg', mimeType: 'image/jpeg' },
8
+ // PNG
9
+ { bytes: [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], extension: '.png', mimeType: 'image/png' },
10
+ // GIF87a
11
+ { bytes: [0x47, 0x49, 0x46, 0x38, 0x37, 0x61], extension: '.gif', mimeType: 'image/gif' },
12
+ // GIF89a
13
+ { bytes: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61], extension: '.gif', mimeType: 'image/gif' },
14
+ // NOTE: BMP is handled by dedicated isBMP() check, not in this array.
15
+ // TIFF (little endian)
16
+ { bytes: [0x49, 0x49, 0x2A, 0x00], extension: '.tiff', mimeType: 'image/tiff' },
17
+ // TIFF (big endian)
18
+ { bytes: [0x4D, 0x4D, 0x00, 0x2A], extension: '.tiff', mimeType: 'image/tiff' },
19
+ // NOTE: WebP is handled by dedicated isWebP() check, not in this array.
20
+ // NOTE: HEIC/HEIF removed — the old [0x00,0x00,0x00] signature was a false-positive
21
+ // magnet (matches any file starting with null bytes). Proper HEIC detection requires
22
+ // checking for "ftyp" at offset 4 and brand codes at offset 8.
23
+ ];
24
+ /**
25
+ * Check if a buffer starts with the given signature bytes.
26
+ */
27
+ function matchesSignature(buffer, signature) {
28
+ if (buffer.length < signature.length)
29
+ return false;
30
+ for (let i = 0; i < signature.length; i++) {
31
+ if (buffer[i] !== signature[i])
32
+ return false;
33
+ }
34
+ return true;
35
+ }
36
+ /**
37
+ * Special check for WebP which has RIFF header followed by WEBP at bytes 8-11.
38
+ */
39
+ function isWebP(buffer) {
40
+ if (buffer.length < 12)
41
+ return false;
42
+ // Check RIFF header
43
+ if (!matchesSignature(buffer, [0x52, 0x49, 0x46, 0x46]))
44
+ return false;
45
+ // Check WEBP signature at offset 8
46
+ return buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50;
47
+ }
48
+ /**
49
+ * Detect HEIF container brand from ISO BMFF ftyp box.
50
+ * Returns 'heic' for HEVC-based brands, 'heif' for generic HEIF brands, or null.
51
+ */
52
+ function getHeifBrand(buffer) {
53
+ if (buffer.length < 12)
54
+ return null;
55
+ if (buffer[4] !== 0x66 || buffer[5] !== 0x74 || buffer[6] !== 0x79 || buffer[7] !== 0x70)
56
+ return null;
57
+ const brand = buffer.slice(8, 12).toString('ascii');
58
+ if (['heic', 'heix', 'hevc', 'hevx'].includes(brand))
59
+ return 'heic';
60
+ if (['mif1', 'msf1', 'heif'].includes(brand))
61
+ return 'heif';
62
+ return null;
63
+ }
64
+ /**
65
+ * Additional BMP validation: reserved bytes at offset 6-9 should be zero.
66
+ */
67
+ function isBMP(buffer) {
68
+ if (buffer.length < 10)
69
+ return false;
70
+ if (buffer[0] !== 0x42 || buffer[1] !== 0x4D)
71
+ return false;
72
+ // Reserved fields at bytes 6-9 must be zero in valid BMP files
73
+ return buffer[6] === 0 && buffer[7] === 0 && buffer[8] === 0 && buffer[9] === 0;
74
+ }
75
+ /**
76
+ * Detect file type from magic bytes.
77
+ * Returns null if the file type is not recognized as an image.
78
+ */
79
+ export function detectImageType(buffer) {
80
+ // Check WebP first (special case — shares RIFF header with WAV/AVI)
81
+ if (isWebP(buffer)) {
82
+ return { extension: '.webp', mimeType: 'image/webp' };
83
+ }
84
+ // Check HEIC/HEIF (proper ftyp box validation)
85
+ const heifBrand = getHeifBrand(buffer);
86
+ if (heifBrand === 'heic') {
87
+ return { extension: '.heic', mimeType: 'image/heic' };
88
+ }
89
+ if (heifBrand === 'heif') {
90
+ return { extension: '.heif', mimeType: 'image/heif' };
91
+ }
92
+ // Check BMP with reserved-byte validation (avoids 2-byte false positives)
93
+ if (isBMP(buffer)) {
94
+ return { extension: '.bmp', mimeType: 'image/bmp' };
95
+ }
96
+ // Check other signatures
97
+ for (const sig of IMAGE_SIGNATURES) {
98
+ if (sig.extension === '.bmp')
99
+ continue; // Already checked above
100
+ if (matchesSignature(buffer, sig.bytes)) {
101
+ return { extension: sig.extension, mimeType: sig.mimeType };
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+ function readHeaderBytes(filePath, length = 16) {
107
+ const fd = fs.openSync(filePath, 'r');
108
+ try {
109
+ const buffer = Buffer.alloc(length);
110
+ const bytesRead = fs.readSync(fd, buffer, 0, length, 0);
111
+ return { buffer: buffer.subarray(0, bytesRead), bytesRead };
112
+ }
113
+ finally {
114
+ fs.closeSync(fd);
115
+ }
116
+ }
117
+ /**
118
+ * Validate that a file is actually an image by checking magic bytes.
119
+ * @param filePath Path to the file to validate
120
+ * @returns true if the file is a valid image, false otherwise
121
+ */
122
+ export function isValidImageFile(filePath) {
123
+ try {
124
+ const { buffer, bytesRead } = readHeaderBytes(filePath);
125
+ if (bytesRead < 2)
126
+ return false;
127
+ return detectImageType(buffer) !== null;
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }
133
+ /**
134
+ * Get the actual file type from magic bytes.
135
+ * @param filePath Path to the file
136
+ * @returns FileTypeResult or null if not recognized
137
+ */
138
+ export function getFileType(filePath) {
139
+ try {
140
+ const { buffer, bytesRead } = readHeaderBytes(filePath);
141
+ if (bytesRead < 2)
142
+ return null;
143
+ return detectImageType(buffer);
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ }
149
+ //# sourceMappingURL=file-type.js.map
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Pure display formatters for user-facing numbers and times.
3
+ *
4
+ * These live in `utils/` rather than next to their first caller because both
5
+ * the bot handler layer and the provider layer need them, and the providers
6
+ * cannot import from the handlers — the handlers import the providers back.
7
+ * `pty-provider.ts` used to keep its own copy of `fmtTokens` for exactly that
8
+ * reason; a leaf module with no imports of its own removes the cycle instead
9
+ * of working around it.
10
+ */
11
+ /** Compact token count for user-facing messages: `999`, `12.5k`, `1.2M`. */
12
+ export function fmtTokens(n) {
13
+ if (n >= 1_000_000)
14
+ return (n / 1_000_000).toFixed(1) + 'M';
15
+ if (n >= 1_000)
16
+ return (n / 1_000).toFixed(1) + 'k';
17
+ return String(n);
18
+ }
19
+ /**
20
+ * Ten-cell usage bar, colour-coded green / amber / red at 60% and 80%. Pass
21
+ * `color` to colour it by something other than the fill, as the context bar
22
+ * does with `contextHealthColor`.
23
+ */
24
+ export function getProgressBar(pct, color) {
25
+ const clamped = Math.max(0, Math.min(100, pct));
26
+ const filled = Math.round(clamped / 10);
27
+ const empty = 10 - filled;
28
+ const shade = color ?? (clamped >= 80 ? '🔴' : clamped >= 60 ? '🟡' : '🟢');
29
+ return shade + ' [' + '█'.repeat(filled) + '░'.repeat(empty) + ']';
30
+ }
31
+ /** Context size from which answers get slower, costlier and less sharp. */
32
+ export const CONTEXT_WARN_TOKENS = 150_000;
33
+ /** Context size from which it's time to /clear, fork or /compact. */
34
+ export const CONTEXT_HIGH_TOKENS = 300_000;
35
+ /**
36
+ * How healthy a context of `used` tokens is, as 🟢 / 🟡 / 🔴.
37
+ *
38
+ * The share of the window alone doesn't say it: with the 1M window a context
39
+ * at 30% is already 300k tokens, where every turn costs more and recall gets
40
+ * patchier, long before auto-compact would step in. So whichever comes first
41
+ * counts — the absolute size, or 60% / 80% of the window.
42
+ */
43
+ export function contextHealthColor(used, contextWindow) {
44
+ const pct = contextWindow > 0 ? (used / contextWindow) * 100 : 0;
45
+ if (used >= CONTEXT_HIGH_TOKENS || pct >= 80)
46
+ return '🔴';
47
+ if (used >= CONTEXT_WARN_TOKENS || pct >= 60)
48
+ return '🟡';
49
+ return '🟢';
50
+ }
51
+ /**
52
+ * One-line manual `/compact` confirmation with the token reduction.
53
+ *
54
+ * Shared by both providers: the PTY provider reads the numbers back out of the
55
+ * session JSONL, the SDK provider gets them on the `compact_boundary` message.
56
+ * Same command, same wording, whichever transport ran it.
57
+ */
58
+ export function formatCompactionConfirmation(c) {
59
+ const before = fmtTokens(c.preTokens);
60
+ // postTokens is absent on older Claude Code builds — omit the arrow then.
61
+ return c.postTokens && c.postTokens > 0
62
+ ? `🗜️ Context compacted — ${before} → ${fmtTokens(c.postTokens)} tokens.`
63
+ : `🗜️ Context compacted — was ${before} tokens.`;
64
+ }
65
+ export function formatTimeAgo(date) {
66
+ const now = new Date();
67
+ const diffMs = now.getTime() - date.getTime();
68
+ const diffMins = Math.floor(diffMs / 60000);
69
+ const diffHours = Math.floor(diffMs / 3600000);
70
+ const diffDays = Math.floor(diffMs / 86400000);
71
+ if (diffMins < 1)
72
+ return 'just now';
73
+ if (diffMins < 60)
74
+ return `${diffMins}m ago`;
75
+ if (diffHours < 24)
76
+ return `${diffHours}h ago`;
77
+ if (diffDays < 7)
78
+ return `${diffDays}d ago`;
79
+ return date.toLocaleDateString();
80
+ }
81
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The project a bot is for (HOME_PROJECT), set per bot in instances.json by
3
+ * /newbot. A bot made for one project names itself after it, so it neither
4
+ * needs a /project before the first message nor the project in front of
5
+ * every thread's name.
6
+ */
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+ import { config } from '../config.js';
10
+ import { getWorkspaceRoot } from './workspace-guard.js';
11
+ let warned = false;
12
+ /** The bot's home project as an absolute path, or undefined when it has none or it's gone. */
13
+ export function homeProject() {
14
+ if (!config.HOME_PROJECT)
15
+ return undefined;
16
+ const dir = path.resolve(getWorkspaceRoot(), config.HOME_PROJECT);
17
+ if (fs.existsSync(dir) && fs.statSync(dir).isDirectory())
18
+ return dir;
19
+ if (!warned) {
20
+ warned = true;
21
+ console.warn(`[HomeProject] HOME_PROJECT ${dir} is not a directory; ignoring it`);
22
+ }
23
+ return undefined;
24
+ }
25
+ /** Whether `dir` is the bot's home project. */
26
+ export function isHomeProject(dir) {
27
+ const home = homeProject();
28
+ return home !== undefined && dir !== undefined && path.resolve(dir) === home;
29
+ }
30
+ //# sourceMappingURL=home-project.js.map