@qusic/pi-telegram 0.0.0 → 0.1.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/LICENSE +21 -0
- package/README.md +71 -29
- package/package.json +59 -8
- package/src/api.ts +204 -0
- package/src/chunk.ts +86 -0
- package/src/config.ts +55 -0
- package/src/dispatch.ts +237 -0
- package/src/index.ts +21 -0
- package/src/media.ts +142 -0
- package/src/polling.ts +152 -0
- package/src/preview.ts +149 -0
- package/src/toolcall.ts +145 -0
- package/src/turn.ts +209 -0
- package/src/types.ts +74 -0
- package/src/utils.ts +91 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bang Lee
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,45 +1,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-telegram
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/Qusic/pi-telegram/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/@qusic/pi-telegram)
|
|
5
|
+
[](https://github.com/earendil-works/pi)
|
|
6
|
+
[](LICENSE)
|
|
4
7
|
|
|
5
|
-
|
|
8
|
+
A Telegram DM bridge for [pi](https://pi.dev) — chat with your pi coding agent from anywhere through a Telegram bot. Based on [badlogic/pi-telegram](https://github.com/badlogic/pi-telegram), rewritten with AI (Claude `opus-4.7`) to better fit my personal preferences and needs.
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
## Features
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
- **Two-way Telegram ↔ pi bridge** over long-polling `getUpdates`
|
|
13
|
+
- **Streamed replies** with live previews, including extended thinking (separated from the answer by 💭 / ✏️ markers); long answers grow incrementally instead of only appearing at the end
|
|
14
|
+
- **Markdown rendering** to native Telegram formatting (headings, bold, italics, links, inline & fenced code, blockquotes, lists, tables, task lists, footnotes, LaTeX), robust to partial mid-stream snippets
|
|
15
|
+
- **Attachments in**: photos, albums, documents, video, audio, voice, animations and stickers; images are inlined as image inputs, everything else is referenced by local path
|
|
16
|
+
- **Attachments out**: a `telegram_attach` tool lets the agent send generated files with its reply
|
|
17
|
+
- **Tool call breadcrumbs**: each tool call posts a `🔧 …` Rich Message with its arguments and output in collapsible blocks, edited in place to ✅ / ❌ on completion
|
|
18
|
+
- **Mid-turn steering**: messages sent while the agent is busy are injected into the running turn
|
|
19
|
+
- **Typing indicator** while the agent is working
|
|
20
|
+
- **Single-user authorization** by Telegram user id
|
|
10
21
|
|
|
11
|
-
|
|
12
|
-
1. Configure OIDC trusted publishing for the package name `@qusic/pi-telegram`
|
|
13
|
-
2. Enable secure, token-less publishing from CI/CD workflows
|
|
14
|
-
3. Establish provenance for packages published under this name
|
|
22
|
+
### Telegram-side commands
|
|
15
23
|
|
|
16
|
-
|
|
24
|
+
Auto-published as the bot menu at boot. Anything else is forwarded to pi as a user turn.
|
|
17
25
|
|
|
18
|
-
|
|
26
|
+
| Command | Description |
|
|
27
|
+
| ---------- | -------------------------------------------- |
|
|
28
|
+
| `/new` | Start a new pi session |
|
|
29
|
+
| `/resume` | List recent sessions; `/resumeN` to switch |
|
|
30
|
+
| `/stop` | Abort the current turn |
|
|
31
|
+
| `/status` | Model, token usage, cost and context window |
|
|
32
|
+
| `/compact` | Compact the conversation |
|
|
33
|
+
| `/skills` | List skills available to the agent |
|
|
19
34
|
|
|
20
|
-
|
|
35
|
+
Resuming a session echoes that session's last reply back to the chat, so it reflects where you left off (the TUI already shows the full history).
|
|
21
36
|
|
|
22
|
-
|
|
37
|
+
## Differences vs. upstream `badlogic/pi-telegram`
|
|
23
38
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
39
|
+
| Area | Upstream | This fork |
|
|
40
|
+
| --------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
41
|
+
| Setup & lifecycle | `/telegram-setup` / `/telegram-connect` / `/telegram-disconnect` commands; explicit per-session connect | No pi-side commands; you write `~/.pi/agent/telegram.json` yourself, polling auto-starts per session |
|
|
42
|
+
| Authorization | First DM user is auto-paired | First DM user id is reported via `notify`; you add it to the config and restart |
|
|
43
|
+
| Commands & bot menu | Telegram-side commands limited to `/status`, `/compact`, `stop`, `/help`, `/start`; no menu published | Adds `/new`, `/resume`, `/skills` and publishes the menu via `setMyCommands`; session switching from Telegram |
|
|
44
|
+
| Concurrency | Extra messages while busy are queued and dispatched after the current turn ends | Extra messages are steered into the running turn |
|
|
45
|
+
| Aborted-turn replay | After `stop`, queued messages are re-injected as a synthetic history block | No replay — `stop` just aborts |
|
|
46
|
+
| Prompt prefix | Each message prefixed with `[telegram]`, plus a system-prompt suffix | Forwarded as-is |
|
|
47
|
+
| Rendering | Plain text only; URL preview cards enabled | Native Rich Message (`sendRichMessage`, GitHub-Flavored Markdown) for every outgoing message |
|
|
48
|
+
| Streaming | Probes `sendMessageDraft`, falls back to `sendMessage` + `editMessageText`; previews truncated at 4096 chars, full answer only appears at `agent_end` | `sendRichMessageDraft` live previews committed with `sendRichMessage`; oversized previews are promoted into real messages mid-stream so long answers grow live |
|
|
49
|
+
| Tool call breadcrumbs | None | `🔧 …` Rich Message per tool call: summary line plus collapsible arguments + output, edited with ✅ / ❌ |
|
|
50
|
+
| Thinking blocks | Stripped | Streamed, separated by 💭 / ✏️ markers |
|
|
51
|
+
| Status bar | Rich colored status | Only transient polling errors |
|
|
28
52
|
|
|
29
|
-
|
|
53
|
+
Media-group debouncing and the `telegram_attach` tool surface match upstream. Internally the fork is split into small manager closures instead of a single file.
|
|
30
54
|
|
|
31
|
-
|
|
32
|
-
- Contains no executable code
|
|
33
|
-
- Provides no functionality
|
|
34
|
-
- Should not be installed as a dependency
|
|
35
|
-
- Exists only for administrative purposes
|
|
55
|
+
## Install
|
|
36
56
|
|
|
37
|
-
|
|
57
|
+
Only one pi session should poll a given bot token at a time, so load this per-session instead of installing globally:
|
|
38
58
|
|
|
39
|
-
|
|
40
|
-
-
|
|
41
|
-
|
|
59
|
+
```bash
|
|
60
|
+
pi -e npm:@qusic/pi-telegram
|
|
61
|
+
```
|
|
42
62
|
|
|
43
|
-
|
|
63
|
+
To use the Git checkout instead:
|
|
44
64
|
|
|
45
|
-
|
|
65
|
+
```bash
|
|
66
|
+
pi -e git:github.com/Qusic/pi-telegram
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Configure
|
|
70
|
+
|
|
71
|
+
1. Talk to [@BotFather](https://t.me/BotFather), run `/newbot`, copy the bot token.
|
|
72
|
+
2. Create `~/.pi/agent/telegram.json`:
|
|
73
|
+
|
|
74
|
+
```json
|
|
75
|
+
{ "botToken": "123456:ABC-your-token-here" }
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
3. Start pi — polling starts automatically.
|
|
79
|
+
4. DM your bot once. pi will notify you with your Telegram user id; add `"allowedUserId": <id>` to the config and restart.
|
|
80
|
+
|
|
81
|
+
## Usage
|
|
82
|
+
|
|
83
|
+
Just chat with your bot. Text becomes the next pi turn; photos/files are downloaded and referenced in the prompt (images also inlined); ask pi for an artifact and it can call `telegram_attach` to send files back; `/stop` aborts.
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
MIT. See [LICENSE](./LICENSE).
|
package/package.json
CHANGED
|
@@ -1,10 +1,61 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
2
|
+
"name": "@qusic/pi-telegram",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Telegram bridge extension for Pi agent",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package",
|
|
7
|
+
"pi-extension",
|
|
8
|
+
"pi",
|
|
9
|
+
"pi-coding-agent",
|
|
10
|
+
"coding-agent",
|
|
11
|
+
"ai-agent",
|
|
12
|
+
"telegram",
|
|
13
|
+
"telegram-bot",
|
|
14
|
+
"bot",
|
|
15
|
+
"bridge",
|
|
16
|
+
"messaging",
|
|
17
|
+
"remote-control"
|
|
18
|
+
],
|
|
19
|
+
"homepage": "https://github.com/Qusic/pi-telegram#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/Qusic/pi-telegram/issues"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/Qusic/pi-telegram.git"
|
|
26
|
+
},
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"type": "module",
|
|
29
|
+
"files": [
|
|
30
|
+
"src"
|
|
31
|
+
],
|
|
32
|
+
"pi": {
|
|
33
|
+
"extensions": [
|
|
34
|
+
"./src/index.ts"
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"test": "node --test \"test/**/*.test.ts\"",
|
|
39
|
+
"check": "tsc",
|
|
40
|
+
"lint": "biome check",
|
|
41
|
+
"format": "biome check --write",
|
|
42
|
+
"release": "semantic-release"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"@earendil-works/pi-agent-core": "*",
|
|
46
|
+
"@earendil-works/pi-ai": "*",
|
|
47
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
48
|
+
"typebox": "*"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@biomejs/biome": "^2.5.13",
|
|
52
|
+
"@earendil-works/pi-agent-core": "0.85.1",
|
|
53
|
+
"@earendil-works/pi-ai": "0.85.1",
|
|
54
|
+
"@earendil-works/pi-coding-agent": "0.85.1",
|
|
55
|
+
"@types/node": "^24.13.4",
|
|
56
|
+
"npm": "^11.6.2",
|
|
57
|
+
"semantic-release": "^25.0.9",
|
|
58
|
+
"typebox": "1.3.7",
|
|
59
|
+
"typescript": "^7.0.2"
|
|
60
|
+
}
|
|
10
61
|
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Telegram Bot API HTTP client.
|
|
2
|
+
|
|
3
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import type { createConfig } from "./config.ts";
|
|
7
|
+
import { guessMediaType, sanitizeFileName } from "./utils.ts";
|
|
8
|
+
|
|
9
|
+
const TEMP_DIR = join(homedir(), ".pi", "agent", "tmp", "telegram");
|
|
10
|
+
|
|
11
|
+
/** Telegram's per-message character budget. */
|
|
12
|
+
export const MAX_MESSAGE_LENGTH = 32768;
|
|
13
|
+
|
|
14
|
+
interface TelegramApiResponse<T> {
|
|
15
|
+
ok: boolean;
|
|
16
|
+
result?: T;
|
|
17
|
+
description?: string;
|
|
18
|
+
error_code?: number;
|
|
19
|
+
parameters?: { retry_after?: number };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function abortError(): Error {
|
|
23
|
+
const err = new Error("aborted");
|
|
24
|
+
err.name = "AbortError";
|
|
25
|
+
return err;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function delay(ms: number, signal?: AbortSignal): Promise<void> {
|
|
29
|
+
return new Promise((resolve, reject) => {
|
|
30
|
+
if (signal?.aborted) return reject(abortError());
|
|
31
|
+
const timer = setTimeout(() => {
|
|
32
|
+
signal?.removeEventListener("abort", onAbort);
|
|
33
|
+
resolve();
|
|
34
|
+
}, ms);
|
|
35
|
+
function onAbort() {
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
reject(abortError());
|
|
38
|
+
}
|
|
39
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface TelegramGetFileResult {
|
|
44
|
+
file_path: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Response shape for sendRichMessage / sendPhoto / sendDocument etc. */
|
|
48
|
+
interface TelegramSentMessage {
|
|
49
|
+
message_id: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function createApi(config: Awaited<ReturnType<typeof createConfig>>) {
|
|
53
|
+
const { apiRoot: configuredApiRoot, botToken } = config.get();
|
|
54
|
+
const apiRoot = (configuredApiRoot || "https://api.telegram.org").replace(/\/+$/, "");
|
|
55
|
+
const baseUrl = `${apiRoot}/bot${botToken}/`;
|
|
56
|
+
const fileBaseUrl = `${apiRoot}/file/bot${botToken}/`;
|
|
57
|
+
|
|
58
|
+
// POST to the Bot API with shared retry on 429 / 5xx / network errors.
|
|
59
|
+
// Pass a plain object for the common JSON call, or a request factory
|
|
60
|
+
// (re-invoked per attempt — a consumed body can't be replayed) for non-JSON
|
|
61
|
+
// calls like multipart uploads.
|
|
62
|
+
//
|
|
63
|
+
// Telegram per-chat rate limits (HTTP 429) are routine when streaming long
|
|
64
|
+
// answers (each promoted chunk + draft is a separate request); retrying them
|
|
65
|
+
// — and transient 5xx / network blips — keeps a rejection from stalling the
|
|
66
|
+
// live draft and dropping the final message.
|
|
67
|
+
async function call<T>(
|
|
68
|
+
method: string,
|
|
69
|
+
body: Record<string, unknown> | (() => Promise<Response>),
|
|
70
|
+
opts?: { signal?: AbortSignal },
|
|
71
|
+
): Promise<T> {
|
|
72
|
+
const signal = opts?.signal;
|
|
73
|
+
const makeRequest =
|
|
74
|
+
typeof body === "function"
|
|
75
|
+
? body
|
|
76
|
+
: () =>
|
|
77
|
+
fetch(baseUrl + method, {
|
|
78
|
+
method: "POST",
|
|
79
|
+
headers: { "content-type": "application/json" },
|
|
80
|
+
body: JSON.stringify(body),
|
|
81
|
+
signal: signal ?? null,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const MAX_RETRIES = 5;
|
|
85
|
+
const MAX_BACKOFF_MS = 15_000;
|
|
86
|
+
// Exponential backoff (capped) for retry attempt `n` (0-based).
|
|
87
|
+
const backoff = (n: number) => Math.min(2 ** n * 500, MAX_BACKOFF_MS);
|
|
88
|
+
for (let attempt = 0; ; attempt++) {
|
|
89
|
+
let response: Response;
|
|
90
|
+
try {
|
|
91
|
+
response = await makeRequest();
|
|
92
|
+
} catch (err) {
|
|
93
|
+
// Network error: retry unless aborted or out of attempts.
|
|
94
|
+
if (signal?.aborted || attempt >= MAX_RETRIES) throw err;
|
|
95
|
+
await delay(backoff(attempt), signal);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const data = (await response.json()) as TelegramApiResponse<T>;
|
|
99
|
+
if (data.ok && data.result !== undefined) return data.result;
|
|
100
|
+
|
|
101
|
+
const code = data.error_code;
|
|
102
|
+
const retriable = code === 429 || (code !== undefined && code >= 500);
|
|
103
|
+
if (retriable && !signal?.aborted && attempt < MAX_RETRIES) {
|
|
104
|
+
const retryAfter = data.parameters?.retry_after;
|
|
105
|
+
await delay(retryAfter !== undefined ? retryAfter * 1000 + 250 : backoff(attempt), signal);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
throw new Error(data.description || `Telegram API ${method} failed`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function callMultipart<T>(
|
|
113
|
+
method: string,
|
|
114
|
+
fields: Record<string, string>,
|
|
115
|
+
fileField: string,
|
|
116
|
+
filePath: string,
|
|
117
|
+
fileName: string,
|
|
118
|
+
opts?: { signal?: AbortSignal },
|
|
119
|
+
): Promise<T> {
|
|
120
|
+
// Read once; rebuild the FormData per attempt (a consumed body can't be reused).
|
|
121
|
+
const blob = new Blob([await readFile(filePath)]);
|
|
122
|
+
return call<T>(
|
|
123
|
+
method,
|
|
124
|
+
() => {
|
|
125
|
+
const form = new FormData();
|
|
126
|
+
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
|
127
|
+
form.set(fileField, blob, fileName);
|
|
128
|
+
return fetch(baseUrl + method, { method: "POST", body: form, signal: opts?.signal ?? null });
|
|
129
|
+
},
|
|
130
|
+
opts,
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function download(fileId: string, suggestedName: string): Promise<string> {
|
|
135
|
+
const file = await call<TelegramGetFileResult>("getFile", { file_id: fileId });
|
|
136
|
+
await mkdir(TEMP_DIR, { recursive: true });
|
|
137
|
+
const targetPath = join(TEMP_DIR, `${Date.now()}-${sanitizeFileName(suggestedName)}`);
|
|
138
|
+
const response = await fetch(fileBaseUrl + file.file_path);
|
|
139
|
+
if (!response.ok) throw new Error(`Failed to download Telegram file: ${response.status}`);
|
|
140
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
141
|
+
await writeFile(targetPath, Buffer.from(arrayBuffer));
|
|
142
|
+
return targetPath;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Send markdown as a native Rich Message, returning the sent message so callers
|
|
146
|
+
* can edit it later. Plain strings are valid markdown too, so this is also the
|
|
147
|
+
* channel for short system/status replies. */
|
|
148
|
+
async function sendText(
|
|
149
|
+
chatId: number,
|
|
150
|
+
markdown: string,
|
|
151
|
+
options?: { silent?: boolean },
|
|
152
|
+
): Promise<TelegramSentMessage> {
|
|
153
|
+
return await call<TelegramSentMessage>("sendRichMessage", {
|
|
154
|
+
chat_id: chatId,
|
|
155
|
+
rich_message: { markdown },
|
|
156
|
+
...(options?.silent ? { disable_notification: true } : {}),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Edit a message in place with new Rich Message content (markdown as-is). */
|
|
161
|
+
async function editText(chatId: number, messageId: number, markdown: string): Promise<void> {
|
|
162
|
+
await call("editMessageText", {
|
|
163
|
+
chat_id: chatId,
|
|
164
|
+
message_id: messageId,
|
|
165
|
+
rich_message: { markdown },
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Stream a partial Rich Message as an ephemeral ~30s draft; updates sharing a
|
|
170
|
+
* `draftId` animate. Unclosed markers in a mid-stream snapshot render
|
|
171
|
+
* best-effort (the parser treats them as invalid data, never errors), so no
|
|
172
|
+
* auto-closing is needed. */
|
|
173
|
+
async function sendDraft(chatId: number, draftId: number, markdown: string): Promise<void> {
|
|
174
|
+
await call("sendRichMessageDraft", {
|
|
175
|
+
chat_id: chatId,
|
|
176
|
+
draft_id: draftId,
|
|
177
|
+
rich_message: { markdown },
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Clear a live draft (best-effort) before committing the real message.
|
|
182
|
+
* Drafts expire on Telegram's side anyway, so failures are ignored. */
|
|
183
|
+
async function clearDraft(chatId: number, draftId: number): Promise<void> {
|
|
184
|
+
try {
|
|
185
|
+
await call("sendRichMessageDraft", {
|
|
186
|
+
chat_id: chatId,
|
|
187
|
+
draft_id: draftId,
|
|
188
|
+
rich_message: { markdown: "" },
|
|
189
|
+
});
|
|
190
|
+
} catch {
|
|
191
|
+
// best-effort; drafts expire on Telegram's side
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Upload a local file as photo (if recognised image mime) or generic document. */
|
|
196
|
+
async function sendAttachment(chatId: number, filePath: string, fileName: string): Promise<TelegramSentMessage> {
|
|
197
|
+
const mediaType = guessMediaType(filePath);
|
|
198
|
+
const method = mediaType ? "sendPhoto" : "sendDocument";
|
|
199
|
+
const fieldName = mediaType ? "photo" : "document";
|
|
200
|
+
return await callMultipart<TelegramSentMessage>(method, { chat_id: String(chatId) }, fieldName, filePath, fileName);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return { call, download, sendText, editText, sendDraft, clearDraft, sendAttachment };
|
|
204
|
+
}
|
package/src/chunk.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Pure helpers to split a growing markdown answer into messages under the
|
|
2
|
+
// per-message limit. The only block that breaks when split is a fenced code
|
|
3
|
+
// block, so we prefer to cut at a fence-depth-0 boundary (nextBoundary) and
|
|
4
|
+
// render each piece with the fence context it starts/ends in (renderChunk) —
|
|
5
|
+
// reopening a carried-over fence and closing a dangling one. At a clean boundary
|
|
6
|
+
// there's none, so a normal split and a forced mid-fence split share one path.
|
|
7
|
+
|
|
8
|
+
/** A fenced code block's opener — enough to re-open it in a continuation. */
|
|
9
|
+
interface OpenFence {
|
|
10
|
+
marker: string;
|
|
11
|
+
info: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// ≤3-space-indented run of ≥3 backticks/tildes, then the info string.
|
|
15
|
+
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
16
|
+
|
|
17
|
+
/** Walk `text` line by line tracking fenced-code state, invoking `onLine` with
|
|
18
|
+
* the fence state *before* each line. Returns the fence still open at the end,
|
|
19
|
+
* or null. A closer needs the same char, length ≥ the opener, nothing after. */
|
|
20
|
+
function scanLines(
|
|
21
|
+
text: string,
|
|
22
|
+
onLine?: (lineStart: number, insideFence: boolean, line: string) => void,
|
|
23
|
+
): OpenFence | null {
|
|
24
|
+
let open: OpenFence | null = null;
|
|
25
|
+
let pos = 0;
|
|
26
|
+
for (;;) {
|
|
27
|
+
const nl = text.indexOf("\n", pos);
|
|
28
|
+
const end = nl === -1 ? text.length : nl;
|
|
29
|
+
const line = text.slice(pos, end);
|
|
30
|
+
onLine?.(pos, open !== null, line);
|
|
31
|
+
const m = FENCE_RE.exec(line);
|
|
32
|
+
const marker = m?.[1];
|
|
33
|
+
const info = m?.[2];
|
|
34
|
+
if (marker !== undefined && info !== undefined) {
|
|
35
|
+
if (!open) {
|
|
36
|
+
// A backtick fence's info string may not contain a backtick.
|
|
37
|
+
if (marker[0] === "~" || !info.includes("`")) open = { marker, info: info.trim() };
|
|
38
|
+
} else if (marker[0] === open.marker[0] && marker.length >= open.marker.length && info.trim() === "") {
|
|
39
|
+
open = null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (nl === -1) return open;
|
|
43
|
+
pos = nl + 1;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The fenced code block still open at the end of `text`, or null. */
|
|
48
|
+
function openFenceAt(text: string): OpenFence | null {
|
|
49
|
+
return scanLines(text);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Where to cut a chunk starting at `from`: the latest fence-depth-0 boundary
|
|
53
|
+
* at or before `from + maxLen` (paragraph > line), else a word break, else a
|
|
54
|
+
* hard cut. Always returns an offset greater than `from`. */
|
|
55
|
+
export function nextBoundary(text: string, from: number, maxLen: number): number {
|
|
56
|
+
const limit = Math.min(text.length, from + maxLen);
|
|
57
|
+
let lastLine = -1;
|
|
58
|
+
let lastPara = -1;
|
|
59
|
+
let prevBlank = false;
|
|
60
|
+
scanLines(text, (lineStart, insideFence, line) => {
|
|
61
|
+
if (lineStart > from && lineStart <= limit && !insideFence) {
|
|
62
|
+
lastLine = lineStart;
|
|
63
|
+
if (prevBlank) lastPara = lineStart;
|
|
64
|
+
}
|
|
65
|
+
prevBlank = line.trim() === "";
|
|
66
|
+
});
|
|
67
|
+
if (lastPara > from) return lastPara;
|
|
68
|
+
if (lastLine > from) return lastLine;
|
|
69
|
+
const space = text.lastIndexOf(" ", limit);
|
|
70
|
+
return space > from ? space + 1 : limit;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Wrap a raw slice into self-contained markdown: reopen `openStart` and close
|
|
74
|
+
* `openEnd`. Both null at a clean boundary, so the slice passes through. */
|
|
75
|
+
function renderSegment(raw: string, openStart: OpenFence | null, openEnd: OpenFence | null): string {
|
|
76
|
+
const pre = openStart ? `${openStart.marker}${openStart.info}\n` : "";
|
|
77
|
+
const suf = openEnd ? `${raw.endsWith("\n") ? "" : "\n"}${openEnd.marker}` : "";
|
|
78
|
+
return pre + raw + suf;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Render `text[from, to)` as a standalone message, reopening a code fence
|
|
82
|
+
* carried over from before `from` and closing one left open at `to`. At a
|
|
83
|
+
* clean boundary it's just the slice. */
|
|
84
|
+
export function renderChunk(text: string, from: number, to: number): string {
|
|
85
|
+
return renderSegment(text.slice(from, to), openFenceAt(text.slice(0, from)), openFenceAt(text.slice(0, to)));
|
|
86
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Loads telegram.json at construction, persists on update.
|
|
2
|
+
|
|
3
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
|
|
7
|
+
interface TelegramConfig {
|
|
8
|
+
apiRoot?: string;
|
|
9
|
+
botToken?: string;
|
|
10
|
+
allowedUserId?: number;
|
|
11
|
+
lastUpdateId?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const CONFIG_PATH = join(homedir(), ".pi", "agent", "telegram.json");
|
|
15
|
+
|
|
16
|
+
async function readConfig(): Promise<TelegramConfig> {
|
|
17
|
+
try {
|
|
18
|
+
const content = await readFile(CONFIG_PATH, "utf8");
|
|
19
|
+
return JSON.parse(content) as TelegramConfig;
|
|
20
|
+
} catch {
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function writeConfig(config: TelegramConfig): Promise<void> {
|
|
26
|
+
await mkdir(join(homedir(), ".pi", "agent"), { recursive: true });
|
|
27
|
+
await writeFile(CONFIG_PATH, `${JSON.stringify(config, null, "\t")}\n`, "utf8");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function validateConfig(config: TelegramConfig): void {
|
|
31
|
+
if (!config.botToken) {
|
|
32
|
+
throw new Error(
|
|
33
|
+
`Telegram bridge: ${CONFIG_PATH} missing "botToken". ` +
|
|
34
|
+
`Create the file with {"botToken": "<bot-token-from-BotFather>"} and restart. ` +
|
|
35
|
+
`Optionally set "allowedUserId" too — if omitted, the bot will report your user id when you first message it.`,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type ConfigManager = {
|
|
41
|
+
get(): TelegramConfig;
|
|
42
|
+
update(patch: Partial<TelegramConfig>): Promise<void>;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export async function createConfig(): Promise<ConfigManager> {
|
|
46
|
+
let config = await readConfig();
|
|
47
|
+
validateConfig(config);
|
|
48
|
+
return {
|
|
49
|
+
get: () => config,
|
|
50
|
+
update: async (patch) => {
|
|
51
|
+
config = { ...config, ...patch };
|
|
52
|
+
await writeConfig(config);
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|