@qusic/pi-telegram 0.0.0 → 0.1.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/LICENSE +21 -0
- package/README.md +71 -29
- package/package.json +59 -8
- package/src/api.ts +204 -0
- package/src/chunk.ts +86 -0
- package/src/config.ts +55 -0
- package/src/dispatch.ts +237 -0
- package/src/index.ts +21 -0
- package/src/media.ts +142 -0
- package/src/polling.ts +173 -0
- package/src/preview.ts +149 -0
- package/src/toolcall.ts +145 -0
- package/src/turn.ts +209 -0
- package/src/types.ts +74 -0
- package/src/utils.ts +91 -0
package/src/preview.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// Streaming preview / draft management.
|
|
2
|
+
//
|
|
3
|
+
// Caller pushes the full accumulated assistant text via update(); finalize()
|
|
4
|
+
// publishes whatever is buffered. When the pending tail exceeds the per-message
|
|
5
|
+
// budget, a head is promoted to a real message and the rest keeps streaming as
|
|
6
|
+
// a draft; chunk.ts picks block-aware cut points so each piece stays valid
|
|
7
|
+
// markdown (code fences split across messages are reopened/closed).
|
|
8
|
+
//
|
|
9
|
+
// Concurrency: update() is synchronous and only ever GROWS `fullText`
|
|
10
|
+
// (assistant output is append-only). All async work (draft sends, promotions,
|
|
11
|
+
// finalize) runs through a single serialized `enqueue` chain so two operations
|
|
12
|
+
// can never mutate the same state concurrently — that race was the source of
|
|
13
|
+
// duplicated commits and dropped tails on long outputs. Because update() is
|
|
14
|
+
// append-only, every serialized task re-derives the pending region from
|
|
15
|
+
// `publishedChars` at point-of-use, so an update() landing between awaits can
|
|
16
|
+
// never corrupt the invariant.
|
|
17
|
+
|
|
18
|
+
import { type createApi, MAX_MESSAGE_LENGTH } from "./api.ts";
|
|
19
|
+
import { nextBoundary, renderChunk } from "./chunk.ts";
|
|
20
|
+
|
|
21
|
+
const PREVIEW_THROTTLE_MS = 1500;
|
|
22
|
+
|
|
23
|
+
// Headroom for the fence reopen/close markers renderChunk may add to a chunk
|
|
24
|
+
// (```lang … ```): at most a couple of fence runs plus a language token.
|
|
25
|
+
const CHUNK_BUDGET = MAX_MESSAGE_LENGTH - 64;
|
|
26
|
+
|
|
27
|
+
type PreviewApi = Pick<ReturnType<typeof createApi>, "clearDraft" | "sendDraft" | "sendText">;
|
|
28
|
+
|
|
29
|
+
interface TelegramPreviewState {
|
|
30
|
+
chatId: number;
|
|
31
|
+
/** Entire accumulated assistant text seen so far (monotonically grows). */
|
|
32
|
+
fullText: string;
|
|
33
|
+
/** Raw chars of `fullText` already committed as real messages (a true prefix
|
|
34
|
+
* offset — synthetic fences are render-only and never counted here). */
|
|
35
|
+
publishedChars: number;
|
|
36
|
+
/** Last text pushed to the live draft (dedup guard). */
|
|
37
|
+
lastSentText: string;
|
|
38
|
+
/** True once anything has been committed as a real message. */
|
|
39
|
+
published: boolean;
|
|
40
|
+
draftId: number | undefined;
|
|
41
|
+
flushTimer: ReturnType<typeof setTimeout> | undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createPreview(api: PreviewApi) {
|
|
45
|
+
let current: TelegramPreviewState | undefined;
|
|
46
|
+
|
|
47
|
+
// Single-writer queue: every async preview op runs strictly one at a time,
|
|
48
|
+
// in FIFO order, so flush/promote/finalize never overlap. A failed task
|
|
49
|
+
// never poisons the chain (its rejection is swallowed for chain purposes
|
|
50
|
+
// but still surfaced to the original caller).
|
|
51
|
+
let chain: Promise<unknown> = Promise.resolve();
|
|
52
|
+
function enqueue<T>(task: () => Promise<T>): Promise<T> {
|
|
53
|
+
// `chain` is kept non-rejecting (the .catch below), so a plain .then runs
|
|
54
|
+
// tasks strictly one at a time, in FIFO order.
|
|
55
|
+
const next = chain.then(task);
|
|
56
|
+
chain = next.catch(() => {});
|
|
57
|
+
return next;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Render the uncommitted region [publishedChars, to) as a standalone message. */
|
|
61
|
+
function renderPending(c: TelegramPreviewState, to: number): string {
|
|
62
|
+
return renderChunk(c.fullText, c.publishedChars, to);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function clearDraft(c: TelegramPreviewState): Promise<void> {
|
|
66
|
+
if (c.draftId === undefined) return;
|
|
67
|
+
await api.clearDraft(c.chatId, c.draftId);
|
|
68
|
+
c.draftId = undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Promote oversized pending text into one or more real messages until it
|
|
72
|
+
* fits. Re-reads `fullText` each iteration so a concurrent update() (which
|
|
73
|
+
* only appends) is absorbed safely. */
|
|
74
|
+
async function promoteOversized(c: TelegramPreviewState): Promise<void> {
|
|
75
|
+
while (c.fullText.length - c.publishedChars > CHUNK_BUDGET) {
|
|
76
|
+
const to = nextBoundary(c.fullText, c.publishedChars, CHUNK_BUDGET);
|
|
77
|
+
const head = renderPending(c, to);
|
|
78
|
+
await clearDraft(c);
|
|
79
|
+
await api.sendText(c.chatId, head, { silent: true });
|
|
80
|
+
c.publishedChars = to;
|
|
81
|
+
c.published = true;
|
|
82
|
+
c.lastSentText = "";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Replace the accumulated text and schedule a throttled flush. */
|
|
87
|
+
function update(chatId: number, fullText: string): void {
|
|
88
|
+
if (!current || current.chatId !== chatId) {
|
|
89
|
+
current = {
|
|
90
|
+
chatId,
|
|
91
|
+
fullText,
|
|
92
|
+
publishedChars: 0,
|
|
93
|
+
lastSentText: "",
|
|
94
|
+
published: false,
|
|
95
|
+
draftId: undefined,
|
|
96
|
+
flushTimer: undefined,
|
|
97
|
+
};
|
|
98
|
+
} else {
|
|
99
|
+
current.fullText = fullText;
|
|
100
|
+
}
|
|
101
|
+
const c = current;
|
|
102
|
+
if (!c.flushTimer) {
|
|
103
|
+
c.flushTimer = setTimeout(() => {
|
|
104
|
+
c.flushTimer = undefined;
|
|
105
|
+
// Skip if this state was already finalized/replaced.
|
|
106
|
+
void enqueue(() => (current === c ? flushState(c) : Promise.resolve())).catch(() => {});
|
|
107
|
+
}, PREVIEW_THROTTLE_MS);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function flushState(c: TelegramPreviewState): Promise<void> {
|
|
112
|
+
await promoteOversized(c);
|
|
113
|
+
const draft = renderPending(c, c.fullText.length);
|
|
114
|
+
if (!draft || draft === c.lastSentText) return;
|
|
115
|
+
const draftId = c.draftId ?? Date.now();
|
|
116
|
+
c.draftId = draftId;
|
|
117
|
+
await api.sendDraft(c.chatId, draftId, draft);
|
|
118
|
+
c.lastSentText = draft;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function finalizeState(c: TelegramPreviewState, final: boolean): Promise<boolean> {
|
|
122
|
+
await promoteOversized(c);
|
|
123
|
+
const text = renderPending(c, c.fullText.length);
|
|
124
|
+
await clearDraft(c);
|
|
125
|
+
if (!text) return c.published;
|
|
126
|
+
await api.sendText(c.chatId, text, { silent: !final });
|
|
127
|
+
c.publishedChars = c.fullText.length;
|
|
128
|
+
c.published = true;
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 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> {
|
|
136
|
+
const c = current;
|
|
137
|
+
if (!c) return Promise.resolve(false);
|
|
138
|
+
if (c.flushTimer) {
|
|
139
|
+
clearTimeout(c.flushTimer);
|
|
140
|
+
c.flushTimer = undefined;
|
|
141
|
+
}
|
|
142
|
+
// Detach synchronously so any queued flush for this state no-ops and a
|
|
143
|
+
// subsequent assistant message starts a fresh preview.
|
|
144
|
+
current = undefined;
|
|
145
|
+
return enqueue(() => finalizeState(c, final)).catch(() => c.published);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return { update, finalize };
|
|
149
|
+
}
|
package/src/toolcall.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
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;
|
|
22
|
+
}
|
|
23
|
+
|
|
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;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ---------- helpers ----------
|
|
49
|
+
|
|
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}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
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)`;
|
|
62
|
+
}
|
|
63
|
+
|
|
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();
|
|
67
|
+
}
|
|
68
|
+
|
|
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;
|
|
72
|
+
}
|
|
73
|
+
|
|
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>`;
|
|
83
|
+
}
|
|
84
|
+
|
|
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
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
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();
|
|
101
|
+
}
|
|
102
|
+
|
|
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 }));
|
|
118
|
+
}
|
|
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 }));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
sections.unshift(`${icon} **${toolName}**${hint ? ` · \`${hint}\`` : ""}`);
|
|
125
|
+
|
|
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" }));
|
|
129
|
+
|
|
130
|
+
return sections;
|
|
131
|
+
}
|
|
132
|
+
|
|
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
|
+
}
|
|
137
|
+
|
|
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");
|
|
145
|
+
}
|
package/src/turn.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Turn lifecycle + pi event handlers (agent_*, message_*, tool_*). Registers
|
|
2
|
+
// the telegram_attach tool. Media handling lives in media.ts.
|
|
3
|
+
//
|
|
4
|
+
// Concurrency: no local queue. Idle → stash as `pending`, sendUserMessage,
|
|
5
|
+
// agent_start promotes to `active`. Busy → sendUserMessage with
|
|
6
|
+
// deliverAs:"steer" to inject into the running turn.
|
|
7
|
+
|
|
8
|
+
import { stat } from "node:fs/promises";
|
|
9
|
+
import { basename } from "node:path";
|
|
10
|
+
import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
|
|
11
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { Type } from "typebox";
|
|
13
|
+
import type { createApi } from "./api.ts";
|
|
14
|
+
import type { createMedia, QueuedAttachment } from "./media.ts";
|
|
15
|
+
import type { createPreview } from "./preview.ts";
|
|
16
|
+
import { type ResultBlock, renderToolEnd, renderToolStart, type ToolArgs } from "./toolcall.ts";
|
|
17
|
+
import type { TelegramMessage } from "./types.ts";
|
|
18
|
+
import { getMessageText, isAssistantMessage } from "./utils.ts";
|
|
19
|
+
|
|
20
|
+
const MAX_ATTACHMENTS_PER_TURN = 10;
|
|
21
|
+
|
|
22
|
+
interface TelegramTurn {
|
|
23
|
+
chatId: number;
|
|
24
|
+
queuedAttachments: QueuedAttachment[];
|
|
25
|
+
content: Array<TextContent | ImageContent>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface TurnDeps {
|
|
29
|
+
pi: ExtensionAPI;
|
|
30
|
+
api: ReturnType<typeof createApi>;
|
|
31
|
+
media: ReturnType<typeof createMedia>;
|
|
32
|
+
preview: ReturnType<typeof createPreview>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createTurn(deps: TurnDeps) {
|
|
36
|
+
const { pi, api, media, preview } = deps;
|
|
37
|
+
|
|
38
|
+
let pending: TelegramTurn | undefined;
|
|
39
|
+
let active: TelegramTurn | undefined;
|
|
40
|
+
let currentAbort: (() => void) | undefined;
|
|
41
|
+
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
|
+
|
|
46
|
+
function startTyping(chatId: number): void {
|
|
47
|
+
if (typingInterval) return;
|
|
48
|
+
const sendTyping = async () => {
|
|
49
|
+
try {
|
|
50
|
+
await api.call("sendChatAction", { chat_id: chatId, action: "typing" });
|
|
51
|
+
} catch {
|
|
52
|
+
// non-critical UX hint
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
void sendTyping();
|
|
56
|
+
typingInterval = setInterval(() => {
|
|
57
|
+
void sendTyping();
|
|
58
|
+
}, 4000);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function stopTyping(): void {
|
|
62
|
+
if (!typingInterval) return;
|
|
63
|
+
clearInterval(typingInterval);
|
|
64
|
+
typingInterval = undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function build(messages: TelegramMessage[]): Promise<TelegramTurn> {
|
|
68
|
+
const firstMessage = messages[0];
|
|
69
|
+
if (!firstMessage) throw new Error("Missing Telegram message for turn creation");
|
|
70
|
+
const content = await media.buildPromptContent(messages);
|
|
71
|
+
return {
|
|
72
|
+
chatId: firstMessage.chat.id,
|
|
73
|
+
queuedAttachments: [],
|
|
74
|
+
content,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ---------- pi handler registration ----------
|
|
79
|
+
|
|
80
|
+
pi.registerTool({
|
|
81
|
+
name: "telegram_attach",
|
|
82
|
+
label: "Telegram Attach",
|
|
83
|
+
description: "Queue one or more local files to be sent with the next Telegram reply.",
|
|
84
|
+
promptSnippet: "Queue local files to be sent with the next Telegram reply.",
|
|
85
|
+
promptGuidelines: [
|
|
86
|
+
"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.",
|
|
87
|
+
],
|
|
88
|
+
parameters: Type.Object({
|
|
89
|
+
paths: Type.Array(Type.String({ description: "Local file path to attach" }), {
|
|
90
|
+
minItems: 1,
|
|
91
|
+
maxItems: MAX_ATTACHMENTS_PER_TURN,
|
|
92
|
+
}),
|
|
93
|
+
}),
|
|
94
|
+
async execute(_toolCallId, params) {
|
|
95
|
+
if (!active) throw new Error("telegram_attach can only be used while replying to an active Telegram turn");
|
|
96
|
+
const added: string[] = [];
|
|
97
|
+
for (const inputPath of params.paths) {
|
|
98
|
+
const stats = await stat(inputPath);
|
|
99
|
+
if (!stats.isFile()) throw new Error(`Not a file: ${inputPath}`);
|
|
100
|
+
if (active.queuedAttachments.length >= MAX_ATTACHMENTS_PER_TURN) {
|
|
101
|
+
throw new Error(`Attachment limit reached (${MAX_ATTACHMENTS_PER_TURN})`);
|
|
102
|
+
}
|
|
103
|
+
active.queuedAttachments.push({ path: inputPath, fileName: basename(inputPath) });
|
|
104
|
+
added.push(inputPath);
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
content: [{ type: "text", text: `Queued ${added.length} Telegram attachment(s).` }],
|
|
108
|
+
details: { paths: added },
|
|
109
|
+
};
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
pi.on("session_shutdown", async (_event, _ctx) => {
|
|
114
|
+
await preview.finalize();
|
|
115
|
+
pending = undefined;
|
|
116
|
+
active = undefined;
|
|
117
|
+
currentAbort = undefined;
|
|
118
|
+
toolMessages.clear();
|
|
119
|
+
stopTyping();
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
pi.on("agent_start", (_event, ctx) => {
|
|
123
|
+
currentAbort = () => ctx.abort();
|
|
124
|
+
if (pending) {
|
|
125
|
+
active = pending;
|
|
126
|
+
pending = undefined;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
pi.on("message_start", async (event, _ctx) => {
|
|
131
|
+
if (!active || !isAssistantMessage(event.message)) return;
|
|
132
|
+
await preview.finalize();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
pi.on("message_update", (event, _ctx) => {
|
|
136
|
+
if (!active || !isAssistantMessage(event.message)) return;
|
|
137
|
+
preview.update(active.chatId, getMessageText(event.message));
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
pi.on("tool_execution_start", async (event) => {
|
|
141
|
+
if (!active) return;
|
|
142
|
+
// Finalize first so pre-tool text doesn't end up below the 🔧 message.
|
|
143
|
+
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 });
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
pi.on("tool_execution_end", async (event) => {
|
|
150
|
+
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(() => {});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
pi.on("agent_end", async (event, _ctx) => {
|
|
160
|
+
const turn = active;
|
|
161
|
+
currentAbort = undefined;
|
|
162
|
+
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();
|
|
167
|
+
if (!turn) return;
|
|
168
|
+
|
|
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";
|
|
172
|
+
const sent = await preview.finalize(final);
|
|
173
|
+
if (stopReason === "aborted") return;
|
|
174
|
+
if (stopReason === "error") {
|
|
175
|
+
await api.sendText(turn.chatId, errorMessage || "Telegram bridge: pi failed while processing the request.");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (!sent && turn.queuedAttachments.length > 0) {
|
|
179
|
+
await api.sendText(turn.chatId, "Attached requested file(s).");
|
|
180
|
+
}
|
|
181
|
+
await media.sendAttachments(turn.chatId, turn.queuedAttachments);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
/** Dispatch a new batch of Telegram messages. Starts a fresh turn (if idle)
|
|
185
|
+
* or steers into the running one. */
|
|
186
|
+
async function handleIncoming(messages: TelegramMessage[], _ctx: ExtensionContext): Promise<void> {
|
|
187
|
+
const built = await build(messages);
|
|
188
|
+
const isFresh = !pending && !active;
|
|
189
|
+
if (isFresh) {
|
|
190
|
+
pending = built;
|
|
191
|
+
startTyping(built.chatId);
|
|
192
|
+
}
|
|
193
|
+
pi.sendUserMessage(built.content, {
|
|
194
|
+
expandPromptTemplates: true,
|
|
195
|
+
...(isFresh ? {} : { deliverAs: "steer" }),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Abort the active turn. Returns true iff one was active. */
|
|
200
|
+
function abort(): boolean {
|
|
201
|
+
if (currentAbort) {
|
|
202
|
+
currentAbort();
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return { handleIncoming, abort };
|
|
209
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Telegram Bot API wire format — shared message type. Module-private types
|
|
2
|
+
// (config, updates, file infos, etc.) live with their owners.
|
|
3
|
+
|
|
4
|
+
interface TelegramUser {
|
|
5
|
+
id: number;
|
|
6
|
+
is_bot: boolean;
|
|
7
|
+
first_name: string;
|
|
8
|
+
username?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface TelegramChat {
|
|
12
|
+
id: number;
|
|
13
|
+
type: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface TelegramPhotoSize {
|
|
17
|
+
file_id: string;
|
|
18
|
+
file_size?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface TelegramDocument {
|
|
22
|
+
file_id: string;
|
|
23
|
+
file_name?: string;
|
|
24
|
+
mime_type?: string;
|
|
25
|
+
file_size?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface TelegramVideo {
|
|
29
|
+
file_id: string;
|
|
30
|
+
file_name?: string;
|
|
31
|
+
mime_type?: string;
|
|
32
|
+
file_size?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface TelegramAudio {
|
|
36
|
+
file_id: string;
|
|
37
|
+
file_name?: string;
|
|
38
|
+
mime_type?: string;
|
|
39
|
+
file_size?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface TelegramVoice {
|
|
43
|
+
file_id: string;
|
|
44
|
+
mime_type?: string;
|
|
45
|
+
file_size?: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface TelegramAnimation {
|
|
49
|
+
file_id: string;
|
|
50
|
+
file_name?: string;
|
|
51
|
+
mime_type?: string;
|
|
52
|
+
file_size?: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface TelegramSticker {
|
|
56
|
+
file_id: string;
|
|
57
|
+
emoji?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TelegramMessage {
|
|
61
|
+
message_id: number;
|
|
62
|
+
chat: TelegramChat;
|
|
63
|
+
from?: TelegramUser;
|
|
64
|
+
text?: string;
|
|
65
|
+
caption?: string;
|
|
66
|
+
media_group_id?: string;
|
|
67
|
+
photo?: TelegramPhotoSize[];
|
|
68
|
+
document?: TelegramDocument;
|
|
69
|
+
video?: TelegramVideo;
|
|
70
|
+
audio?: TelegramAudio;
|
|
71
|
+
voice?: TelegramVoice;
|
|
72
|
+
animation?: TelegramAnimation;
|
|
73
|
+
sticker?: TelegramSticker;
|
|
74
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Pure helpers.
|
|
2
|
+
|
|
3
|
+
import { extname } from "node:path";
|
|
4
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
5
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
6
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
|
|
8
|
+
export function sanitizeFileName(name: string): string {
|
|
9
|
+
return name.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function guessExtensionFromMime(mimeType: string | undefined, fallback: string): string {
|
|
13
|
+
if (!mimeType) return fallback;
|
|
14
|
+
const normalized = mimeType.toLowerCase();
|
|
15
|
+
if (normalized === "image/jpeg") return ".jpg";
|
|
16
|
+
if (normalized === "image/png") return ".png";
|
|
17
|
+
if (normalized === "image/webp") return ".webp";
|
|
18
|
+
if (normalized === "image/gif") return ".gif";
|
|
19
|
+
if (normalized === "audio/ogg") return ".ogg";
|
|
20
|
+
if (normalized === "audio/mpeg") return ".mp3";
|
|
21
|
+
if (normalized === "audio/wav") return ".wav";
|
|
22
|
+
if (normalized === "video/mp4") return ".mp4";
|
|
23
|
+
if (normalized === "application/pdf") return ".pdf";
|
|
24
|
+
return fallback;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function guessMediaType(path: string): string | undefined {
|
|
28
|
+
const ext = extname(path).toLowerCase();
|
|
29
|
+
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
|
|
30
|
+
if (ext === ".png") return "image/png";
|
|
31
|
+
if (ext === ".webp") return "image/webp";
|
|
32
|
+
if (ext === ".gif") return "image/gif";
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function isImageMimeType(mimeType: string | undefined): boolean {
|
|
37
|
+
return mimeType?.toLowerCase().startsWith("image/") ?? false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function formatTokens(count: number): string {
|
|
41
|
+
if (count < 1000) return count.toString();
|
|
42
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
43
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
44
|
+
if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
|
|
45
|
+
return `${Math.round(count / 1000000)}M`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function isAssistantMessage(message: AgentMessage | undefined): message is AssistantMessage {
|
|
49
|
+
return message?.role === "assistant";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const SECTION_MARKER: Record<"text" | "thinking", string> = {
|
|
53
|
+
text: "✏️\n",
|
|
54
|
+
thinking: "💭\n",
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Render an assistant message's content blocks to text. Thinking blocks are
|
|
58
|
+
* prefixed with 💭, text after thinking with ✏️, so the boundary is
|
|
59
|
+
* visible in chat. */
|
|
60
|
+
export function getMessageText(message: AssistantMessage): string {
|
|
61
|
+
const parts: string[] = [];
|
|
62
|
+
let prevType: "text" | "thinking" = "text";
|
|
63
|
+
for (const block of message.content) {
|
|
64
|
+
if (block.type !== "text" && block.type !== "thinking") continue;
|
|
65
|
+
const marker = block.type === prevType ? "" : SECTION_MARKER[block.type];
|
|
66
|
+
parts.push(marker + (block.type === "text" ? block.text : block.thinking));
|
|
67
|
+
prevType = block.type;
|
|
68
|
+
}
|
|
69
|
+
return parts.join("\n\n").trim();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Answer text (text blocks only, thinking excluded) of the most recent
|
|
73
|
+
* assistant message on a branch that produced any, or undefined. */
|
|
74
|
+
export function lastAssistantText(branch: SessionEntry[]): string | undefined {
|
|
75
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
76
|
+
const entry = branch[i];
|
|
77
|
+
if (entry?.type !== "message" || !isAssistantMessage(entry.message)) continue;
|
|
78
|
+
const text = answerText(entry.message);
|
|
79
|
+
if (text) return text;
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Like getMessageText, but answer-only — thinking blocks are dropped. */
|
|
85
|
+
function answerText(message: AssistantMessage): string {
|
|
86
|
+
return message.content
|
|
87
|
+
.filter((block) => block.type === "text")
|
|
88
|
+
.map((block) => block.text)
|
|
89
|
+
.join("\n\n")
|
|
90
|
+
.trim();
|
|
91
|
+
}
|