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.
- package/.env.example +363 -0
- package/CHANGELOG.md +1186 -0
- package/LICENSE +22 -0
- package/README.md +126 -2
- package/dist/audio/transcribe.js +50 -0
- package/dist/bin/mcp-server.js +378 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +592 -0
- package/dist/bot/file-access.js +141 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +827 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/btw.js +224 -0
- package/dist/bot/handlers/command/cost.js +409 -0
- package/dist/bot/handlers/command/media.js +197 -0
- package/dist/bot/handlers/command/model.js +305 -0
- package/dist/bot/handlers/command/prefs-scope.js +197 -0
- package/dist/bot/handlers/command/project.js +536 -0
- package/dist/bot/handlers/command/resume.js +321 -0
- package/dist/bot/handlers/command/session.js +438 -0
- package/dist/bot/handlers/command/settings.js +1012 -0
- package/dist/bot/handlers/command/shared.js +210 -0
- package/dist/bot/handlers/command/streaming-mode.js +16 -0
- package/dist/bot/handlers/command/tasks.js +513 -0
- package/dist/bot/handlers/command/topic-store.js +113 -0
- package/dist/bot/handlers/command/topic.js +80 -0
- package/dist/bot/handlers/command.handler.js +772 -0
- package/dist/bot/handlers/fork.handler.js +1109 -0
- package/dist/bot/handlers/media-fallback.js +121 -0
- package/dist/bot/handlers/message/replies.js +133 -0
- package/dist/bot/handlers/message/shared.js +117 -0
- package/dist/bot/handlers/message/throttle.js +49 -0
- package/dist/bot/handlers/message/turn-notify.js +169 -0
- package/dist/bot/handlers/message/turn-runner.js +141 -0
- package/dist/bot/handlers/message.handler.js +107 -0
- package/dist/bot/handlers/newbot.handler.js +221 -0
- package/dist/bot/handlers/photo.handler.js +327 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/schedule.handler.js +303 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +209 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +139 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +971 -0
- package/dist/bot/middleware/stale-filter.js +31 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/agent-watchdog.js +162 -0
- package/dist/claude/agent.js +1458 -0
- package/dist/claude/ask-user.js +295 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +126 -0
- package/dist/claude/available-commands.js +153 -0
- package/dist/claude/carry-over.js +27 -0
- package/dist/claude/ccr-shim.js +46 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +121 -0
- package/dist/claude/command-parser.js +200 -0
- package/dist/claude/cost-overlay-scraper.js +129 -0
- package/dist/claude/enabled-plugins.js +56 -0
- package/dist/claude/fork-tree.js +393 -0
- package/dist/claude/held-query.js +190 -0
- package/dist/claude/in-flight-tracker.js +61 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +453 -0
- package/dist/claude/mcp-tools.js +354 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +450 -0
- package/dist/claude/model-catalog.js +85 -0
- package/dist/claude/monitor-relay.js +597 -0
- package/dist/claude/pending-forks.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +337 -0
- package/dist/claude/permission-mode.js +178 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-provider.js +2214 -0
- package/dist/claude/pty-spawn-config.js +296 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/request-queue.js +135 -0
- package/dist/claude/scheduled-runner.js +91 -0
- package/dist/claude/scheduler.js +237 -0
- package/dist/claude/scope-guard.js +274 -0
- package/dist/claude/sdk-permission-gate.js +77 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-cost.js +41 -0
- package/dist/claude/session-history.js +286 -0
- package/dist/claude/session-jsonl.js +920 -0
- package/dist/claude/session-manager.js +195 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +249 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/system-prompt.js +162 -0
- package/dist/claude/tasks-overlay-scraper.js +94 -0
- package/dist/claude/tip-scraper.js +78 -0
- package/dist/claude/tui-modal.js +501 -0
- package/dist/claude/tui-state.js +384 -0
- package/dist/claude/turn-end.js +91 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +305 -0
- package/dist/cli/commands/help.js +25 -0
- package/dist/cli/commands/init.js +123 -0
- package/dist/cli/commands/service.js +678 -0
- package/dist/cli/commands/start.js +53 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/dispatch.js +79 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +638 -0
- package/dist/cli/init/prompter.js +116 -0
- package/dist/cli/init/telegram.js +94 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +500 -0
- package/dist/index.js +367 -0
- package/dist/launcher.js +933 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +149 -0
- package/dist/providers/ccr-provider.js +60 -0
- package/dist/providers/claude-provider.js +63 -0
- package/dist/providers/prefs-sync.js +164 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +127 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/sdk-provider.js +37 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +214 -0
- package/dist/restart-when-idle.js +153 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +173 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +684 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +336 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +27 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +57 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1287 -0
- package/dist/telegram/prompt-label.js +142 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +105 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +209 -0
- package/dist/telegram/telegraph-settings.js +31 -0
- package/dist/telegram/telegraph.js +453 -0
- package/dist/telegram/terminal-renderer.js +671 -0
- package/dist/telegram/terminal-settings.js +25 -0
- package/dist/telegram/thread-titles.js +190 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/tts/tts-settings.js +62 -0
- package/dist/tts/tts.js +245 -0
- package/dist/tts/voice-reply.js +78 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-token.js +74 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +50 -0
- package/dist/utils/claude-env.js +54 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/debug-agent.js +117 -0
- package/dist/utils/debug-watchdog.js +121 -0
- package/dist/utils/download.js +111 -0
- package/dist/utils/exit-codes.js +48 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +81 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/project-data-dir.js +33 -0
- package/dist/utils/reasoning-summary.js +12 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +63 -0
- package/dist/utils/respawn-backoff.js +19 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +76 -4
|
@@ -0,0 +1,453 @@
|
|
|
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
|