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
@@ -1,162 +0,0 @@
1
- /**
2
- * The SDK provider's system prompt.
3
- *
4
- * Pure prompt text — the guidelines, the Telegram formatting rules, and the
5
- * per-tool usage notes that are conditionally included based on which
6
- * features are enabled. Separated from agent.ts so the runtime logic there
7
- * isn't 200 lines of prose, and so prompt edits show up as prompt-only diffs.
8
- *
9
- * Note this is the SDK side only. PTY mode gets its tool guidance from
10
- * buildMcpToolsSystemPromptNote() in pty-spawn-config.ts, which describes the
11
- * larger tool set that src/bin/mcp-server.ts registers.
12
- */
13
- import { config } from '../config.js';
14
- const CORE_GUIDELINES = `You are ${config.BOT_NAME}, an AI assistant helping via Telegram.
15
-
16
- Guidelines:
17
- - Show relevant code snippets when helpful, but keep them short
18
- - If a task requires multiple steps, execute them and summarize what you did
19
- - When you can't do something, explain why briefly`;
20
- const TELEGRAPH_FORMATTING = `
21
-
22
- Response Formatting — Telegraph-Aware Writing:
23
- Write standard markdown. Telegram shows it formatted, chunked across messages when long.
24
- Responses over 2500 chars are ALSO published as a Telegraph (telegra.ph) Instant View page,
25
- linked under the reply — the same text, in a second place, so both renderings have to work.
26
- You MUST write with Telegraph's rendering constraints in mind at all times.
27
-
28
- Telegraph supports ONLY these elements:
29
- - Headings: h3 (from # and ##) and h4 (from ### and ####). No h1, h2, h5, h6.
30
- - Text formatting: **bold**, *italic*, ~~strikethrough~~, \`inline code\`
31
- - Links: [text](url)
32
- - Lists: unordered (- item) and ordered (1. item). Nested lists are supported (indent sub-items).
33
- - Code blocks: \`\`\`code\`\`\` — rendered as monospace preformatted text. No syntax highlighting.
34
- - Blockquotes: > text
35
- - Horizontal rules: ---
36
-
37
- Telegraph does NOT support:
38
- - TABLES — pipe-delimited markdown tables (|col|col|) will NOT render as tables. They break into ugly labeled text. NEVER use markdown tables.
39
- - No checkboxes, footnotes, or task lists
40
- - No custom colors, fonts, or inline styles
41
- - Only two heading levels (h3, h4)
42
-
43
- Instead of tables, use these alternatives (in order of preference):
44
- 1. Bullet lists with bold labels — best for key-value data or comparisons:
45
- - **Name**: Alice
46
- - **Age**: 30
47
- - **City**: NYC
48
-
49
- 2. Nested lists — best for grouped/categorized data:
50
- - **Frontend**
51
- - React 18
52
- - TypeScript
53
- - **Backend**
54
- - Node.js
55
- - Express
56
-
57
- 3. Bold headers with list items — best for feature/comparison matrices:
58
- **Telegram bot** — Grammy v1.31
59
- **AI agent** — Claude Code SDK v1.0
60
- **TTS** — OpenAI gpt-4o-mini-tts
61
-
62
- 4. Preformatted code blocks — ONLY for data where alignment matters (ASCII tables):
63
- \`\`\`
64
- Name Age City
65
- Alice 30 NYC
66
- Bob 25 London
67
- \`\`\`
68
- Note: code blocks lose all formatting (no bold, links, etc.) so only use when alignment is critical.
69
-
70
- Structure guidelines for long responses:
71
- - Use ## or ### headings to create clear sections (renders as h3/h4)
72
- - Use --- horizontal rules to separate major sections
73
- - Use bullet lists liberally — they render cleanly
74
- - Use > blockquotes for callouts, warnings, or important notes
75
- - Keep paragraphs concise; Telegraph renders best with short blocks of text
76
- - Nest sub-items under list items for tree-like structures instead of indented text`;
77
- const INLINE_FORMATTING = `
78
-
79
- Response Formatting:
80
- Write standard markdown; Telegram shows it formatted.
81
- Long responses are automatically chunked into multiple messages.
82
-
83
- Supported formatting:
84
- - **bold**, *italic*, ~~strikethrough~~, \`inline code\`
85
- - Links: [text](url)
86
- - Lists: unordered (- item) and ordered (1. item)
87
- - Code blocks: \`\`\`code\`\`\`
88
- - Blockquotes: > text
89
-
90
- Instead of tables (which don't render well in Telegram), use bullet lists with bold labels:
91
- - **Name**: Alice
92
- - **Age**: 30
93
- - **City**: NYC`;
94
- const BASE_SYSTEM_PROMPT = CORE_GUIDELINES + (config.TELEGRAPH_ENABLED ? TELEGRAPH_FORMATTING : INLINE_FORMATTING);
95
- const SEND_FILE_TOOL_PROMPT = `
96
-
97
- Send File Tool:
98
- You have a telecoder_send_file MCP tool that sends files to the user via Telegram.
99
- Use it after creating or generating files (SVGs, images, PDFs, reports, code bundles, etc.) to deliver them directly.
100
- The file must be within the current working directory or /tmp. Maximum size: 50MB.
101
- When you generate a file and the user would benefit from receiving it, proactively send it — no need to ask.`;
102
- const ASK_USER_TOOL_PROMPT = `
103
-
104
- Ask User Tool:
105
- You have a telecoder_ask_user MCP tool that pops up a Telegram inline keyboard with multiple-choice options and pauses the agent loop until the user taps a button.
106
- Use it when:
107
- - You need a clear decision and free-text would be ambiguous (picking between 2–8 distinct approaches, confirming a destructive action, choosing among detected variants).
108
- - The user's instruction is genuinely ambiguous and asking for free-text would feel like more friction than tapping a button.
109
- Do NOT use it for:
110
- - Open-ended questions where the answer needs to be free-text.
111
- - Trivial confirmations where reasonable defaults exist (just proceed and note the assumption).
112
- - Yes/no questions that the conversation context already implies the answer to.
113
- Keep button labels ≤ 25 chars where you can — a longer one still reaches the user in full (the message body lists every option, keyed A/B/C), but the whole keyboard then shrinks to bare letters. Prefer 2–4 options. Add an optional one-line description per option only when the label alone is unclear.`;
114
- const REQUEST_SECRET_TOOL_PROMPT = `
115
-
116
- Secrets:
117
- When a task needs a credential from the user (an API key, a token, a password), get it with the telecoder_request_secret MCP tool. Never ask them to paste one into the chat, and don't send them to a terminal for it: whatever is sent in the chat ends up in this conversation and in the Telegram history.
118
- The tool runs your command with the secret in $SECRET and on stdin, after the user sends it and the bot deletes their message. You get the exit code and the output with the secret blanked out, never the value, so make the command store or use it in one go.
119
- For a long-lived Claude token (CLAUDE_CODE_OAUTH_TOKEN), set source to "claude-setup-token": the bot runs \`claude setup-token\` on this machine and walks the user through signing in, and the token goes into your command without passing through Telegram.`;
120
- const SET_TOPIC_TOOL_PROMPT = `
121
-
122
- Auto-Topic Tool (IMPORTANT — call this often):
123
- You MUST use the telecoder_set_topic MCP tool to keep the bot's display name in sync with what the user is working on. The bot name renders as "topic — project — Name" with a 64-char limit.
124
-
125
- Call telecoder_set_topic in these situations:
126
- 1. ON YOUR VERY FIRST RESPONSE of any conversation — read the user's first message and call the tool with a 1-4 word topic BEFORE writing your reply text.
127
- 2. WHENEVER THE USER'S FOCUS SHIFTS to a meaningfully different task (different file/feature/bug/question category). Call the tool, THEN respond.
128
- 3. Pass an empty string ("") to clear when the conversation becomes general or idle.
129
-
130
- When NOT to call: minor follow-up on the same topic; clarifying questions about ongoing work; the next message in a continuous task.
131
-
132
- Format: 1-4 lowercase words. Examples: "auth bug", "CI fix", "dark mode", "API docs", "watchdog tuning", "PR planning", "reading code".
133
-
134
- When uncertain whether the topic shifted, LEAN TOWARD CALLING. A slightly-too-frequent topic update is fine; a stale topic is bad UX. The user is relying on the bot name to know what you're working on.`;
135
- const MONITOR_RESPONSE_INSTRUCTIONS = `
136
-
137
- Monitor Event Responses:
138
- When you receive a <task-notification> that contains an <event> tag (i.e. a Monitor tool's event), respond with EXACTLY one line:
139
-
140
- 📡 <event-content>
141
-
142
- Where <event-content> is the verbatim text from the <event> tag — no quotes, no commentary, no surrounding text. This is the only content of your response for that turn. The bot surfaces this single line as a separate Telegram message so the user can see each monitor event.
143
-
144
- The 📡 marks an event's own text. Don't put it in front of anything you write yourself, such as a note that you re-armed an expired monitor.
145
-
146
- This rule applies ONLY to monitor event notifications. Task completion notifications (the ones with <status>) are handled by the bot — for those, respond as you normally would (briefly acknowledge or stay silent).`;
147
- const REASONING_SUMMARY_INSTRUCTIONS = `
148
-
149
- Reasoning Summary (required when enabled):
150
- - At the end of each response, add a short section titled "Reasoning Summary".
151
- - Provide 2–5 bullet points describing high-level actions/decisions taken.
152
- - Do NOT reveal chain-of-thought, hidden reasoning, or sensitive tool outputs.
153
- - Skip the summary for very short acknowledgements or pure error messages.`;
154
- const TOOL_PROMPTS = [
155
- SEND_FILE_TOOL_PROMPT,
156
- ASK_USER_TOOL_PROMPT,
157
- REQUEST_SECRET_TOOL_PROMPT,
158
- config.DYNAMIC_BOT_NAME && !config.AUTO_TOPIC_HAIKU ? SET_TOPIC_TOOL_PROMPT : '',
159
- ].join('');
160
- const SYSTEM_PROMPT = `${BASE_SYSTEM_PROMPT}${TOOL_PROMPTS}${MONITOR_RESPONSE_INSTRUCTIONS}${config.CLAUDE_REASONING_SUMMARY ? REASONING_SUMMARY_INSTRUCTIONS : ''}`;
161
- export { SYSTEM_PROMPT };
162
- //# sourceMappingURL=system-prompt.js.map
@@ -1,37 +0,0 @@
1
- import { sendToAgent as claudeSendToAgent, sendLoopToAgent as claudeSendLoopToAgent, clearConversation as claudeClearConversation, setModel as claudeSetModel, getModel as claudeGetModel, clearModel as claudeClearModel, getCachedUsage as claudeGetCachedUsage, isDangerousMode as claudeIsDangerousMode, } from '../claude/agent.js';
2
- import { getModelsForBinary } from '../claude/model-catalog.js';
3
- import { resolveActiveClaudeExecutable } from '../utils/resolve-claude-bin.js';
4
- export const sdkProvider = {
5
- name: 'claude',
6
- sendToAgent(sessionKey, message, options) {
7
- return claudeSendToAgent(sessionKey, message, options);
8
- },
9
- sendLoopToAgent(sessionKey, message, options) {
10
- return claudeSendLoopToAgent(sessionKey, message, options);
11
- },
12
- clearConversation(sessionKey) {
13
- claudeClearConversation(sessionKey);
14
- },
15
- setModel(scope, model) {
16
- claudeSetModel(scope, model);
17
- },
18
- getModel(scope) {
19
- return claudeGetModel(scope);
20
- },
21
- clearModel(scope) {
22
- claudeClearModel(scope);
23
- },
24
- getCachedUsage(sessionKey) {
25
- return claudeGetCachedUsage(sessionKey);
26
- },
27
- isDangerousMode() {
28
- return claudeIsDangerousMode();
29
- },
30
- async getAvailableModels() {
31
- // The SDK forwards `model` to whichever binary it spawns — usually the one
32
- // bundled with claude-agent-sdk, which lags the CLI on PATH. Ask that
33
- // binary rather than assuming it matches PTY mode's.
34
- return getModelsForBinary(resolveActiveClaudeExecutable());
35
- },
36
- };
37
- //# sourceMappingURL=sdk-provider.js.map
@@ -1,31 +0,0 @@
1
- /**
2
- * Per-chat Telegraph settings — controls whether long replies are offloaded to
3
- * a Telegraph page instead of being split across Telegram messages.
4
- */
5
- import { z } from 'zod';
6
- import { config } from '../config.js';
7
- import { createKeyedSettings } from '../utils/keyed-settings.js';
8
- const store = createKeyedSettings({
9
- file: 'telegraph-settings.json',
10
- label: 'Telegraph',
11
- entrySchema: z.object({ enabled: z.boolean().optional() }),
12
- normalize: (stored) => ({
13
- // Default to the global config value if not set
14
- enabled: typeof stored?.enabled === 'boolean' ? stored.enabled : config.TELEGRAPH_ENABLED,
15
- }),
16
- });
17
- export function getTelegraphSettings(sessionKey) {
18
- return store.get(sessionKey);
19
- }
20
- export function setTelegraphEnabled(sessionKey, enabled) {
21
- store.update(sessionKey, { enabled });
22
- }
23
- /**
24
- * Whether this chat publishes to Telegraph. The global switch wins: a chat
25
- * that turned it on while TELEGRAPH_ENABLED was true stops publishing the
26
- * moment the owner turns it off, since every page is public.
27
- */
28
- export function isTelegraphEnabled(sessionKey) {
29
- return config.TELEGRAPH_ENABLED && store.get(sessionKey).enabled;
30
- }
31
- //# sourceMappingURL=telegraph-settings.js.map
@@ -1,453 +0,0 @@
1
- import { randomUUID } from 'crypto';
2
- import * as fs from 'fs';
3
- import * as path from 'path';
4
- import { z } from 'zod';
5
- import { config } from '../config.js';
6
- import { isTelegraphEnabled } from './telegraph-settings.js';
7
- import { atomicWriteFileSync } from '../utils/atomic-write.js';
8
- import { configFile } from '../utils/config-home.js';
9
- // Zod schema for Telegraph account file
10
- const telegraphAccountSchema = z.object({
11
- access_token: z.string().min(1),
12
- auth_url: z.string().url(),
13
- short_name: z.string(),
14
- });
15
- // Telegraph account data (no client needed - using native fetch)
16
- let telegraphAccount = null;
17
- // Length past which a reply is worth an Instant View page alongside the text.
18
- const TELEGRAPH_THRESHOLD = 2500;
19
- /**
20
- * Initialize Telegraph account (creates one if needed)
21
- * Uses native fetch instead of telegra.ph library
22
- */
23
- export async function initTelegraph() {
24
- try {
25
- // In the config home (the checkout root, or ~/.telecoder for an npm
26
- // install), not the cwd, which a service manager can set to anywhere.
27
- const accountFile = configFile('.telegraph-account.json');
28
- if (fs.existsSync(accountFile)) {
29
- // Load existing account with schema validation
30
- let raw;
31
- try {
32
- raw = JSON.parse(fs.readFileSync(accountFile, 'utf-8'));
33
- }
34
- catch {
35
- console.warn('[Telegraph] Malformed account file, creating new account');
36
- raw = null;
37
- }
38
- const result = raw ? telegraphAccountSchema.safeParse(raw) : { success: false };
39
- if (result.success) {
40
- telegraphAccount = result.data;
41
- console.log('[Telegraph] Loaded existing account');
42
- return;
43
- }
44
- else {
45
- const reason = 'error' in result ? result.error.message : 'malformed JSON';
46
- console.warn('[Telegraph] Invalid account file, creating new account:', reason);
47
- // Fall through to create new account
48
- }
49
- }
50
- // Create new account using native fetch
51
- const response = await fetch('https://api.telegra.ph/createAccount', {
52
- method: 'POST',
53
- headers: { 'Content-Type': 'application/json' },
54
- body: JSON.stringify({
55
- short_name: 'TeleCoder',
56
- author_name: 'Claude Agent',
57
- author_url: 'https://github.com/anthropics/claude-code'
58
- })
59
- });
60
- if (!response.ok) {
61
- throw new Error(`Telegraph API error: ${response.statusText}`);
62
- }
63
- const json = await response.json();
64
- if (!json.ok || !json.result) {
65
- throw new Error(json.error || 'Unknown Telegraph API error');
66
- }
67
- if (!json.result.access_token || !json.result.auth_url) {
68
- throw new Error('Telegraph API returned incomplete account data');
69
- }
70
- telegraphAccount = {
71
- access_token: json.result.access_token,
72
- auth_url: json.result.auth_url,
73
- short_name: json.result.short_name || 'TeleCoder'
74
- };
75
- // Save for future use
76
- atomicWriteFileSync(accountFile, JSON.stringify(telegraphAccount, null, 2), { mode: 0o600 });
77
- console.log('[Telegraph] Created new account');
78
- }
79
- catch (error) {
80
- console.error('[Telegraph] Failed to initialize:', error);
81
- }
82
- }
83
- /**
84
- * Whether `content` is long enough to be worth an Instant View page *alongside*
85
- * the inline reply. False when Telegraph is off globally or for this chat.
86
- *
87
- * The page is an extra way to read the answer, never a substitute for it. It
88
- * used to be a substitute: anything past the threshold was replaced in chat by
89
- * a 200-character stub ending in an ellipsis, and the only way back to the text
90
- * the model actually wrote was `/recap`. Callers now send the reply in full and
91
- * hang the URL under it.
92
- *
93
- * Length is the only trigger. Merely containing a markdown table used to send a
94
- * three-line reply to Telegraph as well, on the grounds that Telegram can't
95
- * render tables — but `markdownToEntities` rewrites pipe tables into
96
- * `**Header**: cell` lines before they ever reach Telegram, so there is
97
- * nothing left to compensate for.
98
- */
99
- export function shouldPublishTelegraph(content, sessionKey) {
100
- // Global kill switch, then the per-chat toggle.
101
- if (!config.TELEGRAPH_ENABLED)
102
- return false;
103
- if (sessionKey !== undefined && !isTelegraphEnabled(sessionKey))
104
- return false;
105
- return content.length > TELEGRAPH_THRESHOLD;
106
- }
107
- /**
108
- * Convert markdown to Telegraph Node format
109
- * Supported tags: a, aside, b, blockquote, br, code, em, figcaption, figure,
110
- * h3, h4, hr, i, iframe, img, li, ol, p, pre, s, strong, u, ul, video
111
- */
112
- function markdownToNodes(markdown) {
113
- const nodes = [];
114
- const lines = markdown.split('\n');
115
- let inCodeBlock = false;
116
- let codeBlockContent = '';
117
- let inList = null;
118
- let listItems = [];
119
- let pendingParagraphLines = [];
120
- let tableHeaders = [];
121
- const flushParagraph = () => {
122
- if (pendingParagraphLines.length === 0)
123
- return;
124
- const children = [];
125
- for (let j = 0; j < pendingParagraphLines.length; j++) {
126
- if (j > 0)
127
- children.push({ tag: 'br' });
128
- children.push(...parseInline(pendingParagraphLines[j]));
129
- }
130
- nodes.push({ tag: 'p', children });
131
- pendingParagraphLines = [];
132
- };
133
- const flushList = () => {
134
- if (inList && listItems.length > 0) {
135
- nodes.push({ tag: inList, children: listItems });
136
- listItems = [];
137
- inList = null;
138
- }
139
- };
140
- const flushAll = () => {
141
- flushParagraph();
142
- flushList();
143
- };
144
- for (let i = 0; i < lines.length; i++) {
145
- const line = lines[i];
146
- // Code block handling
147
- if (line.startsWith('```')) {
148
- flushAll();
149
- if (inCodeBlock) {
150
- // End code block
151
- nodes.push({
152
- tag: 'pre',
153
- children: [{ tag: 'code', children: [codeBlockContent.trimEnd()] }]
154
- });
155
- inCodeBlock = false;
156
- codeBlockContent = '';
157
- }
158
- else {
159
- // Start code block
160
- inCodeBlock = true;
161
- }
162
- continue;
163
- }
164
- if (inCodeBlock) {
165
- codeBlockContent += line + '\n';
166
- continue;
167
- }
168
- // Empty line = paragraph break (flush accumulated lines into a <p>)
169
- if (line.trim() === '') {
170
- flushAll();
171
- continue;
172
- }
173
- // Horizontal rule
174
- if (/^[-*_]{3,}\s*$/.test(line)) {
175
- flushAll();
176
- nodes.push({ tag: 'hr' });
177
- continue;
178
- }
179
- // Headers
180
- if (line.startsWith('#### ')) {
181
- flushAll();
182
- nodes.push({ tag: 'h4', children: parseInline(line.slice(5)) });
183
- continue;
184
- }
185
- if (line.startsWith('### ')) {
186
- flushAll();
187
- nodes.push({ tag: 'h4', children: parseInline(line.slice(4)) });
188
- continue;
189
- }
190
- if (line.startsWith('## ')) {
191
- flushAll();
192
- nodes.push({ tag: 'h3', children: parseInline(line.slice(3)) });
193
- continue;
194
- }
195
- if (line.startsWith('# ')) {
196
- flushAll();
197
- nodes.push({ tag: 'h3', children: parseInline(line.slice(2)) });
198
- continue;
199
- }
200
- // Unordered list items
201
- if (line.match(/^[\s]*[-*+]\s+/)) {
202
- flushParagraph();
203
- if (inList !== 'ul') {
204
- flushList();
205
- inList = 'ul';
206
- }
207
- const content = line.replace(/^[\s]*[-*+]\s+/, '');
208
- listItems.push({ tag: 'li', children: parseInline(content) });
209
- continue;
210
- }
211
- // Ordered list items
212
- const orderedMatch = line.match(/^[\s]*(\d+)\.\s+(.*)$/);
213
- if (orderedMatch) {
214
- flushParagraph();
215
- if (inList !== 'ol') {
216
- flushList();
217
- inList = 'ol';
218
- }
219
- listItems.push({ tag: 'li', children: parseInline(orderedMatch[2]) });
220
- continue;
221
- }
222
- // Blockquote
223
- if (line.startsWith('> ')) {
224
- flushAll();
225
- nodes.push({ tag: 'blockquote', children: parseInline(line.slice(2)) });
226
- continue;
227
- }
228
- // Table handling - convert to clean formatted lists instead of fake tables
229
- if (line.includes('|') && line.trim().startsWith('|')) {
230
- flushAll();
231
- const cells = line.split('|').filter(c => c.trim()).map(c => c.trim());
232
- // Skip separator rows (e.g., |---|---|)
233
- if (cells.length > 0 && cells.every(c => /^[-:]+$/.test(c))) {
234
- continue;
235
- }
236
- // Detect header row: if next line is a separator, this is the header
237
- const nextLine = i + 1 < lines.length ? lines[i + 1] : '';
238
- const nextCells = nextLine.split('|').filter(c => c.trim()).map(c => c.trim());
239
- const isHeader = nextCells.length > 0 && nextCells.every(c => /^[-:]+$/.test(c));
240
- if (isHeader && cells.length > 0) {
241
- tableHeaders = cells;
242
- // Render header as a bold line
243
- nodes.push({ tag: 'p', children: [{ tag: 'b', children: [cells.join(' · ')] }] });
244
- continue;
245
- }
246
- // Data row - use stored headers for labeled output
247
- if (tableHeaders.length > 0 && cells.length > 0) {
248
- const parts = [];
249
- cells.forEach((cell, idx) => {
250
- if (idx > 0)
251
- parts.push(' | ');
252
- if (tableHeaders[idx]) {
253
- parts.push({ tag: 'b', children: [tableHeaders[idx] + ': '] });
254
- }
255
- parts.push(cell);
256
- });
257
- nodes.push({ tag: 'p', children: parts });
258
- }
259
- else if (cells.length > 0) {
260
- // No headers available - just join with separator
261
- nodes.push({ tag: 'p', children: [cells.join(' | ')] });
262
- }
263
- continue;
264
- }
265
- // Regular text line — accumulate into pending paragraph
266
- flushList();
267
- pendingParagraphLines.push(line);
268
- }
269
- // Flush any remaining accumulated content
270
- flushAll();
271
- // Close any unclosed code block
272
- if (inCodeBlock && codeBlockContent) {
273
- nodes.push({
274
- tag: 'pre',
275
- children: [{ tag: 'code', children: [codeBlockContent.trimEnd()] }]
276
- });
277
- }
278
- return nodes;
279
- }
280
- /**
281
- * Parse inline markdown (bold, italic, code, links, strikethrough)
282
- * Returns array of Telegraph nodes
283
- */
284
- function parseInline(text) {
285
- const nodes = [];
286
- let remaining = text;
287
- // Regex patterns for inline elements (order matters - longer patterns first)
288
- const patterns = [
289
- // Links: [text](url)
290
- {
291
- regex: /\[([^\]]+)\]\(([^)]+)\)/,
292
- handler: (m) => ({ tag: 'a', attrs: { href: m[2] }, children: [m[1]] })
293
- },
294
- // Bold + Italic: ***text*** or ___text___
295
- {
296
- regex: /\*\*\*(.+?)\*\*\*/,
297
- handler: (m) => ({ tag: 'b', children: [{ tag: 'i', children: [m[1]] }] })
298
- },
299
- // Bold: **text** or __text__
300
- {
301
- regex: /\*\*(.+?)\*\*/,
302
- handler: (m) => ({ tag: 'b', children: [m[1]] })
303
- },
304
- {
305
- regex: /__(.+?)__/,
306
- handler: (m) => ({ tag: 'b', children: [m[1]] })
307
- },
308
- // Italic: *text* or _text_ (but not inside words for _)
309
- {
310
- regex: /\*(.+?)\*/,
311
- handler: (m) => ({ tag: 'i', children: [m[1]] })
312
- },
313
- {
314
- regex: /(?<!\w)_(.+?)_(?!\w)/,
315
- handler: (m) => ({ tag: 'i', children: [m[1]] })
316
- },
317
- // Strikethrough: ~~text~~
318
- {
319
- regex: /~~(.+?)~~/,
320
- handler: (m) => ({ tag: 's', children: [m[1]] })
321
- },
322
- // Inline code: `code`
323
- {
324
- regex: /`([^`]+)`/,
325
- handler: (m) => ({ tag: 'code', children: [m[1]] })
326
- },
327
- ];
328
- while (remaining.length > 0) {
329
- let earliestMatch = null;
330
- // Find the earliest matching pattern
331
- for (const pattern of patterns) {
332
- const match = remaining.match(pattern.regex);
333
- if (match && match.index !== undefined) {
334
- if (!earliestMatch || match.index < earliestMatch.index) {
335
- earliestMatch = {
336
- index: match.index,
337
- length: match[0].length,
338
- node: pattern.handler(match)
339
- };
340
- }
341
- }
342
- }
343
- if (earliestMatch) {
344
- // Add text before the match
345
- if (earliestMatch.index > 0) {
346
- nodes.push(remaining.slice(0, earliestMatch.index));
347
- }
348
- // Add the matched node
349
- nodes.push(earliestMatch.node);
350
- // Continue with the rest
351
- remaining = remaining.slice(earliestMatch.index + earliestMatch.length);
352
- }
353
- else {
354
- // No more matches - add remaining text
355
- nodes.push(remaining);
356
- break;
357
- }
358
- }
359
- return nodes;
360
- }
361
- /**
362
- * Create a Telegraph page with a UUID-based title for unguessable URLs
363
- * The UUID becomes the URL slug, making pages unguessable
364
- */
365
- async function createPageWithUuidTitle(token, displayTitle, content) {
366
- // Use UUID as the actual title to make URL unguessable
367
- const uuidTitle = randomUUID();
368
- // Prepend the display title as an h3 heading in the content
369
- const contentWithTitle = [
370
- { tag: 'h3', children: [displayTitle] },
371
- ...content
372
- ];
373
- const response = await fetch('https://api.telegra.ph/createPage', {
374
- method: 'POST',
375
- headers: { 'Content-Type': 'application/json' },
376
- body: JSON.stringify({
377
- access_token: token,
378
- title: uuidTitle,
379
- author_name: 'Claude Agent',
380
- content: contentWithTitle,
381
- return_content: false
382
- })
383
- });
384
- if (!response.ok) {
385
- throw new Error(`Telegraph API error: ${response.statusText}`);
386
- }
387
- const json = await response.json();
388
- if (!json.ok || !json.result || !json.result.url) {
389
- throw new Error(json.error || 'Unknown Telegraph API error');
390
- }
391
- return { url: json.result.url };
392
- }
393
- // Telegraph's cap on a page's content. createPage turns anything bigger away
394
- // with CONTENT_TOO_BIG.
395
- const PAGE_CONTENT_LIMIT = 64 * 1024;
396
- /**
397
- * Whether `markdown` fits on one Telegraph page. Telegraph doesn't say how it
398
- * counts its 64 KB, so this takes the strictest reading — the content as JSON
399
- * with `/` and every non-ASCII character escaped — and keeps a kilobyte back
400
- * for the title heading createPageWithUuidTitle puts on top.
401
- */
402
- export function fitsTelegraphPage(markdown) {
403
- const json = JSON.stringify(markdownToNodes(markdown))
404
- .replace(/\//g, '\\/')
405
- .replace(/[^\x00-\x7f]/g, '\\uffff');
406
- return json.length <= PAGE_CONTENT_LIMIT - 1024;
407
- }
408
- /**
409
- * Create a Telegraph page from markdown content
410
- * Uses a UUID-based title to prevent URL guessing
411
- */
412
- export async function createTelegraphPage(title, markdown) {
413
- if (!telegraphAccount) {
414
- await initTelegraph();
415
- }
416
- if (!telegraphAccount) {
417
- console.error('[Telegraph] Account not initialized');
418
- return null;
419
- }
420
- try {
421
- const content = markdownToNodes(markdown);
422
- const page = await createPageWithUuidTitle(telegraphAccount.access_token, title, content);
423
- return page.url;
424
- }
425
- catch (error) {
426
- console.error('[Telegraph] Failed to create page:', error);
427
- return null;
428
- }
429
- }
430
- /**
431
- * Create Telegraph page from an existing markdown file
432
- */
433
- export async function createTelegraphFromFile(filePath) {
434
- try {
435
- if (!fs.existsSync(filePath)) {
436
- console.error('[Telegraph] File not found:', filePath);
437
- return null;
438
- }
439
- const content = fs.readFileSync(filePath, 'utf-8');
440
- const fileName = path.basename(filePath, path.extname(filePath));
441
- const title = fileName.replace(/[-_]/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
442
- return await createTelegraphPage(title, content);
443
- }
444
- catch (error) {
445
- console.error('[Telegraph] Failed to create page from file:', error);
446
- return null;
447
- }
448
- }
449
- // Initialize on module load (only if enabled)
450
- if (config.TELEGRAPH_ENABLED) {
451
- initTelegraph().catch(console.error);
452
- }
453
- //# sourceMappingURL=telegraph.js.map