@qusic/pi-telegram 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,237 @@
1
+ // Routes incoming Telegram messages: built-in slash commands first, then
2
+ // fall through to the agent as a regular turn.
3
+ //
4
+ // /new and /resume <n> need ctx.newSession() / switchSession(), which only
5
+ // exist on ExtensionCommandContext. dispatch's ctx is a regular
6
+ // ExtensionContext (event handler), so we stash a closure in `pendingAction`
7
+ // and fire `/telegram-execute-action` to bounce through a registered command
8
+ // handler whose ctx has the right type.
9
+
10
+ import type {
11
+ ExtensionAPI,
12
+ ExtensionCommandContext,
13
+ ExtensionContext,
14
+ SessionInfo,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
17
+ import { type createApi, MAX_MESSAGE_LENGTH } from "./api.ts";
18
+ import type { createTurn } from "./turn.ts";
19
+ import type { TelegramMessage } from "./types.ts";
20
+ import { formatTokens, lastAssistantText } from "./utils.ts";
21
+
22
+ type Dispatcher = (messages: TelegramMessage[], ctx: ExtensionContext) => Promise<void>;
23
+
24
+ type PendingTelegramAction = (ctx: ExtensionCommandContext) => Promise<void>;
25
+
26
+ /** Commands published to the Telegram bot menu at boot. */
27
+ const BOT_COMMANDS = [
28
+ { command: "new", description: "Start a new session" },
29
+ { command: "resume", description: "List or resume sessions: /resume [n]" },
30
+ { command: "stop", description: "Abort current turn" },
31
+ { command: "status", description: "Show usage info" },
32
+ { command: "compact", description: "Compact conversation" },
33
+ { command: "skills", description: "List available skills" },
34
+ ];
35
+
36
+ interface DispatcherDeps {
37
+ pi: ExtensionAPI;
38
+ api: ReturnType<typeof createApi>;
39
+ turn: ReturnType<typeof createTurn>;
40
+ }
41
+
42
+ export function createDispatcher(deps: DispatcherDeps): Dispatcher {
43
+ const { pi, api, turn } = deps;
44
+
45
+ // Cache last /resume listing for index lookup; per-closure (cleared on session swap).
46
+ let lastList: SessionInfo[] | undefined;
47
+
48
+ // Closure queued by /new or /resume <n>, drained by /telegram-execute-action.
49
+ let pendingAction: PendingTelegramAction | undefined;
50
+
51
+ pi.registerCommand("telegram-execute-action", {
52
+ description: "(internal) execute a queued Telegram-initiated session action",
53
+ handler: async (_args, ctx) => {
54
+ const action = pendingAction;
55
+ pendingAction = undefined;
56
+ if (action) await action(ctx);
57
+ },
58
+ });
59
+
60
+ /** Bounce through a registered command so the handler gets an
61
+ * ExtensionCommandContext (with newSession/switchSession). Opt into
62
+ * command dispatch so the internal command is not sent to the LLM. */
63
+ function trampoline(action: PendingTelegramAction): void {
64
+ pendingAction = action;
65
+ pi.sendUserMessage("/telegram-execute-action", { expandPromptTemplates: true });
66
+ }
67
+
68
+ // Publish the bot menu once. Telegram persists this server-side; a network
69
+ // blip just leaves the previous menu in place.
70
+ void api.call("setMyCommands", { commands: BOT_COMMANDS }).catch(() => {});
71
+
72
+ return async function dispatch(messages, ctx) {
73
+ const firstMessage = messages[0];
74
+ if (!firstMessage) return;
75
+ const rawText = messages.map((m) => (m.text || m.caption || "").trim()).find((t) => t.length > 0) || "";
76
+ const lower = rawText.toLowerCase();
77
+ const reply = (text: string) => api.sendText(firstMessage.chat.id, text);
78
+ const requireIdle = async (action: string): Promise<boolean> => {
79
+ if (ctx.isIdle()) return true;
80
+ await reply(`Cannot ${action} while pi is busy. Send /stop first.`);
81
+ return false;
82
+ };
83
+
84
+ if (lower === "/new") {
85
+ if (!(await requireIdle("start new session"))) return;
86
+ trampoline(async (cmdCtx) => {
87
+ const result = await cmdCtx.newSession();
88
+ await reply(result.cancelled ? "New session cancelled." : "✅ New session started.");
89
+ });
90
+ return;
91
+ }
92
+
93
+ if (lower === "/resume") {
94
+ const cwd = ctx.sessionManager.getCwd();
95
+ const all = await SessionManager.list(cwd);
96
+ const currentFile = ctx.sessionManager.getSessionFile();
97
+ lastList = all.slice(0, 20);
98
+ if (lastList.length === 0) {
99
+ await reply("No sessions found.");
100
+ return;
101
+ }
102
+ const lines = lastList.map((s, i) => {
103
+ const marker = s.path === currentFile ? "● " : "";
104
+ const date = s.modified.toLocaleString(undefined, {
105
+ month: "short",
106
+ day: "numeric",
107
+ hour: "2-digit",
108
+ minute: "2-digit",
109
+ });
110
+ const title = (s.name || s.firstMessage).replace(/\s+/g, " ").slice(0, 60);
111
+ return `- ${marker}/resume${i + 1} — ${code(title)} · ${s.messageCount} msg · ${date}`;
112
+ });
113
+ await reply(section("**Sessions** — tap to switch", lines));
114
+ return;
115
+ }
116
+
117
+ const resumeNumber = lower.match(/^\/resume\s*(\d+)$/)?.[1];
118
+ if (resumeNumber !== undefined) {
119
+ if (!(await requireIdle("resume"))) return;
120
+ const idx = parseInt(resumeNumber, 10) - 1;
121
+ const target = lastList?.[idx];
122
+ if (!target) {
123
+ await reply("Invalid index. Run /resume to list sessions first.");
124
+ return;
125
+ }
126
+ const label = (target.name || target.firstMessage).replace(/\s+/g, " ").slice(0, 80);
127
+ trampoline(async (cmdCtx) => {
128
+ // Within the resumed session's context, grab its last reply to mirror to the chat.
129
+ let recap: string | undefined;
130
+ const result = await cmdCtx.switchSession(target.path, {
131
+ withSession: async (newCtx) => {
132
+ recap = lastAssistantText(newCtx.sessionManager.getBranch());
133
+ },
134
+ });
135
+ if (result.cancelled) {
136
+ await reply("Resume cancelled.");
137
+ return;
138
+ }
139
+ await reply(`✅ Resumed: ${code(label)}`);
140
+ if (recap) await api.sendText(firstMessage.chat.id, truncateRecap(recap));
141
+ });
142
+ return;
143
+ }
144
+
145
+ if (lower === "/stop") {
146
+ const hadActive = turn.abort();
147
+ await reply(hadActive ? "Aborted current turn." : "No active turn.");
148
+ return;
149
+ }
150
+
151
+ if (lower === "/status") {
152
+ await reply(buildStatusReport(ctx));
153
+ return;
154
+ }
155
+
156
+ if (lower === "/compact") {
157
+ if (!(await requireIdle("compact"))) return;
158
+ ctx.compact({
159
+ onComplete: () => {
160
+ void reply("✅ Compaction completed.");
161
+ },
162
+ onError: (error) => {
163
+ const message = error instanceof Error ? error.message : String(error);
164
+ void reply(`⚠️ Compaction failed: ${message}`);
165
+ },
166
+ });
167
+ await reply("⏳ Compaction started…");
168
+ return;
169
+ }
170
+
171
+ if (lower === "/skills") {
172
+ const skills = pi
173
+ .getCommands()
174
+ .filter((cmd) => cmd.source === "skill")
175
+ .map((cmd) => `- /${cmd.name} — ${cmd.description || "no description"}`);
176
+ await reply(skills.length > 0 ? section("**Skills**", skills) : "No skills available.");
177
+ return;
178
+ }
179
+
180
+ // Default: forward as a regular agent turn.
181
+ await turn.handleIncoming(messages, ctx);
182
+ };
183
+ }
184
+
185
+ // Keep the tail (the conclusion matters most) and flag the cut; full history is in the TUI.
186
+ function truncateRecap(text: string): string {
187
+ if (text.length <= MAX_MESSAGE_LENGTH) return text;
188
+ const notice = "…(truncated — open the TUI for full history)\n\n";
189
+ return notice + text.slice(-(MAX_MESSAGE_LENGTH - notice.length)).trimStart();
190
+ }
191
+
192
+ // Inline-code dynamic text (model ids, titles, costs) so Rich Message markdown
193
+ // can't mis-parse it; backticks are neutralized.
194
+ function code(text: string): string {
195
+ return `\`${text.replaceAll("`", "ʼ")}\``;
196
+ }
197
+
198
+ /** A titled message: heading, blank line, then body lines. */
199
+ function section(heading: string, body: string[]): string {
200
+ return [heading, "", ...body].join("\n");
201
+ }
202
+
203
+ function buildStatusReport(ctx: ExtensionContext): string {
204
+ let totalInput = 0,
205
+ totalOutput = 0,
206
+ totalCacheRead = 0,
207
+ totalCacheWrite = 0,
208
+ totalCost = 0;
209
+ for (const entry of ctx.sessionManager.getEntries()) {
210
+ if (entry.type !== "message" || entry.message.role !== "assistant") continue;
211
+ totalInput += entry.message.usage.input;
212
+ totalOutput += entry.message.usage.output;
213
+ totalCacheRead += entry.message.usage.cacheRead;
214
+ totalCacheWrite += entry.message.usage.cacheWrite;
215
+ totalCost += entry.message.usage.cost.total;
216
+ }
217
+ const usage = ctx.getContextUsage();
218
+ const rows: string[] = [];
219
+ if (ctx.model) rows.push(`- **Model** — ${code(`${ctx.model.provider}/${ctx.model.id}`)}`);
220
+ const tokenParts: string[] = [];
221
+ if (totalInput) tokenParts.push(`↑${formatTokens(totalInput)}`);
222
+ if (totalOutput) tokenParts.push(`↓${formatTokens(totalOutput)}`);
223
+ if (totalCacheRead) tokenParts.push(`R${formatTokens(totalCacheRead)}`);
224
+ if (totalCacheWrite) tokenParts.push(`W${formatTokens(totalCacheWrite)}`);
225
+ if (tokenParts.length > 0) rows.push(`- **Tokens** — ${tokenParts.join(" ")}`);
226
+ const usingSubscription = ctx.model ? ctx.modelRegistry.isUsingOAuth(ctx.model) : false;
227
+ if (totalCost || usingSubscription)
228
+ rows.push(`- **Cost** — ${code(`$${totalCost.toFixed(3)}`)}${usingSubscription ? " · sub" : ""}`);
229
+ if (usage) {
230
+ const contextWindow = usage.contextWindow ?? ctx.model?.contextWindow ?? 0;
231
+ const percent = usage.percent !== null ? `${usage.percent.toFixed(1)}%` : "?";
232
+ rows.push(`- **Context** — ${percent} / ${formatTokens(contextWindow)}`);
233
+ } else {
234
+ rows.push("- **Context** — unknown");
235
+ }
236
+ return rows.length === 0 ? "No usage data yet." : section("**Status**", rows);
237
+ }
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
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.
3
+
4
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+ import { createApi } from "./api.ts";
6
+ import { createConfig } from "./config.ts";
7
+ import { createDispatcher } from "./dispatch.ts";
8
+ import { createMedia } from "./media.ts";
9
+ import { createPolling } from "./polling.ts";
10
+ import { createPreview } from "./preview.ts";
11
+ import { createTurn } from "./turn.ts";
12
+
13
+ export default async function (pi: ExtensionAPI) {
14
+ const config = await createConfig();
15
+ const api = createApi(config);
16
+ const preview = createPreview(api);
17
+ const media = createMedia(api);
18
+ const turn = createTurn({ pi, api, media, preview });
19
+ const dispatch = createDispatcher({ pi, api, turn });
20
+ createPolling({ pi, api, config, dispatch });
21
+ }
package/src/media.ts ADDED
@@ -0,0 +1,142 @@
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 on agent_end. */
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
+ }
package/src/polling.ts ADDED
@@ -0,0 +1,152 @@
1
+ // Long-poll loop against getUpdates, with media-group debouncing and
2
+ // authorization filtering. Self-registers session_start/shutdown handlers.
3
+
4
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import type { createApi } from "./api.ts";
6
+ import type { createConfig } from "./config.ts";
7
+ import type { createDispatcher } from "./dispatch.ts";
8
+ import type { TelegramMessage } from "./types.ts";
9
+
10
+ const TELEGRAM_MEDIA_GROUP_DEBOUNCE_MS = 1200;
11
+
12
+ interface TelegramUpdate {
13
+ update_id: number;
14
+ message?: TelegramMessage;
15
+ edited_message?: TelegramMessage;
16
+ }
17
+
18
+ interface TelegramMediaGroupState {
19
+ messages: TelegramMessage[];
20
+ flushTimer?: ReturnType<typeof setTimeout>;
21
+ }
22
+
23
+ interface PollingDeps {
24
+ pi: ExtensionAPI;
25
+ api: ReturnType<typeof createApi>;
26
+ config: Awaited<ReturnType<typeof createConfig>>;
27
+ dispatch: ReturnType<typeof createDispatcher>;
28
+ }
29
+
30
+ export function createPolling(deps: PollingDeps): void {
31
+ const { pi, api, config, dispatch } = deps;
32
+
33
+ let controller: AbortController | undefined;
34
+ const mediaGroups = new Map<string, TelegramMediaGroupState>();
35
+
36
+ function stop(): void {
37
+ controller?.abort();
38
+ controller = undefined;
39
+ // Don't await pollLoop — stop() may be called from inside its own call
40
+ // stack (e.g. /new from Telegram triggers session_shutdown via pollLoop).
41
+ // The aborted signal lets pollLoop exit on its next iteration.
42
+ for (const group of mediaGroups.values()) {
43
+ if (group.flushTimer) clearTimeout(group.flushTimer);
44
+ }
45
+ mediaGroups.clear();
46
+ }
47
+
48
+ function start(ctx: ExtensionContext): void {
49
+ if (controller) return;
50
+ controller = new AbortController();
51
+ void pollLoop(ctx, controller.signal).finally(() => {
52
+ controller = undefined;
53
+ });
54
+ }
55
+
56
+ async function pollLoop(ctx: ExtensionContext, signal: AbortSignal): Promise<void> {
57
+ if (config.get().lastUpdateId === undefined) {
58
+ try {
59
+ const updates = await api.call<TelegramUpdate[]>(
60
+ "getUpdates",
61
+ { offset: -1, limit: 1, timeout: 0 },
62
+ { signal },
63
+ );
64
+ const last = updates.at(-1);
65
+ if (last) await config.update({ lastUpdateId: last.update_id });
66
+ } catch {
67
+ // ignore
68
+ }
69
+ }
70
+
71
+ while (!signal.aborted) {
72
+ try {
73
+ const lastSeen = config.get().lastUpdateId;
74
+ const updates = await api.call<TelegramUpdate[]>(
75
+ "getUpdates",
76
+ {
77
+ offset: lastSeen !== undefined ? lastSeen + 1 : undefined,
78
+ limit: 10,
79
+ timeout: 30,
80
+ allowed_updates: ["message", "edited_message"],
81
+ },
82
+ { signal },
83
+ );
84
+ for (const update of updates) {
85
+ await config.update({ lastUpdateId: update.update_id });
86
+ await handleUpdate(update, ctx);
87
+ }
88
+ } catch (error) {
89
+ if (signal.aborted) return;
90
+ if (error instanceof DOMException && error.name === "AbortError") return;
91
+ // Not aborted → no session swap in progress → ctx is still live.
92
+ const message = error instanceof Error ? error.message : String(error);
93
+ ctx.ui.setStatus("telegram", `⚠ ${message}`);
94
+ await new Promise((resolve) => setTimeout(resolve, 3000));
95
+ ctx.ui.setStatus("telegram", undefined);
96
+ }
97
+ }
98
+ }
99
+
100
+ 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;
103
+
104
+ const cfg = config.get();
105
+ 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.");
113
+ return;
114
+ }
115
+
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
+ }
120
+
121
+ // Albums arrive as separate updates with the same media_group_id; debounce.
122
+ if (message.media_group_id) {
123
+ const key = `${message.chat.id}:${message.media_group_id}`;
124
+ const existing = mediaGroups.get(key) ?? { messages: [] as TelegramMessage[] };
125
+ existing.messages.push(message);
126
+ if (existing.flushTimer) clearTimeout(existing.flushTimer);
127
+ existing.flushTimer = setTimeout(() => {
128
+ const group = mediaGroups.get(key);
129
+ mediaGroups.delete(key);
130
+ if (group) void dispatch(group.messages, ctx);
131
+ }, TELEGRAM_MEDIA_GROUP_DEBOUNCE_MS);
132
+ mediaGroups.set(key, existing);
133
+ return;
134
+ }
135
+
136
+ await dispatch([message], ctx);
137
+ }
138
+
139
+ // ---------- pi handler registration ----------
140
+
141
+ 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.
144
+ start(ctx);
145
+ });
146
+
147
+ pi.on("session_shutdown", (_event, _ctx) => {
148
+ // Always abort: pi reloads the extension on every session swap, and a
149
+ // lingering pollLoop would race with the new closure on getUpdates.
150
+ stop();
151
+ });
152
+ }