@qusic/pi-telegram 0.1.0 → 0.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/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![pi](https://img.shields.io/npm/dependency-version/%40qusic%2Fpi-telegram/dev/%40earendil-works%2Fpi-coding-agent?label=pi)](https://github.com/earendil-works/pi)
6
6
  [![License](https://img.shields.io/npm/l/%40qusic%2Fpi-telegram)](LICENSE)
7
7
 
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.
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 to better fit my personal preferences and needs.
9
9
 
10
10
  ## Features
11
11
 
@@ -14,7 +14,7 @@ A Telegram DM bridge for [pi](https://pi.dev) — chat with your pi coding agent
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
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
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
20
20
  - **Single-user authorization** by Telegram user id
@@ -39,14 +39,14 @@ Resuming a session echoes that session's last reply back to the chat, so it refl
39
39
  | Area | Upstream | This fork |
40
40
  | --------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
41
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 |
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
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
44
  | Concurrency | Extra messages while busy are queued and dispatched after the current turn ends | Extra messages are steered into the running turn |
45
45
  | Aborted-turn replay | After `stop`, queued messages are re-injected as a synthetic history block | No replay — `stop` just aborts |
46
46
  | Prompt prefix | Each message prefixed with `[telegram]`, plus a system-prompt suffix | Forwarded as-is |
47
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 | `🔧 …` Rich Message per tool call: summary line plus collapsible arguments + output, edited with ✅ / ❌ |
49
+ | Tool call breadcrumbs | None | Grouped progress that updates as tools run |
50
50
  | Thinking blocks | Stripped | Streamed, separated by 💭 / ✏️ markers |
51
51
  | Status bar | Rich colored status | Only transient polling errors |
52
52
 
@@ -76,7 +76,7 @@ pi -e git:github.com/Qusic/pi-telegram
76
76
  ```
77
77
 
78
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.
79
+ 4. DM your bot once. pi shows a warning with your Telegram user id; add `"allowedUserId": <id>` to the config and restart. The bot stays silent until authorized.
80
80
 
81
81
  ## Usage
82
82
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qusic/pi-telegram",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Telegram bridge extension for Pi agent",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -48,14 +48,14 @@
48
48
  "typebox": "*"
49
49
  },
50
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",
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",
57
57
  "semantic-release": "^25.0.9",
58
- "typebox": "1.3.7",
58
+ "typebox": "1.3.27",
59
59
  "typescript": "^7.0.2"
60
60
  }
61
61
  }
package/src/config.ts CHANGED
@@ -32,7 +32,7 @@ function validateConfig(config: TelegramConfig): void {
32
32
  throw new Error(
33
33
  `Telegram bridge: ${CONFIG_PATH} missing "botToken". ` +
34
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.`,
35
+ `Optionally set "allowedUserId" too — if omitted, pi will show the sender's user id as a warning when the bot first receives a DM.`,
36
36
  );
37
37
  }
38
38
  }
package/src/index.ts CHANGED
@@ -1,5 +1,4 @@
1
- // Entry point. Pi reloads extensions on every session swap, so each module
2
- // returns a manager closure that owns its own state and event handlers.
1
+ // Pi reloads the extension on session swaps, so these managers are session-scoped.
3
2
 
4
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
4
  import { createApi } from "./api.ts";
package/src/media.ts CHANGED
@@ -20,7 +20,7 @@ interface DownloadedTelegramFile {
20
20
  mimeType: string | undefined;
21
21
  }
22
22
 
23
- /** Outbound file queued by telegram_attach, sent on agent_end. */
23
+ /** Outbound file queued by telegram_attach, sent when the agent settles. */
24
24
  export interface QueuedAttachment {
25
25
  path: string;
26
26
  fileName: string;
package/src/polling.ts CHANGED
@@ -20,6 +20,25 @@ interface TelegramMediaGroupState {
20
20
  flushTimer?: ReturnType<typeof setTimeout>;
21
21
  }
22
22
 
23
+ interface IncomingPrivateMessage {
24
+ message: TelegramMessage;
25
+ userId: number;
26
+ }
27
+
28
+ function getIncomingPrivateMessage(update: TelegramUpdate): IncomingPrivateMessage | undefined {
29
+ const message = update.message ?? update.edited_message;
30
+ if (message?.chat.type !== "private" || !message.from || message.from.is_bot) return undefined;
31
+ return { message, userId: message.from.id };
32
+ }
33
+
34
+ function notifyAuthorizationRequired(ctx: ExtensionContext, userId: number): void {
35
+ ctx.ui.notify(
36
+ `Telegram user id ${userId} needs authorization. ` +
37
+ `Add "allowedUserId": ${userId} to ~/.pi/agent/telegram.json, then restart pi.`,
38
+ "warning",
39
+ );
40
+ }
41
+
23
42
  interface PollingDeps {
24
43
  pi: ExtensionAPI;
25
44
  api: ReturnType<typeof createApi>;
@@ -62,7 +81,15 @@ export function createPolling(deps: PollingDeps): void {
62
81
  { signal },
63
82
  );
64
83
  const last = updates.at(-1);
65
- if (last) await config.update({ lastUpdateId: last.update_id });
84
+ if (last) {
85
+ await config.update({ lastUpdateId: last.update_id });
86
+ // Skip stale work on startup, but still report the authorization id
87
+ // from the latest private message when authorization is unconfigured.
88
+ if (config.get().allowedUserId === undefined) {
89
+ const incoming = getIncomingPrivateMessage(last);
90
+ if (incoming) notifyAuthorizationRequired(ctx, incoming.userId);
91
+ }
92
+ }
66
93
  } catch {
67
94
  // ignore
68
95
  }
@@ -98,25 +125,19 @@ export function createPolling(deps: PollingDeps): void {
98
125
  }
99
126
 
100
127
  async function handleUpdate(update: TelegramUpdate, ctx: ExtensionContext): Promise<void> {
101
- const message = update.message || update.edited_message;
102
- if (message?.chat.type !== "private" || !message.from || message.from.is_bot) return;
128
+ const incoming = getIncomingPrivateMessage(update);
129
+ if (!incoming) return;
130
+ const { message, userId } = incoming;
103
131
 
104
132
  const cfg = config.get();
105
133
  if (cfg.allowedUserId === undefined) {
106
- // Bootstrap: report the user id so the operator can authorize it.
107
- ctx.ui.notify(
108
- `Telegram bridge: received message from user id ${message.from.id}. ` +
109
- `Add "allowedUserId": ${message.from.id} to ~/.pi/agent/telegram.json to authorize, then restart.`,
110
- "warning",
111
- );
112
- await api.sendText(message.chat.id, "Bot not configured: ask the operator to authorize your user id.");
134
+ notifyAuthorizationRequired(ctx, userId);
113
135
  return;
114
136
  }
115
137
 
116
- if (message.from.id !== cfg.allowedUserId) {
117
- await api.sendText(message.chat.id, "This bot is not authorized for your account.");
118
- return;
119
- }
138
+ // Stay silent for unauthorized senders so the bot does not disclose that
139
+ // it is active or invite strangers to keep probing it.
140
+ if (userId !== cfg.allowedUserId) return;
120
141
 
121
142
  // Albums arrive as separate updates with the same media_group_id; debounce.
122
143
  if (message.media_group_id) {
@@ -139,8 +160,8 @@ export function createPolling(deps: PollingDeps): void {
139
160
  // ---------- pi handler registration ----------
140
161
 
141
162
  pi.on("session_start", (_event, ctx) => {
142
- // botToken validity guaranteed by createConfig; allowedUserId may still
143
- // be missing — handleUpdate bootstraps it on first incoming message.
163
+ // botToken validity is guaranteed by createConfig; polling reports the
164
+ // sender id locally while allowedUserId is missing.
144
165
  start(ctx);
145
166
  });
146
167
 
package/src/toolcall.ts CHANGED
@@ -1,145 +1,200 @@
1
- // Render tool-call breadcrumbs as Telegram Rich Messages.
2
- //
3
- // One message per call, edited in place from "running" to done/error. Layout:
4
- // <icon> **toolName** · `head` ← summary; head inlined when short
5
- // <details>head</details> ← head as a code block instead, when long
6
- // <details>body</details> ← bulk field (content/edits), if any
7
- // <details>arguments</details> ← leftover options as JSON, if any
8
- // <details>output</details> ← result, auto-expanded when short/error
9
- //
10
- // Per-tool layout is declarative (see SPECS); unknown tools fall through to the
11
- // generic arguments block rather than us guessing field meanings. Rich Messages
12
- // parse markdown inside <details>.
13
- // See https://core.telegram.org/bots/api#rich-messages.
14
-
15
- interface ToolSpec {
16
- /** Field shown as the summary: inlined when short, a code block when long. */
17
- head: string;
18
- /** Bulky field always shown as its own code block (file content, edits…). */
19
- body?: string;
20
- /** Code-block language for head/body when rendered as a block. */
21
- lang?: string;
1
+ // Compact tool breadcrumbs: one line per call, one silent message per batch.
2
+ // Shared-message writes are serialized and coalesced; turn_end seals the batch.
3
+
4
+ import { type createApi, MAX_MESSAGE_LENGTH } from "./api.ts";
5
+
6
+ const EDIT_THROTTLE_MS = 500;
7
+ const NAME_MAX = 64;
8
+ const SUMMARY_MAX = 96;
9
+
10
+ const STATUS_ICON = {
11
+ running: "🔧",
12
+ success: "✅",
13
+ error: "❌",
14
+ cancelled: "🚫", // batch closed without a tool_execution_end
15
+ } as const;
16
+
17
+ type ToolStatus = keyof typeof STATUS_ICON;
18
+
19
+ type ToolApi = Pick<ReturnType<typeof createApi>, "sendText" | "editText">;
20
+
21
+ interface ToolCall {
22
+ toolCallId: string;
23
+ toolName: string;
24
+ args: unknown;
25
+ parentToolCallId?: string;
22
26
  }
23
27
 
24
- // Field names are pi's built-in tool schemas; nothing here is guessed.
25
- const SPECS: Record<string, ToolSpec> = {
26
- bash: { head: "command", lang: "sh" },
27
- read: { head: "path" },
28
- ls: { head: "path" },
29
- grep: { head: "pattern" },
30
- find: { head: "pattern" },
31
- write: { head: "path", body: "content" },
32
- edit: { head: "path", body: "edits", lang: "json" },
33
- };
34
-
35
- // Sizing knobs (UX, not technical caps — Telegram's hard limit is 32768 chars).
36
- const INLINE_MAX = 40; // head longer than this renders as a code block, not inline
37
- const FIELD_MAX = 2000; // head/body/arguments block budget
38
- const RESULT_MAX = 3000; // output block budget
39
- const AUTO_OPEN_CHARS = 280; // expand a section only if both this short…
40
- const AUTO_OPEN_LINES = 12; // …and this few lines
41
-
42
- export type ToolArgs = Record<string, unknown> | undefined;
43
- export interface ResultBlock {
44
- type: string;
45
- text?: string;
28
+ interface ToolLine {
29
+ text: string;
30
+ nested: boolean;
31
+ status: ToolStatus;
46
32
  }
47
33
 
48
- // ---------- helpers ----------
34
+ interface ToolPage {
35
+ lines: ToolLine[];
36
+ budget: number;
37
+ messageId: number | undefined;
38
+ lastText: string;
39
+ }
49
40
 
50
- /** Wrap `body` in a fenced code block whose fence outruns any backtick run
51
- * inside it, so content containing ``` can't break out of the block. */
52
- function fence(body: string, lang: string): string {
53
- let longest = 0;
54
- for (const run of body.match(/`+/g) ?? []) longest = Math.max(longest, run.length);
55
- const ticks = "`".repeat(Math.max(3, longest + 1));
56
- return `${ticks}${lang}\n${body}\n${ticks}`;
41
+ interface ToolBatch {
42
+ chatId: number;
43
+ calls: Map<string, ToolLine>;
44
+ pages: ToolPage[];
45
+ flushTimer: ReturnType<typeof setTimeout> | undefined;
57
46
  }
58
47
 
59
- /** Truncate to `max` chars, flagging how much was dropped. */
60
- function clip(text: string, max: number): string {
61
- return text.length <= max ? text : `${text.slice(0, max).trimEnd()}\n… (+${text.length - max} chars)`;
48
+ function oneLine(text: string): string {
49
+ // Parameters must not create extra tool rows.
50
+ return text.replace(/\s+/g, " ").trim();
62
51
  }
63
52
 
64
- /** Collapse to one line and strip backticks for safe use in an inline-code span. */
65
- function inlineHint(text: string): string {
66
- return text.replace(/\s+/g, " ").replace(/`/g, "ʼ").trim();
53
+ function neutralizeBackticks(text: string): string {
54
+ // Dynamic text must not open or close a Markdown code span.
55
+ return text.replaceAll("`", "ʼ");
67
56
  }
68
57
 
69
- /** Short enough to render expanded rather than collapsed. */
70
- function isShort(text: string): boolean {
71
- return text.length <= AUTO_OPEN_CHARS && text.split("\n").length <= AUTO_OPEN_LINES;
58
+ function inlineCode(text: string): string {
59
+ return `\`${neutralizeBackticks(text)}\``;
72
60
  }
73
61
 
74
- /** A tappable <summary> over a fenced code block; short bodies auto-expand. */
75
- function block(
76
- label: string,
77
- body: string,
78
- opts: { lang?: string | undefined; max?: number; open?: boolean } = {},
79
- ): string {
80
- const clipped = clip(body, opts.max ?? FIELD_MAX);
81
- const open = opts.open || isShort(clipped) ? " open" : "";
82
- return `<details${open}><summary>${label}</summary>\n\n${fence(clipped, opts.lang ?? "")}\n\n</details>`;
62
+ function boldToolName(name: string): string {
63
+ // Keep punctuation in custom tool names from becoming Markdown/HTML markup.
64
+ return `**${neutralizeBackticks(name).replace(/[\\*_~[\]<>]/g, "\\$&")}**`;
83
65
  }
84
66
 
85
- /** A field value as code-block text: strings verbatim, JSON when possible. */
86
- function asCode(value: unknown): string {
87
- if (typeof value === "string") return value;
88
- try {
89
- return JSON.stringify(value, null, 2) ?? String(value);
90
- } catch {
91
- return String(value);
92
- }
67
+ function shortenStart(text: string, max: number): string {
68
+ if (text.length <= max) return text;
69
+ // Don't split an emoji's UTF-16 surrogate pair at the cut.
70
+ return `${text.slice(0, max - 1).replace(/[\uD800-\uDBFF]$/, "")}…`;
93
71
  }
94
72
 
95
- /** Flatten result content blocks, noting non-text blocks by type (e.g. `[image]`). */
96
- function resultText(blocks: ResultBlock[]): string {
97
- return blocks
98
- .map((b) => (b.type === "text" && typeof b.text === "string" ? b.text : `[${b.type}]`))
99
- .join("\n")
100
- .trim();
73
+ function shortenPath(value: string, max: number): string {
74
+ const path = oneLine(value);
75
+ if (path.length <= max) return path;
76
+ const suffix = path.replaceAll("\\", "/").slice(-(max - 1));
77
+ const separator = suffix.indexOf("/");
78
+ // Keep as many complete trailing directories as fit. Only cut through the
79
+ // filename if that final segment alone exceeds the budget.
80
+ const tail = separator < 0 ? suffix.replace(/^[\uDC00-\uDFFF]/, "") : suffix.slice(separator);
81
+ return `…${tail}`;
101
82
  }
102
83
 
103
- // ---------- renderer ----------
104
-
105
- /** Summary line + head/body/arguments sections, shared by start and end. */
106
- function header(icon: string, toolName: string, args: Record<string, unknown>): string[] {
107
- const spec = SPECS[toolName];
108
- const used = new Set<string>();
109
- const sections: string[] = [];
110
-
111
- let hint = "";
112
- if (spec) {
113
- const head = args[spec.head];
114
- if (typeof head === "string" && head.length > 0) {
115
- used.add(spec.head);
116
- if (!head.includes("\n") && head.length <= INLINE_MAX) hint = inlineHint(head);
117
- else sections.push(block(spec.head, head, { lang: spec.lang }));
84
+ function summarizeArgs(toolName: string, args: unknown): string {
85
+ if (!args || typeof args !== "object") return "";
86
+ const fields = args as Record<string, unknown>;
87
+ switch (toolName) {
88
+ case "read":
89
+ case "write":
90
+ case "edit":
91
+ case "ls":
92
+ return typeof fields.path === "string" ? shortenPath(fields.path, SUMMARY_MAX) : "";
93
+ case "bash":
94
+ case "powershell":
95
+ return typeof fields.command === "string" ? shortenStart(oneLine(fields.command), SUMMARY_MAX) : "";
96
+ case "grep":
97
+ case "find":
98
+ 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"}` : "";
118
102
  }
119
- if (spec.body && args[spec.body] != null) {
120
- used.add(spec.body);
121
- sections.push(block(spec.body, asCode(args[spec.body]), { lang: spec.lang }));
103
+ default:
104
+ // Unknown schemas may contain bulk or sensitive fields; show only the name.
105
+ return "";
106
+ }
107
+ }
108
+
109
+ function renderLine(line: ToolLine): string {
110
+ return `${line.nested ? "↳ " : ""}${STATUS_ICON[line.status]} ${line.text}`;
111
+ }
112
+
113
+ export function createToolMessages(api: ToolApi) {
114
+ let current: ToolBatch | undefined;
115
+ let chain = Promise.resolve();
116
+
117
+ function enqueue(task: () => Promise<void>): Promise<void> {
118
+ chain = chain.then(task).catch(() => {});
119
+ return chain;
120
+ }
121
+
122
+ async function flush(batch: ToolBatch): Promise<void> {
123
+ for (const page of batch.pages) {
124
+ const text = page.lines.map(renderLine).join("\n");
125
+ if (text === page.lastText) continue;
126
+ try {
127
+ if (page.messageId === undefined) {
128
+ const sent = await api.sendText(batch.chatId, text, { silent: true });
129
+ page.messageId = sent.message_id;
130
+ } else {
131
+ await api.editText(batch.chatId, page.messageId, text);
132
+ }
133
+ page.lastText = text;
134
+ } catch {
135
+ // Breadcrumbs are best-effort. Retry this page on a later flush,
136
+ // but don't prevent the remaining pages from being written.
137
+ }
122
138
  }
123
139
  }
124
- sections.unshift(`${icon} **${toolName}**${hint ? ` · \`${hint}\`` : ""}`);
125
140
 
126
- // everything else: one generic JSON block (the whole arg set for unknown tools).
127
- const rest = Object.fromEntries(Object.entries(args).filter(([k]) => !used.has(k)));
128
- if (Object.keys(rest).length > 0) sections.push(block("arguments", asCode(rest), { lang: "json" }));
141
+ // Merge rapid tool starts/completions into one Telegram edit; the first
142
+ // message is sent immediately, and finalize() flushes without waiting.
143
+ function scheduleFlush(batch: ToolBatch): void {
144
+ if (batch.flushTimer) return;
145
+ batch.flushTimer = setTimeout(() => {
146
+ batch.flushTimer = undefined;
147
+ void enqueue(() => (current === batch ? flush(batch) : Promise.resolve()));
148
+ }, EDIT_THROTTLE_MS);
149
+ }
129
150
 
130
- return sections;
131
- }
151
+ async function start(chatId: number, call: ToolCall): Promise<void> {
152
+ if (call.parentToolCallId && (current?.chatId !== chatId || !current.calls.has(call.parentToolCallId))) return;
153
+ // Record synchronously before any await; the writer queue preserves send order.
154
+ if (current && current.chatId !== chatId) void finalize();
155
+ current ??= { chatId, calls: new Map(), pages: [], flushTimer: undefined };
156
+ const batch = current;
157
+ if (batch.calls.has(call.toolCallId)) return;
158
+ const name = boldToolName(shortenStart(oneLine(call.toolName), NAME_MAX));
159
+ const args = summarizeArgs(call.toolName, call.args);
160
+ const line: ToolLine = {
161
+ text: `${name}${args ? ` · ${inlineCode(args)}` : ""}`,
162
+ nested: call.parentToolCallId !== undefined,
163
+ status: "running",
164
+ };
165
+ batch.calls.set(call.toolCallId, line);
166
+ // Running and cancelled icons have the same length; reserve a newline
167
+ // so status edits never move a line between pages.
168
+ const budget = renderLine(line).length + 1;
169
+ let page = batch.pages.at(-1);
170
+ if (!page || page.budget + budget > MAX_MESSAGE_LENGTH) {
171
+ page = { lines: [], budget: 0, messageId: undefined, lastText: "" };
172
+ batch.pages.push(page);
173
+ }
174
+ page.lines.push(line);
175
+ page.budget += budget;
176
+ if (page.messageId === undefined) await enqueue(() => flush(batch));
177
+ else scheduleFlush(batch);
178
+ }
132
179
 
133
- /** Breadcrumb for a tool that just started running. */
134
- export function renderToolStart(toolName: string, args: ToolArgs): string {
135
- return header("🔧", toolName, args ?? {}).join("\n\n");
136
- }
180
+ function end(toolCallId: string, isError: boolean): void {
181
+ const batch = current;
182
+ const line = batch?.calls.get(toolCallId);
183
+ if (!batch || !line) return;
184
+ line.status = isError ? "error" : "success";
185
+ scheduleFlush(batch);
186
+ }
187
+
188
+ function finalize(): Promise<void> {
189
+ const batch = current;
190
+ if (!batch) return chain;
191
+ current = undefined;
192
+ if (batch.flushTimer) clearTimeout(batch.flushTimer);
193
+ for (const line of batch.calls.values()) {
194
+ if (line.status === "running") line.status = "cancelled";
195
+ }
196
+ return enqueue(() => flush(batch));
197
+ }
137
198
 
138
- /** Breadcrumb for a finished tool: same header (now ✅/❌) plus the output.
139
- * Args come from the start event since the end event omits them. */
140
- export function renderToolEnd(toolName: string, args: ToolArgs, blocks: ResultBlock[], isError: boolean): string {
141
- const sections = header(isError ? "❌" : "✅", toolName, args ?? {});
142
- const result = resultText(blocks);
143
- if (result) sections.push(block("output", result, { max: RESULT_MAX, open: isError }));
144
- return sections.join("\n\n");
199
+ return { start, end, finalize };
145
200
  }
package/src/turn.ts CHANGED
@@ -1,19 +1,21 @@
1
1
  // Turn lifecycle + pi event handlers (agent_*, message_*, tool_*). Registers
2
2
  // the telegram_attach tool. Media handling lives in media.ts.
3
3
  //
4
+ // A Telegram request can span multiple pi turns and retries: turn_end closes
5
+ // each tool batch, while agent_settled closes the Telegram request.
4
6
  // Concurrency: no local queue. Idle → stash as `pending`, sendUserMessage,
5
7
  // agent_start promotes to `active`. Busy → sendUserMessage with
6
8
  // deliverAs:"steer" to inject into the running turn.
7
9
 
8
10
  import { stat } from "node:fs/promises";
9
11
  import { basename } from "node:path";
10
- import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
12
+ import type { AssistantMessage, ImageContent, TextContent } from "@earendil-works/pi-ai";
11
13
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
14
  import { Type } from "typebox";
13
15
  import type { createApi } from "./api.ts";
14
16
  import type { createMedia, QueuedAttachment } from "./media.ts";
15
17
  import type { createPreview } from "./preview.ts";
16
- import { type ResultBlock, renderToolEnd, renderToolStart, type ToolArgs } from "./toolcall.ts";
18
+ import { createToolMessages } from "./toolcall.ts";
17
19
  import type { TelegramMessage } from "./types.ts";
18
20
  import { getMessageText, isAssistantMessage } from "./utils.ts";
19
21
 
@@ -23,6 +25,8 @@ interface TelegramTurn {
23
25
  chatId: number;
24
26
  queuedAttachments: QueuedAttachment[];
25
27
  content: Array<TextContent | ImageContent>;
28
+ lastResponse?: { stopReason: AssistantMessage["stopReason"]; errorMessage: string | undefined };
29
+ abortRequested?: boolean;
26
30
  }
27
31
 
28
32
  interface TurnDeps {
@@ -34,14 +38,12 @@ interface TurnDeps {
34
38
 
35
39
  export function createTurn(deps: TurnDeps) {
36
40
  const { pi, api, media, preview } = deps;
41
+ const toolMessages = createToolMessages(api);
37
42
 
38
43
  let pending: TelegramTurn | undefined;
39
44
  let active: TelegramTurn | undefined;
40
45
  let currentAbort: (() => void) | undefined;
41
46
  let typingInterval: ReturnType<typeof setInterval> | undefined;
42
- // toolCallId → its breadcrumb message id and the args from tool_execution_start
43
- // (the end event omits args, so we stash them to re-render the finished card).
44
- const toolMessages = new Map<string, { id: number; toolName: string; args: ToolArgs }>();
45
47
 
46
48
  function startTyping(chatId: number): void {
47
49
  if (typingInterval) return;
@@ -111,11 +113,11 @@ export function createTurn(deps: TurnDeps) {
111
113
  });
112
114
 
113
115
  pi.on("session_shutdown", async (_event, _ctx) => {
116
+ await toolMessages.finalize();
114
117
  await preview.finalize();
115
118
  pending = undefined;
116
119
  active = undefined;
117
120
  currentAbort = undefined;
118
- toolMessages.clear();
119
121
  stopTyping();
120
122
  });
121
123
 
@@ -139,38 +141,41 @@ export function createTurn(deps: TurnDeps) {
139
141
 
140
142
  pi.on("tool_execution_start", async (event) => {
141
143
  if (!active) return;
142
- // Finalize first so pre-tool text doesn't end up below the 🔧 message.
143
144
  await preview.finalize();
144
- const args = event.args as ToolArgs;
145
- const sent = await api.sendText(active.chatId, renderToolStart(event.toolName, args), { silent: true });
146
- toolMessages.set(event.toolCallId, { id: sent.message_id, toolName: event.toolName, args });
145
+ await toolMessages.start(active.chatId, event);
147
146
  });
148
147
 
149
- pi.on("tool_execution_end", async (event) => {
148
+ pi.on("tool_execution_end", (event) => {
149
+ if (active) toolMessages.end(event.toolCallId, event.isError);
150
+ });
151
+
152
+ pi.on("turn_end", async () => {
153
+ await toolMessages.finalize();
154
+ });
155
+
156
+ pi.on("agent_end", async (event) => {
157
+ await toolMessages.finalize();
150
158
  if (!active) return;
151
- const entry = toolMessages.get(event.toolCallId);
152
- toolMessages.delete(event.toolCallId);
153
- if (!entry) return;
154
- const blocks = (Array.isArray(event.result?.content) ? event.result.content : []) as ResultBlock[];
155
- const text = renderToolEnd(entry.toolName, entry.args, blocks, event.isError);
156
- await api.editText(active.chatId, entry.id, text).catch(() => {});
159
+ const response = event.messages.findLast(isAssistantMessage);
160
+ if (response) active.lastResponse = { stopReason: response.stopReason, errorMessage: response.errorMessage };
161
+ // A failed attempt may be retried. Publish its partial output silently,
162
+ // but keep the Telegram turn active until pi is fully settled.
163
+ if (response?.stopReason === "error" || response?.stopReason === "aborted") await preview.finalize();
157
164
  });
158
165
 
159
- pi.on("agent_end", async (event, _ctx) => {
166
+ pi.on("agent_settled", async () => {
160
167
  const turn = active;
168
+ // Detach before awaiting Telegram I/O so messages arriving now start a new turn.
169
+ active = undefined;
161
170
  currentAbort = undefined;
162
171
  stopTyping();
163
- active = undefined;
164
- pending = undefined;
165
- // Drop any breadcrumbs whose tool never reported an end (e.g. aborted mid-run).
166
- toolMessages.clear();
172
+ if (pending) startTyping(pending.chatId);
167
173
  if (!turn) return;
168
174
 
169
- const { stopReason, errorMessage } = event.messages.findLast(isAssistantMessage) ?? {};
170
- // Partial output before abort/error is progress; the error itself notifies.
171
- const final = stopReason !== "aborted" && stopReason !== "error";
175
+ const { stopReason, errorMessage } = turn.lastResponse ?? {};
176
+ const final = !turn.abortRequested && stopReason !== "aborted" && stopReason !== "error";
172
177
  const sent = await preview.finalize(final);
173
- if (stopReason === "aborted") return;
178
+ if (turn.abortRequested || stopReason === "aborted") return;
174
179
  if (stopReason === "error") {
175
180
  await api.sendText(turn.chatId, errorMessage || "Telegram bridge: pi failed while processing the request.");
176
181
  return;
@@ -183,9 +188,11 @@ export function createTurn(deps: TurnDeps) {
183
188
 
184
189
  /** Dispatch a new batch of Telegram messages. Starts a fresh turn (if idle)
185
190
  * or steers into the running one. */
186
- async function handleIncoming(messages: TelegramMessage[], _ctx: ExtensionContext): Promise<void> {
191
+ async function handleIncoming(messages: TelegramMessage[], ctx: ExtensionContext): Promise<void> {
187
192
  const built = await build(messages);
188
- const isFresh = !pending && !active;
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());
189
196
  if (isFresh) {
190
197
  pending = built;
191
198
  startTyping(built.chatId);
@@ -199,6 +206,7 @@ export function createTurn(deps: TurnDeps) {
199
206
  /** Abort the active turn. Returns true iff one was active. */
200
207
  function abort(): boolean {
201
208
  if (currentAbort) {
209
+ if (active) active.abortRequested = true;
202
210
  currentAbort();
203
211
  return true;
204
212
  }