@qusic/pi-telegram 0.2.0 → 0.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.
package/README.md CHANGED
@@ -13,7 +13,7 @@ A Telegram DM bridge for [pi](https://pi.dev) — chat with your pi coding agent
13
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
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
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
16
+ - **Attachments out**: ask for a file and the agent sends it with an `attach` tool
17
17
  - **Tool call breadcrumbs**: grouped progress that updates as tools run
18
18
  - **Mid-turn steering**: messages sent while the agent is busy are injected into the running turn
19
19
  - **Typing indicator** while the agent is working
@@ -23,34 +23,35 @@ A Telegram DM bridge for [pi](https://pi.dev) — chat with your pi coding agent
23
23
 
24
24
  Auto-published as the bot menu at boot. Anything else is forwarded to pi as a user turn.
25
25
 
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 |
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 |
34
34
 
35
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).
36
36
 
37
37
  ## Differences vs. upstream `badlogic/pi-telegram`
38
38
 
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 sender id is shown as a warning in pi; unauthorized senders receive no response |
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 |
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 sender id is shown as a warning in pi; unauthorized senders receive no response |
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
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 | Grouped progress that updates as tools run |
50
- | Thinking blocks | Stripped | Streamed, separated by 💭 / ✏️ markers |
51
- | Status bar | Rich colored status | Only transient polling errors |
49
+ | Tool call breadcrumbs | None | Grouped progress that updates as tools run |
50
+ | Thinking blocks | Stripped | Streamed, separated by 💭 / ✏️ markers |
51
+ | Status bar | Rich colored status | Only transient polling errors |
52
+ | Outgoing files | `telegram_attach`, prompted for `[telegram]` messages; files wait for the reply | `attach`, used when you ask; files are sent immediately, even from the TUI |
52
53
 
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.
54
+ Media-group debouncing matches upstream. Internally the fork is split into small manager closures instead of a single file.
54
55
 
55
56
  ## Install
56
57
 
@@ -80,7 +81,7 @@ pi -e git:github.com/Qusic/pi-telegram
80
81
 
81
82
  ## Usage
82
83
 
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
+ 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 to send you a file and it calls `attach`; `/stop` aborts.
84
85
 
85
86
  ## License
86
87
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qusic/pi-telegram",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Telegram bridge extension for Pi agent",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -48,12 +48,12 @@
48
48
  "typebox": "*"
49
49
  },
50
50
  "devDependencies": {
51
- "@biomejs/biome": "^2.5.15",
52
- "@earendil-works/pi-agent-core": "1.0.4",
53
- "@earendil-works/pi-ai": "1.0.4",
54
- "@earendil-works/pi-coding-agent": "1.0.4",
55
- "@types/node": "^24.19.1",
56
- "npm": "^11.21.0",
51
+ "@biomejs/biome": "^2.6.8",
52
+ "@earendil-works/pi-agent-core": "1.5.2",
53
+ "@earendil-works/pi-ai": "1.5.2",
54
+ "@earendil-works/pi-coding-agent": "1.5.2",
55
+ "@types/node": "^24.19.2",
56
+ "npm": "^11.21.2",
57
57
  "semantic-release": "^25.0.9",
58
58
  "typebox": "1.3.27",
59
59
  "typescript": "^7.0.2"
package/src/api.ts CHANGED
@@ -1,13 +1,11 @@
1
1
  // Telegram Bot API HTTP client.
2
2
 
3
- import { mkdir, readFile, writeFile } from "node:fs/promises";
4
- import { homedir } from "node:os";
5
- import { join } from "node:path";
3
+ import { mkdtemp, readFile, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, join, sep } from "node:path";
6
6
  import type { createConfig } from "./config.ts";
7
7
  import { guessMediaType, sanitizeFileName } from "./utils.ts";
8
8
 
9
- const TEMP_DIR = join(homedir(), ".pi", "agent", "tmp", "telegram");
10
-
11
9
  /** Telegram's per-message character budget. */
12
10
  export const MAX_MESSAGE_LENGTH = 32768;
13
11
 
@@ -49,6 +47,11 @@ interface TelegramSentMessage {
49
47
  message_id: number;
50
48
  }
51
49
 
50
+ /** An absent signal may be passed as `undefined`, e.g. straight from a tool's execute(). */
51
+ interface CallOptions {
52
+ signal?: AbortSignal | undefined;
53
+ }
54
+
52
55
  export function createApi(config: Awaited<ReturnType<typeof createConfig>>) {
53
56
  const { apiRoot: configuredApiRoot, botToken } = config.get();
54
57
  const apiRoot = (configuredApiRoot || "https://api.telegram.org").replace(/\/+$/, "");
@@ -67,7 +70,7 @@ export function createApi(config: Awaited<ReturnType<typeof createConfig>>) {
67
70
  async function call<T>(
68
71
  method: string,
69
72
  body: Record<string, unknown> | (() => Promise<Response>),
70
- opts?: { signal?: AbortSignal },
73
+ opts?: CallOptions,
71
74
  ): Promise<T> {
72
75
  const signal = opts?.signal;
73
76
  const makeRequest =
@@ -114,8 +117,7 @@ export function createApi(config: Awaited<ReturnType<typeof createConfig>>) {
114
117
  fields: Record<string, string>,
115
118
  fileField: string,
116
119
  filePath: string,
117
- fileName: string,
118
- opts?: { signal?: AbortSignal },
120
+ opts?: CallOptions,
119
121
  ): Promise<T> {
120
122
  // Read once; rebuild the FormData per attempt (a consumed body can't be reused).
121
123
  const blob = new Blob([await readFile(filePath)]);
@@ -124,7 +126,7 @@ export function createApi(config: Awaited<ReturnType<typeof createConfig>>) {
124
126
  () => {
125
127
  const form = new FormData();
126
128
  for (const [key, value] of Object.entries(fields)) form.set(key, value);
127
- form.set(fileField, blob, fileName);
129
+ form.set(fileField, blob, basename(filePath));
128
130
  return fetch(baseUrl + method, { method: "POST", body: form, signal: opts?.signal ?? null });
129
131
  },
130
132
  opts,
@@ -133,12 +135,11 @@ export function createApi(config: Awaited<ReturnType<typeof createConfig>>) {
133
135
 
134
136
  async function download(fileId: string, suggestedName: string): Promise<string> {
135
137
  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
138
  const response = await fetch(fileBaseUrl + file.file_path);
139
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));
140
+ // A private directory per file keeps the name as sent, without collisions.
141
+ const targetPath = join(await mkdtemp(`${tmpdir()}${sep}`), sanitizeFileName(suggestedName));
142
+ await writeFile(targetPath, Buffer.from(await response.arrayBuffer()));
142
143
  return targetPath;
143
144
  }
144
145
 
@@ -193,11 +194,11 @@ export function createApi(config: Awaited<ReturnType<typeof createConfig>>) {
193
194
  }
194
195
 
195
196
  /** 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
+ async function sendAttachment(chatId: number, filePath: string, opts?: CallOptions): Promise<TelegramSentMessage> {
197
198
  const mediaType = guessMediaType(filePath);
198
199
  const method = mediaType ? "sendPhoto" : "sendDocument";
199
200
  const fieldName = mediaType ? "photo" : "document";
200
- return await callMultipart<TelegramSentMessage>(method, { chat_id: String(chatId) }, fieldName, filePath, fileName);
201
+ return await callMultipart<TelegramSentMessage>(method, { chat_id: String(chatId) }, fieldName, filePath, opts);
201
202
  }
202
203
 
203
204
  return { call, download, sendText, editText, sendDraft, clearDraft, sendAttachment };
package/src/attach.ts ADDED
@@ -0,0 +1,38 @@
1
+ // The attach tool: sends a local file to the authorized user's DM (a DM's chat
2
+ // id is the user id) as soon as it is called, from Telegram or the TUI alike.
3
+
4
+ import { resolve } from "node:path";
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { Type } from "typebox";
7
+ import type { createApi } from "./api.ts";
8
+ import type { createConfig } from "./config.ts";
9
+
10
+ interface AttachDeps {
11
+ pi: ExtensionAPI;
12
+ api: ReturnType<typeof createApi>;
13
+ config: Awaited<ReturnType<typeof createConfig>>;
14
+ }
15
+
16
+ export function createAttach(deps: AttachDeps): void {
17
+ const { pi, api, config } = deps;
18
+ // Config is read once per load: without an authorized user, never offer it.
19
+ const chatId = config.get().allowedUserId;
20
+ if (chatId === undefined) return;
21
+
22
+ pi.registerTool({
23
+ name: "attach",
24
+ label: "Attach",
25
+ description: "Send a local file to the user as an attachment.",
26
+ promptSnippet: "Send a local file to the user as an attachment",
27
+ parameters: Type.Object({
28
+ path: Type.String({ description: "Local file path" }),
29
+ }),
30
+ // One file per call; several calls run in order so files arrive as listed.
31
+ executionMode: "sequential",
32
+ async execute(_toolCallId, { path }, signal, _onUpdate, ctx) {
33
+ // Like the built-in tools: drop a leading "@" and resolve against the session cwd.
34
+ await api.sendAttachment(chatId, resolve(ctx.cwd, path.replace(/^@/, "")), { signal });
35
+ return { content: [{ type: "text", text: "Sent the file to the user." }], details: undefined };
36
+ },
37
+ });
38
+ }
package/src/dispatch.ts CHANGED
@@ -15,6 +15,7 @@ import type {
15
15
  } from "@earendil-works/pi-coding-agent";
16
16
  import { SessionManager } from "@earendil-works/pi-coding-agent";
17
17
  import { type createApi, MAX_MESSAGE_LENGTH } from "./api.ts";
18
+ import { buildPrompt } from "./prompt.ts";
18
19
  import type { createTurn } from "./turn.ts";
19
20
  import type { TelegramMessage } from "./types.ts";
20
21
  import { formatTokens, lastAssistantText } from "./utils.ts";
@@ -177,8 +178,17 @@ export function createDispatcher(deps: DispatcherDeps): Dispatcher {
177
178
  return;
178
179
  }
179
180
 
180
- // Default: forward as a regular agent turn.
181
- await turn.handleIncoming(messages, ctx);
181
+ // Extension commands may open dialogs only the TUI can answer, and the bridge
182
+ // cannot tell whether they start a run, so they stay in pi itself.
183
+ const command = rawText.match(/^\/\S+/)?.[0];
184
+ if (command && pi.getCommands().some((cmd) => cmd.source === "extension" && `/${cmd.name}` === command)) {
185
+ await reply(`${code(command)} is a pi command; run it in pi itself.`);
186
+ return;
187
+ }
188
+
189
+ // Default: forward as a regular agent turn. A location, contact etc. has nothing to forward.
190
+ const prompt = await buildPrompt(api, messages);
191
+ if (prompt.length > 0) turn.submit(firstMessage.chat.id, prompt, ctx);
182
192
  };
183
193
  }
184
194
 
package/src/index.ts CHANGED
@@ -2,19 +2,17 @@
2
2
 
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { createApi } from "./api.ts";
5
+ import { createAttach } from "./attach.ts";
5
6
  import { createConfig } from "./config.ts";
6
7
  import { createDispatcher } from "./dispatch.ts";
7
- import { createMedia } from "./media.ts";
8
8
  import { createPolling } from "./polling.ts";
9
- import { createPreview } from "./preview.ts";
10
9
  import { createTurn } from "./turn.ts";
11
10
 
12
11
  export default async function (pi: ExtensionAPI) {
13
12
  const config = await createConfig();
14
13
  const api = createApi(config);
15
- const preview = createPreview(api);
16
- const media = createMedia(api);
17
- const turn = createTurn({ pi, api, media, preview });
14
+ const turn = createTurn({ pi, api });
18
15
  const dispatch = createDispatcher({ pi, api, turn });
19
16
  createPolling({ pi, api, config, dispatch });
17
+ createAttach({ pi, api, config });
20
18
  }
package/src/preview.ts CHANGED
@@ -35,8 +35,6 @@ interface TelegramPreviewState {
35
35
  publishedChars: number;
36
36
  /** Last text pushed to the live draft (dedup guard). */
37
37
  lastSentText: string;
38
- /** True once anything has been committed as a real message. */
39
- published: boolean;
40
38
  draftId: number | undefined;
41
39
  flushTimer: ReturnType<typeof setTimeout> | undefined;
42
40
  }
@@ -78,7 +76,6 @@ export function createPreview(api: PreviewApi) {
78
76
  await clearDraft(c);
79
77
  await api.sendText(c.chatId, head, { silent: true });
80
78
  c.publishedChars = to;
81
- c.published = true;
82
79
  c.lastSentText = "";
83
80
  }
84
81
  }
@@ -91,7 +88,6 @@ export function createPreview(api: PreviewApi) {
91
88
  fullText,
92
89
  publishedChars: 0,
93
90
  lastSentText: "",
94
- published: false,
95
91
  draftId: undefined,
96
92
  flushTimer: undefined,
97
93
  };
@@ -118,23 +114,20 @@ export function createPreview(api: PreviewApi) {
118
114
  c.lastSentText = draft;
119
115
  }
120
116
 
121
- async function finalizeState(c: TelegramPreviewState, final: boolean): Promise<boolean> {
117
+ async function finalizeState(c: TelegramPreviewState, final: boolean): Promise<void> {
122
118
  await promoteOversized(c);
123
119
  const text = renderPending(c, c.fullText.length);
124
120
  await clearDraft(c);
125
- if (!text) return c.published;
121
+ if (!text) return;
126
122
  await api.sendText(c.chatId, text, { silent: !final });
127
123
  c.publishedChars = c.fullText.length;
128
- c.published = true;
129
- return true;
130
124
  }
131
125
 
132
126
  /** Publish any buffered text and reset. Commits are silent unless `final` is
133
- * true for a normal final answer. Returns true iff anything was committed
134
- * as a real message over the preview's lifetime. Never rejects. */
135
- function finalize(final = false): Promise<boolean> {
127
+ * true for a normal final answer. Never rejects. */
128
+ function finalize(final = false): Promise<void> {
136
129
  const c = current;
137
- if (!c) return Promise.resolve(false);
130
+ if (!c) return Promise.resolve();
138
131
  if (c.flushTimer) {
139
132
  clearTimeout(c.flushTimer);
140
133
  c.flushTimer = undefined;
@@ -142,7 +135,7 @@ export function createPreview(api: PreviewApi) {
142
135
  // Detach synchronously so any queued flush for this state no-ops and a
143
136
  // subsequent assistant message starts a fresh preview.
144
137
  current = undefined;
145
- return enqueue(() => finalizeState(c, final)).catch(() => c.published);
138
+ return enqueue(() => finalizeState(c, final)).catch(() => {});
146
139
  }
147
140
 
148
141
  return { update, finalize };
package/src/prompt.ts ADDED
@@ -0,0 +1,124 @@
1
+ // Turn incoming Telegram messages into pi prompt content: their text, plus
2
+ // downloaded attachments referenced by local path (images also inlined).
3
+
4
+ import { readFile } from "node:fs/promises";
5
+ import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
6
+ import type { createApi } from "./api.ts";
7
+ import type { TelegramMessage } from "./types.ts";
8
+ import { guessExtensionFromMime, guessMediaType, isImageMimeType } from "./utils.ts";
9
+
10
+ type PromptApi = Pick<ReturnType<typeof createApi>, "download">;
11
+
12
+ interface TelegramFileInfo {
13
+ file_id: string;
14
+ fileName: string;
15
+ mimeType: string | undefined;
16
+ isImage: boolean;
17
+ }
18
+
19
+ interface DownloadedTelegramFile {
20
+ path: string;
21
+ isImage: boolean;
22
+ mimeType: string | undefined;
23
+ }
24
+
25
+ function collectFileInfos(messages: TelegramMessage[]): TelegramFileInfo[] {
26
+ const files: TelegramFileInfo[] = [];
27
+ for (const m of messages) {
28
+ if (Array.isArray(m.photo) && m.photo.length > 0) {
29
+ const photo = [...m.photo].sort((a, b) => (a.file_size ?? 0) - (b.file_size ?? 0)).pop();
30
+ if (photo)
31
+ files.push({
32
+ file_id: photo.file_id,
33
+ fileName: `photo-${m.message_id}.jpg`,
34
+ mimeType: "image/jpeg",
35
+ isImage: true,
36
+ });
37
+ }
38
+ if (m.document)
39
+ files.push({
40
+ file_id: m.document.file_id,
41
+ fileName: m.document.file_name || `document-${m.message_id}${guessExtensionFromMime(m.document.mime_type, "")}`,
42
+ mimeType: m.document.mime_type,
43
+ isImage: isImageMimeType(m.document.mime_type),
44
+ });
45
+ if (m.video)
46
+ files.push({
47
+ file_id: m.video.file_id,
48
+ fileName: m.video.file_name || `video-${m.message_id}${guessExtensionFromMime(m.video.mime_type, ".mp4")}`,
49
+ mimeType: m.video.mime_type,
50
+ isImage: false,
51
+ });
52
+ if (m.audio)
53
+ files.push({
54
+ file_id: m.audio.file_id,
55
+ fileName: m.audio.file_name || `audio-${m.message_id}${guessExtensionFromMime(m.audio.mime_type, ".mp3")}`,
56
+ mimeType: m.audio.mime_type,
57
+ isImage: false,
58
+ });
59
+ if (m.voice)
60
+ files.push({
61
+ file_id: m.voice.file_id,
62
+ fileName: `voice-${m.message_id}${guessExtensionFromMime(m.voice.mime_type, ".ogg")}`,
63
+ mimeType: m.voice.mime_type,
64
+ isImage: false,
65
+ });
66
+ if (m.animation)
67
+ files.push({
68
+ file_id: m.animation.file_id,
69
+ fileName:
70
+ m.animation.file_name || `animation-${m.message_id}${guessExtensionFromMime(m.animation.mime_type, ".mp4")}`,
71
+ mimeType: m.animation.mime_type,
72
+ isImage: false,
73
+ });
74
+ if (m.sticker)
75
+ files.push({
76
+ file_id: m.sticker.file_id,
77
+ fileName: `sticker-${m.message_id}.webp`,
78
+ mimeType: "image/webp",
79
+ isImage: true,
80
+ });
81
+ }
82
+ return files;
83
+ }
84
+
85
+ async function downloadFiles(api: PromptApi, messages: TelegramMessage[]): Promise<DownloadedTelegramFile[]> {
86
+ const downloaded: DownloadedTelegramFile[] = [];
87
+ for (const file of collectFileInfos(messages)) {
88
+ const path = await api.download(file.file_id, file.fileName);
89
+ downloaded.push({ path, isImage: file.isImage, mimeType: file.mimeType });
90
+ }
91
+ return downloaded;
92
+ }
93
+
94
+ /** Build the prompt for a batch of messages (an album arrives as several):
95
+ * text + attachment paths + inline images. */
96
+ export async function buildPrompt(
97
+ api: PromptApi,
98
+ messages: TelegramMessage[],
99
+ ): Promise<Array<TextContent | ImageContent>> {
100
+ const rawText = messages
101
+ .map((m) => (m.text || m.caption || "").trim())
102
+ .filter(Boolean)
103
+ .join("\n\n");
104
+ const files = await downloadFiles(api, messages);
105
+ const content: Array<TextContent | ImageContent> = [];
106
+
107
+ let prompt = rawText;
108
+ if (files.length > 0) {
109
+ if (prompt) prompt += "\n\n";
110
+ prompt += "Attachments saved locally:";
111
+ for (const file of files) prompt += `\n- ${file.path}`;
112
+ }
113
+ if (prompt) content.push({ type: "text", text: prompt });
114
+
115
+ for (const file of files) {
116
+ if (!file.isImage) continue;
117
+ const mediaType = file.mimeType || guessMediaType(file.path);
118
+ if (!mediaType) continue;
119
+ const buffer = await readFile(file.path);
120
+ content.push({ type: "image", data: buffer.toString("base64"), mimeType: mediaType });
121
+ }
122
+
123
+ return content;
124
+ }
package/src/toolcall.ts CHANGED
@@ -4,8 +4,11 @@
4
4
  import { type createApi, MAX_MESSAGE_LENGTH } from "./api.ts";
5
5
 
6
6
  const EDIT_THROTTLE_MS = 500;
7
- const NAME_MAX = 64;
8
- const SUMMARY_MAX = 96;
7
+ // Heuristic for a compact mobile row; actual wrap depends on chat width and font.
8
+ const NAME_MAX = 24;
9
+ const SUMMARY_MAX = 24;
10
+ // A bare newline is a soft break in GFM and can render as a space.
11
+ const TOOL_LINE_BREAK = " \n";
9
12
 
10
13
  const STATUS_ICON = {
11
14
  running: "🔧",
@@ -96,10 +99,6 @@ function summarizeArgs(toolName: string, args: unknown): string {
96
99
  case "grep":
97
100
  case "find":
98
101
  return typeof fields.pattern === "string" ? shortenStart(oneLine(fields.pattern), SUMMARY_MAX) : "";
99
- case "telegram_attach": {
100
- const paths = fields.paths;
101
- return Array.isArray(paths) ? `${paths.length} file${paths.length === 1 ? "" : "s"}` : "";
102
- }
103
102
  default:
104
103
  // Unknown schemas may contain bulk or sensitive fields; show only the name.
105
104
  return "";
@@ -121,7 +120,7 @@ export function createToolMessages(api: ToolApi) {
121
120
 
122
121
  async function flush(batch: ToolBatch): Promise<void> {
123
122
  for (const page of batch.pages) {
124
- const text = page.lines.map(renderLine).join("\n");
123
+ const text = page.lines.map(renderLine).join(TOOL_LINE_BREAK);
125
124
  if (text === page.lastText) continue;
126
125
  try {
127
126
  if (page.messageId === undefined) {
@@ -163,9 +162,9 @@ export function createToolMessages(api: ToolApi) {
163
162
  status: "running",
164
163
  };
165
164
  batch.calls.set(call.toolCallId, line);
166
- // Running and cancelled icons have the same length; reserve a newline
165
+ // Running and cancelled icons have the same length; reserve a break
167
166
  // so status edits never move a line between pages.
168
- const budget = renderLine(line).length + 1;
167
+ const budget = renderLine(line).length + TOOL_LINE_BREAK.length;
169
168
  let page = batch.pages.at(-1);
170
169
  if (!page || page.budget + budget > MAX_MESSAGE_LENGTH) {
171
170
  page = { lines: [], budget: 0, messageId: undefined, lastText: "" };
package/src/turn.ts CHANGED
@@ -1,30 +1,25 @@
1
- // Turn lifecycle + pi event handlers (agent_*, message_*, tool_*). Registers
2
- // the telegram_attach tool. Media handling lives in media.ts.
1
+ // Turn lifecycle + pi event handlers (agent_*, message_*, tool_*): runs a
2
+ // prompt built from Telegram messages (prompt.ts) and mirrors pi's output back
3
+ // to the chat.
3
4
  //
4
5
  // A Telegram request can span multiple pi turns and retries: turn_end closes
5
6
  // each tool batch, while agent_settled closes the Telegram request.
6
7
  // Concurrency: no local queue. Idle → stash as `pending`, sendUserMessage,
7
8
  // agent_start promotes to `active`. Busy → sendUserMessage with
8
- // deliverAs:"steer" to inject into the running turn.
9
+ // deliverAs:"steer" to inject into the running turn, adopting it if Telegram
10
+ // did not start it (e.g. a TUI prompt). Known gap: if another extension's
11
+ // input handler swallows the message, no run starts and `pending` waits for
12
+ // the next one.
9
13
 
10
- import { stat } from "node:fs/promises";
11
- import { basename } from "node:path";
12
14
  import type { AssistantMessage, ImageContent, TextContent } from "@earendil-works/pi-ai";
13
15
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
14
- import { Type } from "typebox";
15
16
  import type { createApi } from "./api.ts";
16
- import type { createMedia, QueuedAttachment } from "./media.ts";
17
- import type { createPreview } from "./preview.ts";
17
+ import { createPreview } from "./preview.ts";
18
18
  import { createToolMessages } from "./toolcall.ts";
19
- import type { TelegramMessage } from "./types.ts";
20
19
  import { getMessageText, isAssistantMessage } from "./utils.ts";
21
20
 
22
- const MAX_ATTACHMENTS_PER_TURN = 10;
23
-
24
21
  interface TelegramTurn {
25
22
  chatId: number;
26
- queuedAttachments: QueuedAttachment[];
27
- content: Array<TextContent | ImageContent>;
28
23
  lastResponse?: { stopReason: AssistantMessage["stopReason"]; errorMessage: string | undefined };
29
24
  abortRequested?: boolean;
30
25
  }
@@ -32,12 +27,11 @@ interface TelegramTurn {
32
27
  interface TurnDeps {
33
28
  pi: ExtensionAPI;
34
29
  api: ReturnType<typeof createApi>;
35
- media: ReturnType<typeof createMedia>;
36
- preview: ReturnType<typeof createPreview>;
37
30
  }
38
31
 
39
32
  export function createTurn(deps: TurnDeps) {
40
- const { pi, api, media, preview } = deps;
33
+ const { pi, api } = deps;
34
+ const preview = createPreview(api);
41
35
  const toolMessages = createToolMessages(api);
42
36
 
43
37
  let pending: TelegramTurn | undefined;
@@ -66,52 +60,8 @@ export function createTurn(deps: TurnDeps) {
66
60
  typingInterval = undefined;
67
61
  }
68
62
 
69
- async function build(messages: TelegramMessage[]): Promise<TelegramTurn> {
70
- const firstMessage = messages[0];
71
- if (!firstMessage) throw new Error("Missing Telegram message for turn creation");
72
- const content = await media.buildPromptContent(messages);
73
- return {
74
- chatId: firstMessage.chat.id,
75
- queuedAttachments: [],
76
- content,
77
- };
78
- }
79
-
80
63
  // ---------- pi handler registration ----------
81
64
 
82
- pi.registerTool({
83
- name: "telegram_attach",
84
- label: "Telegram Attach",
85
- description: "Queue one or more local files to be sent with the next Telegram reply.",
86
- promptSnippet: "Queue local files to be sent with the next Telegram reply.",
87
- promptGuidelines: [
88
- "To send a file or generated artifact back to the user, call telegram_attach with its local path. Mentioning the path in plain text alone will not deliver the file.",
89
- ],
90
- parameters: Type.Object({
91
- paths: Type.Array(Type.String({ description: "Local file path to attach" }), {
92
- minItems: 1,
93
- maxItems: MAX_ATTACHMENTS_PER_TURN,
94
- }),
95
- }),
96
- async execute(_toolCallId, params) {
97
- if (!active) throw new Error("telegram_attach can only be used while replying to an active Telegram turn");
98
- const added: string[] = [];
99
- for (const inputPath of params.paths) {
100
- const stats = await stat(inputPath);
101
- if (!stats.isFile()) throw new Error(`Not a file: ${inputPath}`);
102
- if (active.queuedAttachments.length >= MAX_ATTACHMENTS_PER_TURN) {
103
- throw new Error(`Attachment limit reached (${MAX_ATTACHMENTS_PER_TURN})`);
104
- }
105
- active.queuedAttachments.push({ path: inputPath, fileName: basename(inputPath) });
106
- added.push(inputPath);
107
- }
108
- return {
109
- content: [{ type: "text", text: `Queued ${added.length} Telegram attachment(s).` }],
110
- details: { paths: added },
111
- };
112
- },
113
- });
114
-
115
65
  pi.on("session_shutdown", async (_event, _ctx) => {
116
66
  await toolMessages.finalize();
117
67
  await preview.finalize();
@@ -174,30 +124,22 @@ export function createTurn(deps: TurnDeps) {
174
124
 
175
125
  const { stopReason, errorMessage } = turn.lastResponse ?? {};
176
126
  const final = !turn.abortRequested && stopReason !== "aborted" && stopReason !== "error";
177
- const sent = await preview.finalize(final);
178
- if (turn.abortRequested || stopReason === "aborted") return;
179
- if (stopReason === "error") {
127
+ await preview.finalize(final);
128
+ if (stopReason === "error" && !turn.abortRequested) {
180
129
  await api.sendText(turn.chatId, errorMessage || "Telegram bridge: pi failed while processing the request.");
181
- return;
182
130
  }
183
- if (!sent && turn.queuedAttachments.length > 0) {
184
- await api.sendText(turn.chatId, "Attached requested file(s).");
185
- }
186
- await media.sendAttachments(turn.chatId, turn.queuedAttachments);
187
131
  });
188
132
 
189
- /** Dispatch a new batch of Telegram messages. Starts a fresh turn (if idle)
133
+ /** Send a prompt from a Telegram chat to pi. Starts a fresh turn (if idle)
190
134
  * or steers into the running one. */
191
- async function handleIncoming(messages: TelegramMessage[], ctx: ExtensionContext): Promise<void> {
192
- const built = await build(messages);
193
- // Pi reports idle before settled handlers finish. A new Telegram message
194
- // in that window belongs to the next run, not the previous run's steering.
195
- const isFresh = !pending && (!active || ctx.isIdle());
196
- if (isFresh) {
197
- pending = built;
198
- startTyping(built.chatId);
199
- }
200
- pi.sendUserMessage(built.content, {
135
+ function submit(chatId: number, prompt: Array<TextContent | ImageContent>, ctx: ExtensionContext): void {
136
+ // Pi reports idle before settled handlers finish, so a message in that
137
+ // window starts the next run rather than steering the settling one.
138
+ const isFresh = !pending && ctx.isIdle();
139
+ if (isFresh) pending = { chatId };
140
+ else if (!pending) active ??= { chatId }; // adopt a run Telegram did not start, e.g. from the TUI
141
+ startTyping(chatId);
142
+ pi.sendUserMessage(prompt, {
201
143
  expandPromptTemplates: true,
202
144
  ...(isFresh ? {} : { deliverAs: "steer" }),
203
145
  });
@@ -213,5 +155,5 @@ export function createTurn(deps: TurnDeps) {
213
155
  return false;
214
156
  }
215
157
 
216
- return { handleIncoming, abort };
158
+ return { submit, abort };
217
159
  }
package/src/utils.ts CHANGED
@@ -5,8 +5,10 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
5
5
  import type { AssistantMessage } from "@earendil-works/pi-ai";
6
6
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
7
7
 
8
+ /** Make a file name safe as a single path segment on any OS, keeping other
9
+ * characters (e.g. CJK) so the name stays readable. */
8
10
  export function sanitizeFileName(name: string): string {
9
- return name.replace(/[^a-zA-Z0-9._-]+/g, "_");
11
+ return name.replace(/[\p{Cc}<>:"/\\|?*]+/gu, "_");
10
12
  }
11
13
 
12
14
  export function guessExtensionFromMime(mimeType: string | undefined, fallback: string): string {
@@ -62,8 +64,10 @@ export function getMessageText(message: AssistantMessage): string {
62
64
  let prevType: "text" | "thinking" = "text";
63
65
  for (const block of message.content) {
64
66
  if (block.type !== "text" && block.type !== "thinking") continue;
67
+ const content = block.type === "text" ? block.text : block.thinking;
68
+ if (!content.trim()) continue;
65
69
  const marker = block.type === prevType ? "" : SECTION_MARKER[block.type];
66
- parts.push(marker + (block.type === "text" ? block.text : block.thinking));
70
+ parts.push(marker + content);
67
71
  prevType = block.type;
68
72
  }
69
73
  return parts.join("\n\n").trim();
package/src/media.ts DELETED
@@ -1,142 +0,0 @@
1
- // Download incoming attachments, build LLM prompt content from them, and
2
- // send outgoing files queued by the telegram_attach tool.
3
-
4
- import { readFile } from "node:fs/promises";
5
- import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
6
- import type { createApi } from "./api.ts";
7
- import type { TelegramMessage } from "./types.ts";
8
- import { guessExtensionFromMime, guessMediaType, isImageMimeType } from "./utils.ts";
9
-
10
- interface TelegramFileInfo {
11
- file_id: string;
12
- fileName: string;
13
- mimeType: string | undefined;
14
- isImage: boolean;
15
- }
16
-
17
- interface DownloadedTelegramFile {
18
- path: string;
19
- isImage: boolean;
20
- mimeType: string | undefined;
21
- }
22
-
23
- /** Outbound file queued by telegram_attach, sent when the agent settles. */
24
- export interface QueuedAttachment {
25
- path: string;
26
- fileName: string;
27
- }
28
-
29
- export function createMedia(api: ReturnType<typeof createApi>) {
30
- function collectFileInfos(messages: TelegramMessage[]): TelegramFileInfo[] {
31
- const files: TelegramFileInfo[] = [];
32
- for (const m of messages) {
33
- if (Array.isArray(m.photo) && m.photo.length > 0) {
34
- const photo = [...m.photo].sort((a, b) => (a.file_size ?? 0) - (b.file_size ?? 0)).pop();
35
- if (photo)
36
- files.push({
37
- file_id: photo.file_id,
38
- fileName: `photo-${m.message_id}.jpg`,
39
- mimeType: "image/jpeg",
40
- isImage: true,
41
- });
42
- }
43
- if (m.document)
44
- files.push({
45
- file_id: m.document.file_id,
46
- fileName:
47
- m.document.file_name || `document-${m.message_id}${guessExtensionFromMime(m.document.mime_type, "")}`,
48
- mimeType: m.document.mime_type,
49
- isImage: isImageMimeType(m.document.mime_type),
50
- });
51
- if (m.video)
52
- files.push({
53
- file_id: m.video.file_id,
54
- fileName: m.video.file_name || `video-${m.message_id}${guessExtensionFromMime(m.video.mime_type, ".mp4")}`,
55
- mimeType: m.video.mime_type,
56
- isImage: false,
57
- });
58
- if (m.audio)
59
- files.push({
60
- file_id: m.audio.file_id,
61
- fileName: m.audio.file_name || `audio-${m.message_id}${guessExtensionFromMime(m.audio.mime_type, ".mp3")}`,
62
- mimeType: m.audio.mime_type,
63
- isImage: false,
64
- });
65
- if (m.voice)
66
- files.push({
67
- file_id: m.voice.file_id,
68
- fileName: `voice-${m.message_id}${guessExtensionFromMime(m.voice.mime_type, ".ogg")}`,
69
- mimeType: m.voice.mime_type,
70
- isImage: false,
71
- });
72
- if (m.animation)
73
- files.push({
74
- file_id: m.animation.file_id,
75
- fileName:
76
- m.animation.file_name ||
77
- `animation-${m.message_id}${guessExtensionFromMime(m.animation.mime_type, ".mp4")}`,
78
- mimeType: m.animation.mime_type,
79
- isImage: false,
80
- });
81
- if (m.sticker)
82
- files.push({
83
- file_id: m.sticker.file_id,
84
- fileName: `sticker-${m.message_id}.webp`,
85
- mimeType: "image/webp",
86
- isImage: true,
87
- });
88
- }
89
- return files;
90
- }
91
-
92
- async function downloadFiles(messages: TelegramMessage[]): Promise<DownloadedTelegramFile[]> {
93
- const downloaded: DownloadedTelegramFile[] = [];
94
- for (const file of collectFileInfos(messages)) {
95
- const path = await api.download(file.file_id, file.fileName);
96
- downloaded.push({ path, isImage: file.isImage, mimeType: file.mimeType });
97
- }
98
- return downloaded;
99
- }
100
-
101
- /** Build LLM-bound prompt content: text + attachment paths + inline images. */
102
- async function buildPromptContent(messages: TelegramMessage[]): Promise<Array<TextContent | ImageContent>> {
103
- const rawText = messages
104
- .map((m) => (m.text || m.caption || "").trim())
105
- .filter(Boolean)
106
- .join("\n\n");
107
- const files = await downloadFiles(messages);
108
- const content: Array<TextContent | ImageContent> = [];
109
-
110
- let prompt = rawText;
111
- if (files.length > 0) {
112
- if (prompt) prompt += "\n\n";
113
- prompt += "Attachments saved locally:";
114
- for (const file of files) prompt += `\n- ${file.path}`;
115
- }
116
- content.push({ type: "text", text: prompt });
117
-
118
- for (const file of files) {
119
- if (!file.isImage) continue;
120
- const mediaType = file.mimeType || guessMediaType(file.path);
121
- if (!mediaType) continue;
122
- const buffer = await readFile(file.path);
123
- content.push({ type: "image", data: buffer.toString("base64"), mimeType: mediaType });
124
- }
125
-
126
- return content;
127
- }
128
-
129
- /** Send queued outbound files to the chat, with text fallback on failure. */
130
- async function sendAttachments(chatId: number, attachments: QueuedAttachment[]): Promise<void> {
131
- for (const att of attachments) {
132
- try {
133
- await api.sendAttachment(chatId, att.path, att.fileName);
134
- } catch (error) {
135
- const message = error instanceof Error ? error.message : String(error);
136
- await api.sendText(chatId, `Failed to send attachment ${att.fileName}: ${message}`);
137
- }
138
- }
139
- }
140
-
141
- return { buildPromptContent, sendAttachments };
142
- }