@qusic/pi-telegram 0.1.1 β†’ 0.2.1

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
@@ -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
@@ -46,7 +46,7 @@ Resuming a session echoes that session's last reply back to the chat, so it refl
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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qusic/pi-telegram",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
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/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/toolcall.ts CHANGED
@@ -1,145 +1,203 @@
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
+ // 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";
12
+
13
+ const STATUS_ICON = {
14
+ running: "πŸ”§",
15
+ success: "βœ…",
16
+ error: "❌",
17
+ cancelled: "🚫", // batch closed without a tool_execution_end
18
+ } as const;
19
+
20
+ type ToolStatus = keyof typeof STATUS_ICON;
21
+
22
+ type ToolApi = Pick<ReturnType<typeof createApi>, "sendText" | "editText">;
23
+
24
+ interface ToolCall {
25
+ toolCallId: string;
26
+ toolName: string;
27
+ args: unknown;
28
+ parentToolCallId?: string;
22
29
  }
23
30
 
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;
31
+ interface ToolLine {
32
+ text: string;
33
+ nested: boolean;
34
+ status: ToolStatus;
46
35
  }
47
36
 
48
- // ---------- helpers ----------
37
+ interface ToolPage {
38
+ lines: ToolLine[];
39
+ budget: number;
40
+ messageId: number | undefined;
41
+ lastText: string;
42
+ }
49
43
 
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}`;
44
+ interface ToolBatch {
45
+ chatId: number;
46
+ calls: Map<string, ToolLine>;
47
+ pages: ToolPage[];
48
+ flushTimer: ReturnType<typeof setTimeout> | undefined;
57
49
  }
58
50
 
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)`;
51
+ function oneLine(text: string): string {
52
+ // Parameters must not create extra tool rows.
53
+ return text.replace(/\s+/g, " ").trim();
62
54
  }
63
55
 
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();
56
+ function neutralizeBackticks(text: string): string {
57
+ // Dynamic text must not open or close a Markdown code span.
58
+ return text.replaceAll("`", "ΚΌ");
67
59
  }
68
60
 
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;
61
+ function inlineCode(text: string): string {
62
+ return `\`${neutralizeBackticks(text)}\``;
72
63
  }
73
64
 
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>`;
65
+ function boldToolName(name: string): string {
66
+ // Keep punctuation in custom tool names from becoming Markdown/HTML markup.
67
+ return `**${neutralizeBackticks(name).replace(/[\\*_~[\]<>]/g, "\\$&")}**`;
83
68
  }
84
69
 
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
- }
70
+ function shortenStart(text: string, max: number): string {
71
+ if (text.length <= max) return text;
72
+ // Don't split an emoji's UTF-16 surrogate pair at the cut.
73
+ return `${text.slice(0, max - 1).replace(/[\uD800-\uDBFF]$/, "")}…`;
93
74
  }
94
75
 
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();
76
+ function shortenPath(value: string, max: number): string {
77
+ const path = oneLine(value);
78
+ if (path.length <= max) return path;
79
+ const suffix = path.replaceAll("\\", "/").slice(-(max - 1));
80
+ const separator = suffix.indexOf("/");
81
+ // Keep as many complete trailing directories as fit. Only cut through the
82
+ // filename if that final segment alone exceeds the budget.
83
+ const tail = separator < 0 ? suffix.replace(/^[\uDC00-\uDFFF]/, "") : suffix.slice(separator);
84
+ return `…${tail}`;
101
85
  }
102
86
 
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 }));
87
+ function summarizeArgs(toolName: string, args: unknown): string {
88
+ if (!args || typeof args !== "object") return "";
89
+ const fields = args as Record<string, unknown>;
90
+ switch (toolName) {
91
+ case "read":
92
+ case "write":
93
+ case "edit":
94
+ case "ls":
95
+ return typeof fields.path === "string" ? shortenPath(fields.path, SUMMARY_MAX) : "";
96
+ case "bash":
97
+ case "powershell":
98
+ return typeof fields.command === "string" ? shortenStart(oneLine(fields.command), SUMMARY_MAX) : "";
99
+ case "grep":
100
+ case "find":
101
+ return typeof fields.pattern === "string" ? shortenStart(oneLine(fields.pattern), SUMMARY_MAX) : "";
102
+ case "telegram_attach": {
103
+ const paths = fields.paths;
104
+ return Array.isArray(paths) ? `${paths.length} file${paths.length === 1 ? "" : "s"}` : "";
118
105
  }
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 }));
106
+ default:
107
+ // Unknown schemas may contain bulk or sensitive fields; show only the name.
108
+ return "";
109
+ }
110
+ }
111
+
112
+ function renderLine(line: ToolLine): string {
113
+ return `${line.nested ? "↳ " : ""}${STATUS_ICON[line.status]} ${line.text}`;
114
+ }
115
+
116
+ export function createToolMessages(api: ToolApi) {
117
+ let current: ToolBatch | undefined;
118
+ let chain = Promise.resolve();
119
+
120
+ function enqueue(task: () => Promise<void>): Promise<void> {
121
+ chain = chain.then(task).catch(() => {});
122
+ return chain;
123
+ }
124
+
125
+ async function flush(batch: ToolBatch): Promise<void> {
126
+ for (const page of batch.pages) {
127
+ const text = page.lines.map(renderLine).join(TOOL_LINE_BREAK);
128
+ if (text === page.lastText) continue;
129
+ try {
130
+ if (page.messageId === undefined) {
131
+ const sent = await api.sendText(batch.chatId, text, { silent: true });
132
+ page.messageId = sent.message_id;
133
+ } else {
134
+ await api.editText(batch.chatId, page.messageId, text);
135
+ }
136
+ page.lastText = text;
137
+ } catch {
138
+ // Breadcrumbs are best-effort. Retry this page on a later flush,
139
+ // but don't prevent the remaining pages from being written.
140
+ }
122
141
  }
123
142
  }
124
- sections.unshift(`${icon} **${toolName}**${hint ? ` Β· \`${hint}\`` : ""}`);
125
143
 
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" }));
144
+ // Merge rapid tool starts/completions into one Telegram edit; the first
145
+ // message is sent immediately, and finalize() flushes without waiting.
146
+ function scheduleFlush(batch: ToolBatch): void {
147
+ if (batch.flushTimer) return;
148
+ batch.flushTimer = setTimeout(() => {
149
+ batch.flushTimer = undefined;
150
+ void enqueue(() => (current === batch ? flush(batch) : Promise.resolve()));
151
+ }, EDIT_THROTTLE_MS);
152
+ }
129
153
 
130
- return sections;
131
- }
154
+ async function start(chatId: number, call: ToolCall): Promise<void> {
155
+ if (call.parentToolCallId && (current?.chatId !== chatId || !current.calls.has(call.parentToolCallId))) return;
156
+ // Record synchronously before any await; the writer queue preserves send order.
157
+ if (current && current.chatId !== chatId) void finalize();
158
+ current ??= { chatId, calls: new Map(), pages: [], flushTimer: undefined };
159
+ const batch = current;
160
+ if (batch.calls.has(call.toolCallId)) return;
161
+ const name = boldToolName(shortenStart(oneLine(call.toolName), NAME_MAX));
162
+ const args = summarizeArgs(call.toolName, call.args);
163
+ const line: ToolLine = {
164
+ text: `${name}${args ? ` Β· ${inlineCode(args)}` : ""}`,
165
+ nested: call.parentToolCallId !== undefined,
166
+ status: "running",
167
+ };
168
+ batch.calls.set(call.toolCallId, line);
169
+ // Running and cancelled icons have the same length; reserve a break
170
+ // so status edits never move a line between pages.
171
+ const budget = renderLine(line).length + TOOL_LINE_BREAK.length;
172
+ let page = batch.pages.at(-1);
173
+ if (!page || page.budget + budget > MAX_MESSAGE_LENGTH) {
174
+ page = { lines: [], budget: 0, messageId: undefined, lastText: "" };
175
+ batch.pages.push(page);
176
+ }
177
+ page.lines.push(line);
178
+ page.budget += budget;
179
+ if (page.messageId === undefined) await enqueue(() => flush(batch));
180
+ else scheduleFlush(batch);
181
+ }
132
182
 
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
- }
183
+ function end(toolCallId: string, isError: boolean): void {
184
+ const batch = current;
185
+ const line = batch?.calls.get(toolCallId);
186
+ if (!batch || !line) return;
187
+ line.status = isError ? "error" : "success";
188
+ scheduleFlush(batch);
189
+ }
190
+
191
+ function finalize(): Promise<void> {
192
+ const batch = current;
193
+ if (!batch) return chain;
194
+ current = undefined;
195
+ if (batch.flushTimer) clearTimeout(batch.flushTimer);
196
+ for (const line of batch.calls.values()) {
197
+ if (line.status === "running") line.status = "cancelled";
198
+ }
199
+ return enqueue(() => flush(batch));
200
+ }
137
201
 
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");
202
+ return { start, end, finalize };
145
203
  }
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
  }
package/src/utils.ts CHANGED
@@ -62,8 +62,10 @@ export function getMessageText(message: AssistantMessage): string {
62
62
  let prevType: "text" | "thinking" = "text";
63
63
  for (const block of message.content) {
64
64
  if (block.type !== "text" && block.type !== "thinking") continue;
65
+ const content = block.type === "text" ? block.text : block.thinking;
66
+ if (!content.trim()) continue;
65
67
  const marker = block.type === prevType ? "" : SECTION_MARKER[block.type];
66
- parts.push(marker + (block.type === "text" ? block.text : block.thinking));
68
+ parts.push(marker + content);
67
69
  prevType = block.type;
68
70
  }
69
71
  return parts.join("\n\n").trim();