Repository navigation
Expand file tree
/
Copy pathbot.ts
More file actions
518 lines (443 loc) Β· 13.1 KB
/
Copy pathbot.ts
File metadata and controls
518 lines (443 loc) Β· 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import { spawn } from "node:child_process";
import { Bot, InlineKeyboard, InputFile } from "grammy";
import type { Config } from "./config.js";
import { detectFiles, snapshotWorkspace } from "./file-detector.js";
import { markdownToHtml, stripMarkdown } from "./markdown.js";
import {
type ActivityUpdate,
acquireLock,
checkPiAuth,
runPiWithStreaming,
} from "./pi-runner.js";
import { checkRateLimit } from "./rate-limiter.js";
import {
archiveSession,
cleanupOldSessions,
clearActiveSession,
formatFileSize,
formatSessionAge,
generateSessionTitle,
listSessions,
switchSession,
} from "./sessions.js";
import { formatPath, getWorkspace, setWorkspace } from "./workspace.js";
interface ShellResult {
stdout: string;
stderr: string;
code: number | null;
}
async function runShell(
cmd: string,
cwd: string,
timeoutMs: number,
): Promise<ShellResult> {
return new Promise((resolve) => {
const proc = spawn("bash", ["-c", cmd], {
cwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
proc.stdout.on("data", (data) => {
stdout += data.toString();
});
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
proc.on("close", (code) => {
resolve({ stdout, stderr, code });
});
proc.on("error", (err) => {
resolve({ stdout: "", stderr: err.message, code: 1 });
});
setTimeout(() => {
proc.kill("SIGTERM");
resolve({ stdout, stderr: `${stderr}\n(timeout)`, code: 124 });
}, timeoutMs);
});
}
const MAX_MESSAGE_LENGTH = 4096;
function splitMessage(text: string): string[] {
if (text.length <= MAX_MESSAGE_LENGTH) {
return [text];
}
const chunks: string[] = [];
let remaining = text;
while (remaining.length > 0) {
if (remaining.length <= MAX_MESSAGE_LENGTH) {
chunks.push(remaining);
break;
}
// Try to split at newline
let splitIndex = remaining.lastIndexOf("\n", MAX_MESSAGE_LENGTH);
if (splitIndex === -1 || splitIndex < MAX_MESSAGE_LENGTH / 2) {
// Fall back to space
splitIndex = remaining.lastIndexOf(" ", MAX_MESSAGE_LENGTH);
}
if (splitIndex === -1 || splitIndex < MAX_MESSAGE_LENGTH / 2) {
// Hard split
splitIndex = MAX_MESSAGE_LENGTH;
}
chunks.push(remaining.slice(0, splitIndex));
remaining = remaining.slice(splitIndex).trimStart();
}
return chunks;
}
export function createBot(config: Config): Bot {
const bot = new Bot(config.telegramToken);
// Access control middleware
if (config.allowedUsers.length > 0) {
bot.use(async (ctx, next) => {
const userId = ctx.from?.id;
if (userId && config.allowedUsers.includes(userId)) {
await next();
} else {
await ctx.reply("Sorry, you are not authorized to use this bot.");
}
});
}
// Command descriptions for menu
const commands = [
{ command: "start", description: "Welcome & quick start" },
{ command: "help", description: "Show all commands" },
{ command: "pwd", description: "Show current directory" },
{ command: "cd", description: "Change directory" },
{ command: "home", description: "Go to home directory" },
{ command: "shell", description: "Run shell command" },
{ command: "session", description: "Manage sessions" },
{ command: "new", description: "Start fresh conversation" },
{ command: "status", description: "Show bot status" },
];
// Set bot command menu
bot.api.setMyCommands(commands).catch(() => {
// Ignore errors (might not have permission)
});
// /start command
bot.command("start", async (ctx) => {
const piOk = await checkPiAuth();
const status = piOk
? "Pi is ready"
: "Pi is not installed or not authenticated";
const cwd = await getWorkspace(ctx.chat.id);
await ctx.reply(
`Welcome to Mini-Claw!
${status}
Working directory: ${formatPath(cwd)}
Type /help for all commands.
Send any message to chat with AI.`,
);
});
// /help command
bot.command("help", async (ctx) => {
await ctx.reply(
`π Mini-Claw Commands
π Navigation:
/pwd - Show current directory
/cd <path> - Change directory
/home - Go to home directory
π§ Execution:
/shell <cmd> - Run shell command directly
π¬ Sessions:
/session - List & manage sessions
/new - Archive current & start fresh
π Info:
/status - Show bot status
/help - Show this message
π‘ Tips:
β’ Any text β AI conversation
β’ /shell runs instantly, no AI
β’ /cd supports ~, .., relative paths`,
);
});
// /pwd command
bot.command("pwd", async (ctx) => {
const cwd = await getWorkspace(ctx.chat.id);
await ctx.reply(`π ${formatPath(cwd)}`);
});
// /home command
bot.command("home", async (ctx) => {
try {
const cwd = await setWorkspace(ctx.chat.id, "~");
await ctx.reply(`π ${formatPath(cwd)}`);
} catch (err) {
const msg = err instanceof Error ? err.message : "Unknown error";
await ctx.reply(`Error: ${msg}`);
}
});
// /cd command
bot.command("cd", async (ctx) => {
const path = ctx.match?.trim();
if (!path) {
// No argument = go home
try {
const cwd = await setWorkspace(ctx.chat.id, "~");
await ctx.reply(`π ${formatPath(cwd)}`);
} catch (err) {
const msg = err instanceof Error ? err.message : "Unknown error";
await ctx.reply(`Error: ${msg}`);
}
return;
}
try {
const cwd = await setWorkspace(ctx.chat.id, path);
await ctx.reply(`π ${formatPath(cwd)}`);
} catch (err) {
const msg = err instanceof Error ? err.message : "Unknown error";
await ctx.reply(`Error: ${msg}`);
}
});
// /new command - start fresh session
bot.command("new", async (ctx) => {
// Must wait for any ongoing Pi execution to complete first
// Otherwise Pi will recreate the session file after we rename it
const release = await acquireLock(ctx.chat.id);
try {
const archived = await archiveSession(config, ctx.chat.id);
// Clear active session tracking for truly fresh start
await clearActiveSession(ctx.chat.id);
if (archived) {
await ctx.reply(
`Session archived as ${archived}\nStarting fresh conversation.`,
);
} else {
await ctx.reply("Starting fresh conversation.");
}
} finally {
release();
}
});
// /status command
bot.command("status", async (ctx) => {
const piOk = await checkPiAuth();
const cwd = await getWorkspace(ctx.chat.id);
await ctx.reply(
`Status:
- Pi: ${piOk ? "OK" : "Not available"}
- Chat ID: ${ctx.chat.id}
- Workspace: ${formatPath(cwd)}`,
);
});
// /shell command - run shell command in current directory
bot.command("shell", async (ctx) => {
const cmd = ctx.match?.trim();
if (!cmd) {
await ctx.reply("Usage: /shell <command>\nExample: /shell ls -la");
return;
}
const cwd = await getWorkspace(ctx.chat.id);
await ctx.replyWithChatAction("typing");
try {
const result = await runShell(cmd, cwd, config.shellTimeoutMs);
let output = "";
if (result.stdout) {
output += result.stdout;
}
if (result.stderr) {
output += `${output ? "\n" : ""}stderr: ${result.stderr}`;
}
if (!output) {
output = "(no output)";
}
// Add exit code if non-zero
if (result.code !== 0) {
output += `\n\n[exit code: ${result.code}]`;
}
// Split long output
const chunks = splitMessage(output.trim());
for (const chunk of chunks) {
await ctx.reply(chunk);
}
} catch (err) {
const msg = err instanceof Error ? err.message : "Unknown error";
await ctx.reply(`Error: ${msg}`);
}
});
// /session command - list and manage sessions
bot.command("session", async (ctx) => {
await ctx.replyWithChatAction("typing");
const sessions = await listSessions(config);
if (sessions.length === 0) {
await ctx.reply("No sessions found.");
return;
}
// Generate titles for sessions (in parallel, max 5)
const sessionsWithTitles = await Promise.all(
sessions.slice(0, 10).map(async (session) => {
const title = await generateSessionTitle(
session.path,
config.sessionTitleTimeoutMs,
);
return { ...session, title };
}),
);
// Build inline keyboard
const keyboard = new InlineKeyboard();
for (const session of sessionsWithTitles) {
const age = formatSessionAge(session.modifiedAt);
const size = formatFileSize(session.sizeBytes);
const label = `${session.title} (${age}, ${size})`;
// Callback data format: session:load:<filename>
keyboard.text(label, `session:load:${session.filename}`).row();
}
// Add cleanup button
keyboard.text("π Clean Up Old Sessions", "session:cleanup").row();
await ctx.reply(
`π Sessions (${sessions.length} total)\n\nTap to switch session:`,
{ reply_markup: keyboard },
);
});
// Handle callback queries for session buttons
bot.callbackQuery(/^session:load:(.+)$/, async (ctx) => {
const filename = ctx.match[1];
const chatId = ctx.chat?.id;
if (!chatId) {
await ctx.answerCallbackQuery({ text: "Error: No chat ID" });
return;
}
try {
await switchSession(config, chatId, filename);
await ctx.answerCallbackQuery({ text: "Session switched!" });
await ctx.editMessageText(`β
Switched to session: ${filename}`);
} catch (err) {
const msg = err instanceof Error ? err.message : "Unknown error";
await ctx.answerCallbackQuery({
text: `Error: ${msg}`,
show_alert: true,
});
}
});
bot.callbackQuery("session:cleanup", async (ctx) => {
await ctx.answerCallbackQuery({ text: "Cleaning up..." });
const deleted = await cleanupOldSessions(config, 5);
await ctx.editMessageText(
`π Cleanup complete!\nDeleted ${deleted} old session(s).\nKept the 5 most recent sessions per chat.`,
);
});
// Handle all text messages
bot.on("message:text", async (ctx) => {
const chatId = ctx.chat.id;
const text = ctx.message.text;
// Skip commands
if (text.startsWith("/")) {
return;
}
// Rate limiting check
const rateLimit = checkRateLimit(chatId, config.rateLimitCooldownMs);
if (!rateLimit.allowed) {
const seconds = Math.ceil((rateLimit.retryAfterMs || 0) / 1000);
await ctx.reply(
`β³ Please wait ${seconds}s before sending another message.`,
);
return;
}
// Get current workspace for this chat
const workspace = await getWorkspace(chatId);
// Snapshot workspace before Pi execution
const beforeSnapshot = await snapshotWorkspace(workspace);
// Send initial status message that we'll update
const statusMsg = await ctx.reply("π Working...");
let lastStatusUpdate = Date.now();
// Activity emoji mapping
const activityEmoji: Record<string, string> = {
thinking: "π§ ",
reading: "π",
writing: "βοΈ",
running: "β‘",
searching: "π",
working: "π",
};
// Format status message
const formatStatus = (activity: ActivityUpdate): string => {
const emoji = activityEmoji[activity.type] || "π";
const elapsed = `${activity.elapsed}s`;
const detail = activity.detail ? `\nββ ${activity.detail}` : "";
return `${emoji} Working... (${elapsed})${detail}`;
};
// Activity callback - update status message
const (activity: ActivityUpdate) => {
// Throttle updates to avoid rate limits (max once per 2 seconds)
const now = Date.now();
if (now - lastStatusUpdate < 2000) return;
lastStatusUpdate = now;
try {
await ctx.api.editMessageText(
chatId,
statusMsg.message_id,
formatStatus(activity),
);
} catch {
// Ignore edit errors (message might be deleted, or content unchanged)
}
};
// Keep typing indicator active
const typingInterval = setInterval(() => {
ctx.replyWithChatAction("typing").catch(() => {});
}, 4000);
try {
const result = await runPiWithStreaming(
config,
chatId,
text,
workspace,
onActivity,
);
clearInterval(typingInterval);
// Delete status message
try {
await ctx.api.deleteMessage(chatId, statusMsg.message_id);
} catch {
// Ignore delete errors
}
if (result.error) {
await ctx.reply(`Error: ${result.error}`);
}
if (result.output) {
// Try to send as HTML, fallback to plain text
const chunks = splitMessage(result.output.trim());
for (const chunk of chunks) {
try {
const html = markdownToHtml(chunk);
await ctx.reply(html, { parse_mode: "HTML" });
} catch {
// Fallback to plain text if HTML fails
await ctx.reply(stripMarkdown(chunk));
}
}
}
// Detect and send any files created by Pi
const detectedFiles = await detectFiles(
result.output || "",
workspace,
beforeSnapshot,
);
for (const file of detectedFiles) {
try {
if (file.type === "photo") {
await ctx.replyWithPhoto(new InputFile(file.path), {
caption: file.filename,
});
} else {
await ctx.replyWithDocument(new InputFile(file.path), {
caption: file.filename,
});
}
} catch {
// File might have been deleted or inaccessible
await ctx.reply(`(Could not send file: ${file.filename})`);
}
}
} catch (err) {
clearInterval(typingInterval);
// Try to delete status message on error too
try {
await ctx.api.deleteMessage(chatId, statusMsg.message_id);
} catch {
// Ignore
}
const errorMsg = err instanceof Error ? err.message : "Unknown error";
await ctx.reply(`Failed to process: ${errorMsg}`);
}
});
return bot;
}