@lovenyberg/ove 0.2.2 → 0.4.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,571 @@
1
+ import { parseMessage, buildContextualPrompt } from "./router";
2
+ import type { ParsedMessage } from "./router";
3
+ import { isAuthorized, getUserRepos, addRepo, addUser } from "./config";
4
+ import { parseSchedule } from "./schedule-parser";
5
+ import { logger } from "./logger";
6
+ import type { Config } from "./config";
7
+ import type { TaskQueue, Task } from "./queue";
8
+ import type { SessionStore } from "./sessions";
9
+ import type { ScheduleStore } from "./schedules";
10
+ import type { RepoRegistry } from "./repo-registry";
11
+ import type { IncomingMessage, EventAdapter, IncomingEvent } from "./adapters/types";
12
+ import type { AgentRunner } from "./runner";
13
+ import type { TraceStore } from "./trace";
14
+
15
+ export interface HandlerDeps {
16
+ config: Config;
17
+ queue: TaskQueue;
18
+ sessions: SessionStore;
19
+ schedules: ScheduleStore;
20
+ repoRegistry: RepoRegistry;
21
+ trace: TraceStore;
22
+ pendingReplies: Map<string, IncomingMessage>;
23
+ pendingEventReplies: Map<string, { adapter: EventAdapter; event: IncomingEvent }>;
24
+ runningProcesses: Map<string, { abort: AbortController; task: Task }>;
25
+ getRunner: (name?: string) => AgentRunner;
26
+ getRunnerForRepo: (repo: string) => AgentRunner;
27
+ getRepoInfo: (repoName: string) => { url: string; defaultBranch: string } | null;
28
+ }
29
+
30
+ const OVE_PERSONA = `You are Ove, a grumpy but deeply competent Swedish developer. You're modeled after the character from Fredrik Backman's "A Man Called Ove" — you complain about things, mutter about how people don't know what they're doing, but you always help and you always do excellent work. You have strong opinions about code quality.
31
+
32
+ Personality traits:
33
+ - Grumble before helping, but always help thoroughly
34
+ - Short, direct sentences. No fluff.
35
+ - Occasionally mutter about "nowadays people" or how things were better before
36
+ - Take pride in doing things properly — no shortcuts
37
+ - Reluctantly kind. You care more than you let on.
38
+ - Sprinkle in the occasional Swedish word (fan, för helvete, herregud, mja, nåväl, jo)
39
+
40
+ Keep the personality subtle in code output — don't let it interfere with code quality. The grumpiness goes in your commentary, not in the code itself. When doing code reviews or fixes, be thorough and meticulous like Ove would be.`;
41
+
42
+ export { OVE_PERSONA };
43
+
44
+ const PLATFORM_FORMAT_HINTS: Record<string, string> = {
45
+ telegram: "Format output for Telegram: use *bold* for emphasis, `code` for inline code, ```code blocks```. No markdown tables. Use simple bulleted lists with • instead. Keep it concise.",
46
+ slack: "Format output for Slack: use *bold*, no markdown tables. Use simple bulleted lists with • instead. Keep it concise.",
47
+ discord: "Format output for Discord: use **bold**, no wide tables. Use simple bulleted lists. Keep under 2000 chars.",
48
+ whatsapp: "Format output for WhatsApp: use *bold*, no markdown tables or code blocks. Use simple bulleted lists with • instead.",
49
+ cli: "Format output using markdown. Tables are fine.",
50
+ };
51
+
52
+ const MESSAGE_LIMITS: Record<string, number> = {
53
+ slack: 3900,
54
+ whatsapp: 60000,
55
+ cli: Infinity,
56
+ telegram: 4096,
57
+ discord: 2000,
58
+ };
59
+
60
+ export function splitAndReply(text: string, platform: string): string[] {
61
+ const limit = MESSAGE_LIMITS[platform] || 3900;
62
+ if (text.length <= limit) return [text];
63
+ const parts: string[] = [];
64
+ let remaining = text;
65
+ while (remaining.length > 0) {
66
+ if (remaining.length <= limit) {
67
+ parts.push(remaining);
68
+ break;
69
+ }
70
+ let splitAt = remaining.lastIndexOf("\n", limit);
71
+ if (splitAt < limit * 0.5) splitAt = limit;
72
+ parts.push(remaining.slice(0, splitAt));
73
+ remaining = remaining.slice(splitAt).replace(/^\n/, "");
74
+ }
75
+ return parts;
76
+ }
77
+
78
+ function resolveRepo(userId: string, hint: string | undefined, deps: HandlerDeps): string | null {
79
+ if (hint && deps.getRepoInfo(hint)) return hint;
80
+
81
+ const userRepos = getUserRepos(deps.config, userId);
82
+ const hasWildcard = userRepos.includes("*");
83
+
84
+ if (!hasWildcard && userRepos.length === 1) return userRepos[0];
85
+
86
+ if (hasWildcard || userRepos.length > 1) {
87
+ const repoNames = hasWildcard ? deps.repoRegistry.getAllNames() : userRepos;
88
+ if (repoNames.length === 1) return repoNames[0];
89
+ }
90
+
91
+ return null;
92
+ }
93
+
94
+ // --- Individual command handlers ---
95
+
96
+ async function handleClear(msg: IncomingMessage, deps: HandlerDeps) {
97
+ deps.sessions.clear(msg.userId);
98
+ await msg.reply("Conversation cleared.");
99
+ }
100
+
101
+ async function handleStatus(msg: IncomingMessage, deps: HandlerDeps) {
102
+ const userTasks = deps.queue.listByUser(msg.userId, 5);
103
+ const running = userTasks.find((t) => t.status === "running");
104
+
105
+ let reply: string;
106
+ if (running) {
107
+ const elapsed = Math.round((Date.now() - new Date(running.createdAt).getTime()) / 1000);
108
+ const min = Math.floor(elapsed / 60);
109
+ const sec = elapsed % 60;
110
+ const duration = min > 0 ? `${min}m ${sec}s` : `${sec}s`;
111
+ reply = `Working on ${running.repo} (${duration})...`;
112
+ } else {
113
+ const lastDone = userTasks.find((t) => t.status === "completed");
114
+ if (lastDone) {
115
+ reply = `Nothing running. Last task on ${lastDone.repo} completed.`;
116
+ } else {
117
+ const stats = deps.queue.stats();
118
+ reply = `${stats.pending} pending, ${stats.running} running, ${stats.completed} done, ${stats.failed} failed.`;
119
+ }
120
+ }
121
+ await msg.reply(reply);
122
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
123
+ }
124
+
125
+ async function handleHistory(msg: IncomingMessage, deps: HandlerDeps) {
126
+ const tasks = deps.queue.listByUser(msg.userId, 5);
127
+ if (tasks.length === 0) {
128
+ await msg.reply("No recent tasks.");
129
+ deps.sessions.addMessage(msg.userId, "assistant", "No recent tasks.");
130
+ return;
131
+ }
132
+ const lines = tasks.map(
133
+ (t) => `• [${t.status}] ${t.prompt.slice(0, 80)} (${t.repo})`
134
+ );
135
+ const reply = `Recent tasks:\n${lines.join("\n")}`;
136
+ await msg.reply(reply);
137
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
138
+ }
139
+
140
+ async function handleHelp(msg: IncomingMessage, deps: HandlerDeps) {
141
+ const reply = [
142
+ "Available commands:",
143
+ "• review PR #N on <repo> — I'll find every problem",
144
+ "• fix issue #N on <repo> — I'll fix it properly",
145
+ "• simplify <path> in <repo> — clean up your mess",
146
+ "• validate <repo> — run tests, unlike some people",
147
+ "• discuss <topic> — I'll brainstorm, but no promises I'll be nice",
148
+ "• create project <name> [with template <type>]",
149
+ "• init repo <name> <git-url> [branch] — set up a repo from chat",
150
+ "• tasks — see running and pending tasks",
151
+ "• cancel <id> — kill a running or pending task",
152
+ "• trace [task-id] — see what happened step by step",
153
+ "• status / history / clear",
154
+ "• <task> every day/weekday at <time> [on <repo>] — schedule a recurring task",
155
+ "• list schedules — see your scheduled tasks",
156
+ "• remove schedule #N — remove a scheduled task",
157
+ "• Or just ask me whatever. I'll figure it out.",
158
+ ].join("\n");
159
+ await msg.reply(reply);
160
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
161
+ }
162
+
163
+ async function handleListTasks(msg: IncomingMessage, deps: HandlerDeps) {
164
+ const tasks = deps.queue.listActive();
165
+ if (tasks.length === 0) {
166
+ const reply = "Nothing running, nothing pending. Quiet. I like it.";
167
+ await msg.reply(reply);
168
+ return;
169
+ }
170
+ const running = tasks.filter((t) => t.status === "running");
171
+ const pending = tasks.filter((t) => t.status === "pending");
172
+ const lines: string[] = [];
173
+ if (running.length > 0) {
174
+ lines.push("Running:");
175
+ for (const t of running) {
176
+ const elapsed = Math.round((Date.now() - new Date(t.createdAt).getTime()) / 1000);
177
+ const min = Math.floor(elapsed / 60);
178
+ const sec = elapsed % 60;
179
+ const duration = min > 0 ? `${min}m ${sec}s` : `${sec}s`;
180
+ lines.push(` ${t.id.slice(0, 7)} — "${t.prompt.slice(0, 60)}" on ${t.repo} (${duration})`);
181
+ }
182
+ }
183
+ if (pending.length > 0) {
184
+ lines.push("Pending:");
185
+ for (const t of pending) {
186
+ const busyRepo = running.some((r) => r.repo === t.repo);
187
+ const reason = busyRepo ? `waiting — ${t.repo} busy` : "waiting";
188
+ lines.push(` ${t.id.slice(0, 7)} — "${t.prompt.slice(0, 60)}" on ${t.repo} (${reason})`);
189
+ }
190
+ }
191
+ const reply = lines.join("\n");
192
+ await msg.reply(reply);
193
+ }
194
+
195
+ async function handleCancelTask(msg: IncomingMessage, args: Record<string, any>, deps: HandlerDeps) {
196
+ const prefix = args.taskId.toLowerCase();
197
+ let match: { abort: AbortController; task: Task } | undefined;
198
+ for (const [id, entry] of deps.runningProcesses) {
199
+ if (id.toLowerCase().startsWith(prefix)) {
200
+ match = entry;
201
+ break;
202
+ }
203
+ }
204
+ if (!match) {
205
+ const active = deps.queue.listActive();
206
+ const pendingMatch = active.find((t) => t.id.toLowerCase().startsWith(prefix) && t.status === "pending");
207
+ if (pendingMatch) {
208
+ deps.queue.cancel(pendingMatch.id);
209
+ await msg.reply(`Cancelled pending task ${pendingMatch.id.slice(0, 7)} on ${pendingMatch.repo}.`);
210
+ return;
211
+ }
212
+ await msg.reply(`No task found matching "${prefix}". Use /tasks to see what's running.`);
213
+ return;
214
+ }
215
+ match.abort.abort();
216
+ deps.queue.cancel(match.task.id);
217
+ await msg.reply(`Killed task ${match.task.id.slice(0, 7)} on ${match.task.repo}. Gone.`);
218
+ }
219
+
220
+ async function handleListSchedules(msg: IncomingMessage, deps: HandlerDeps) {
221
+ const userSchedules = deps.schedules.listByUser(msg.userId);
222
+ if (userSchedules.length === 0) {
223
+ const reply = "No schedules. You haven't asked me to do anything on a timer yet.";
224
+ await msg.reply(reply);
225
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
226
+ return;
227
+ }
228
+ const lines = userSchedules.map(
229
+ (s) => `#${s.id} — ${s.prompt} on ${s.repo} — ${s.description || s.schedule}`
230
+ );
231
+ const reply = `Your schedules:\n${lines.join("\n")}`;
232
+ await msg.reply(reply);
233
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
234
+ }
235
+
236
+ async function handleRemoveSchedule(msg: IncomingMessage, args: Record<string, any>, deps: HandlerDeps) {
237
+ const id = args.scheduleId;
238
+ const removed = deps.schedules.remove(msg.userId, id);
239
+ const reply = removed
240
+ ? `Schedule #${id} removed. One less thing for me to do.`
241
+ : `Schedule #${id} not found or not yours. I don't delete other people's things.`;
242
+ await msg.reply(reply);
243
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
244
+ }
245
+
246
+ async function handleTrace(msg: IncomingMessage, args: Record<string, any>, deps: HandlerDeps) {
247
+ let taskId = args.taskId as string | undefined;
248
+
249
+ if (!taskId) {
250
+ const recent = deps.queue.listByUser(msg.userId, 1);
251
+ if (recent.length === 0) {
252
+ await msg.reply("No tasks found. Nothing to trace.");
253
+ return;
254
+ }
255
+ taskId = recent[0].id;
256
+ }
257
+
258
+ // Support prefix matching like cancel does
259
+ const task = deps.queue.get(taskId);
260
+ if (!task) {
261
+ await msg.reply(`No task found matching "${taskId}".`);
262
+ return;
263
+ }
264
+
265
+ const events = deps.trace.getByTask(task.id);
266
+ if (events.length === 0) {
267
+ const reason = deps.trace.isEnabled()
268
+ ? "No trace events recorded for this task."
269
+ : "Tracing is disabled. Set OVE_TRACE=true to enable.";
270
+ await msg.reply(reason);
271
+ return;
272
+ }
273
+
274
+ const lines = events.map((e) => {
275
+ const time = e.ts.slice(11, 19); // HH:MM:SS
276
+ const detail = e.detail ? ` — ${e.detail.slice(0, 120)}` : "";
277
+ return `${time} [${e.kind}] ${e.summary}${detail}`;
278
+ });
279
+
280
+ const reply = `Trace for ${task.id.slice(0, 7)} (${task.repo}):\n${lines.join("\n")}`;
281
+ await msg.reply(reply);
282
+ }
283
+
284
+ async function handleSchedule(msg: IncomingMessage, parsedRepo: string | undefined, deps: HandlerDeps) {
285
+ await msg.updateStatus("Parsing your schedule...");
286
+ const rawRepos = getUserRepos(deps.config, msg.userId);
287
+ const userRepos = rawRepos.includes("*") ? deps.repoRegistry.getAllNames() : rawRepos;
288
+
289
+ if (userRepos.length === 0) {
290
+ await msg.reply("You don't have access to any repos. Set one up first with `init repo <name> <git-url>`.");
291
+ return;
292
+ }
293
+
294
+ const result = await parseSchedule(msg.text, userRepos);
295
+
296
+ if (!result) {
297
+ await msg.reply("Couldn't figure out that schedule. Try something like: 'lint and check every day at 9 on my-app'");
298
+ deps.sessions.addMessage(msg.userId, "assistant", "Failed to parse schedule.");
299
+ return;
300
+ }
301
+
302
+ let repo = result.repo;
303
+ if (!repo || !userRepos.includes(repo)) {
304
+ if (parsedRepo && userRepos.includes(parsedRepo)) {
305
+ repo = parsedRepo;
306
+ } else if (userRepos.length === 1) {
307
+ repo = userRepos[0];
308
+ } else {
309
+ const reply = `Which repo? You have: ${userRepos.join(", ")}. Say it again with 'on <repo>'.`;
310
+ await msg.reply(reply);
311
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
312
+ return;
313
+ }
314
+ }
315
+
316
+ const id = deps.schedules.create({
317
+ userId: msg.userId,
318
+ repo,
319
+ prompt: result.prompt,
320
+ schedule: result.schedule,
321
+ description: result.description,
322
+ });
323
+
324
+ const reply = `Schedule #${id} created: "${result.prompt}" on ${repo} ${result.description}.`;
325
+ await msg.reply(reply);
326
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
327
+ }
328
+
329
+ async function handleDiscuss(msg: IncomingMessage, parsed: ParsedMessage, history: { role: string; content: string }[], deps: HandlerDeps) {
330
+ const prompt = buildContextualPrompt(parsed, history, OVE_PERSONA);
331
+
332
+ await msg.updateStatus("Thinking...");
333
+
334
+ try {
335
+ const discussRunner = deps.getRunner(deps.config.runner?.name);
336
+ const result = await discussRunner.run(
337
+ prompt,
338
+ deps.config.reposDir,
339
+ { maxTurns: 5 },
340
+ (event) => {
341
+ if (event.kind === "text") {
342
+ msg.updateStatus(event.text.slice(0, 200));
343
+ }
344
+ }
345
+ );
346
+
347
+ const parts = splitAndReply(result.output, msg.platform);
348
+ for (const part of parts) {
349
+ await msg.reply(part);
350
+ }
351
+ deps.sessions.addMessage(msg.userId, "assistant", result.output.slice(0, 500));
352
+ } catch (err) {
353
+ await msg.reply(`Discussion error: ${String(err).slice(0, 500)}`);
354
+ }
355
+ }
356
+
357
+ async function handleCreateProject(msg: IncomingMessage, parsed: ParsedMessage, history: { role: string; content: string }[], deps: HandlerDeps) {
358
+ const projectName = parsed.args.name;
359
+ const prompt = buildContextualPrompt(parsed, history, OVE_PERSONA);
360
+
361
+ const taskId = deps.queue.enqueue({
362
+ userId: msg.userId,
363
+ repo: projectName,
364
+ prompt,
365
+ taskType: "create-project",
366
+ });
367
+
368
+ deps.pendingReplies.set(taskId, msg);
369
+ await msg.reply(`Creating "${projectName}"...`);
370
+ logger.info("task enqueued", { taskId, type: "create-project", name: projectName });
371
+ }
372
+
373
+ async function handleInitRepo(msg: IncomingMessage, args: Record<string, any>, deps: HandlerDeps) {
374
+ const { name, url, branch } = args;
375
+
376
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
377
+ await msg.reply("Repo name must be alphanumeric, dashes, or underscores. Try again.");
378
+ return;
379
+ }
380
+
381
+ if (deps.config.repos[name]) {
382
+ addUser(deps.config, msg.userId, msg.userId, [name]);
383
+ const reply = `Repo "${name}" already exists. I've added you to it. Go ahead.`;
384
+ await msg.reply(reply);
385
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
386
+ return;
387
+ }
388
+
389
+ addRepo(deps.config, name, url, branch);
390
+ addUser(deps.config, msg.userId, msg.userId, [name]);
391
+ const reply = `Added repo "${name}" (${url}, branch: ${branch}).`;
392
+ await msg.reply(reply);
393
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
394
+ }
395
+
396
+ async function handleTaskMessage(msg: IncomingMessage, parsed: ParsedMessage, deps: HandlerDeps) {
397
+ // If the repo hint doesn't match a known repo, clear it and let auto-resolution handle it
398
+ if (parsed.repo && !deps.getRepoInfo(parsed.repo)) {
399
+ parsed.repo = undefined;
400
+ }
401
+
402
+ if (!parsed.repo) {
403
+ const userRepos = getUserRepos(deps.config, msg.userId);
404
+ const hasWildcard = userRepos.includes("*");
405
+
406
+ if (!hasWildcard && userRepos.length === 1) {
407
+ parsed.repo = userRepos[0];
408
+ } else if (hasWildcard || userRepos.length > 1) {
409
+ const repoNames = hasWildcard ? deps.repoRegistry.getAllNames() : userRepos;
410
+
411
+ if (repoNames.length === 1) {
412
+ parsed.repo = repoNames[0];
413
+ } else if (repoNames.length === 0) {
414
+ const reply = "No repos discovered yet. Set one up with `init repo <name> <git-url>` or configure GitHub sync.";
415
+ await msg.reply(reply);
416
+ return;
417
+ } else {
418
+ // Try last completed task's repo first (cheap)
419
+ const recentTasks = deps.queue.listByUser(msg.userId, 5);
420
+ const lastRepo = recentTasks.find(t => t.status === "completed" || t.status === "failed")?.repo;
421
+ if (lastRepo && repoNames.includes(lastRepo)) {
422
+ parsed.repo = lastRepo;
423
+ logger.info("repo resolved from recent task", { resolved: lastRepo, userText: parsed.rawText.slice(0, 80) });
424
+ } else {
425
+ // Resolve repo via a quick LLM call, then enqueue through the normal path
426
+ const repoList = repoNames.join(", ");
427
+ const history = deps.sessions.getHistory(msg.userId, 6);
428
+ const historyContext = history.length > 1
429
+ ? "Recent conversation:\n" + history.slice(0, -1).map(m => `${m.role}: ${m.content}`).join("\n") + "\n\n"
430
+ : "";
431
+ const resolvePrompt = `You are a repo-name resolver. ${historyContext}The user's latest message:\n"${parsed.rawText}"\n\nAvailable repos: ${repoList}\n\nRespond with ONLY the repo name that best matches their request. Consider the conversation context if the current message doesn't mention a specific repo. Nothing else — just the exact repo name from the list. If you cannot determine which repo, respond with "UNKNOWN".`;
432
+
433
+ await msg.updateStatus("Figuring out which repo...");
434
+ try {
435
+ const runner = deps.getRunner(deps.config.runner?.name);
436
+ const result = await runner.run(resolvePrompt, deps.config.reposDir, { maxTurns: 1 });
437
+ const resolved = result.output.trim().replace(/[`"']/g, "");
438
+
439
+ if (resolved === "UNKNOWN" || !repoNames.includes(resolved)) {
440
+ const reply = `Which repo? I see ${repoNames.length} repos. Some matches: ${repoNames.slice(0, 10).join(", ")}${repoNames.length > 10 ? "..." : ""}.\nSay it again with 'on <repo>'.`;
441
+ await msg.reply(reply);
442
+ deps.sessions.addMessage(msg.userId, "assistant", reply);
443
+ return;
444
+ }
445
+
446
+ parsed.repo = resolved;
447
+ logger.info("repo resolved via LLM", { resolved, userText: parsed.rawText.slice(0, 80) });
448
+ } catch (err) {
449
+ await msg.reply(`Couldn't figure out the repo: ${String(err).slice(0, 300)}`);
450
+ return;
451
+ }
452
+ }
453
+ }
454
+ } else {
455
+ const reply = "You don't have access to any repos yet. Set one up:\n`init repo <name> <git-url> [branch]`\nExample: `init repo my-app git@github.com:user/my-app.git`";
456
+ await msg.reply(reply);
457
+ return;
458
+ }
459
+ }
460
+
461
+ if (!isAuthorized(deps.config, msg.userId, parsed.repo)) {
462
+ await msg.reply(`Not authorized for ${parsed.repo}.`);
463
+ return;
464
+ }
465
+
466
+ const repoInfo = deps.getRepoInfo(parsed.repo);
467
+ if (!repoInfo) {
468
+ await msg.reply(`Unknown repo: ${parsed.repo}`);
469
+ return;
470
+ }
471
+
472
+ const history = deps.sessions.getHistory(msg.userId, 6);
473
+ const prompt = buildContextualPrompt(parsed, history, OVE_PERSONA);
474
+
475
+ const taskId = deps.queue.enqueue({
476
+ userId: msg.userId,
477
+ repo: parsed.repo,
478
+ prompt,
479
+ });
480
+
481
+ deps.pendingReplies.set(taskId, msg);
482
+
483
+ const stats = deps.queue.stats();
484
+ if (stats.running > 0 || stats.pending > 1) {
485
+ await msg.reply(`Queued — ${stats.pending} task${stats.pending > 1 ? "s" : ""} ahead.`);
486
+ }
487
+ logger.info("task enqueued", { taskId, repo: parsed.repo, type: parsed.type });
488
+ }
489
+
490
+ export function createMessageHandler(deps: HandlerDeps): (msg: IncomingMessage) => Promise<void> {
491
+ return async (msg: IncomingMessage) => {
492
+ deps.sessions.addMessage(msg.userId, "user", msg.text);
493
+
494
+ const parsed = parseMessage(msg.text);
495
+
496
+ const handlers: Record<string, () => Promise<void>> = {
497
+ "clear": () => handleClear(msg, deps),
498
+ "status": () => handleStatus(msg, deps),
499
+ "history": () => handleHistory(msg, deps),
500
+ "help": () => handleHelp(msg, deps),
501
+ "list-tasks": () => handleListTasks(msg, deps),
502
+ "cancel-task": () => handleCancelTask(msg, parsed.args, deps),
503
+ "trace": () => handleTrace(msg, parsed.args, deps),
504
+ "list-schedules": () => handleListSchedules(msg, deps),
505
+ "remove-schedule": () => handleRemoveSchedule(msg, parsed.args, deps),
506
+ "schedule": () => handleSchedule(msg, parsed.repo, deps),
507
+ "discuss": () => {
508
+ const history = deps.sessions.getHistory(msg.userId, 6);
509
+ return handleDiscuss(msg, parsed, history, deps);
510
+ },
511
+ "create-project": () => {
512
+ const history = deps.sessions.getHistory(msg.userId, 6);
513
+ return handleCreateProject(msg, parsed, history, deps);
514
+ },
515
+ "init-repo": () => handleInitRepo(msg, parsed.args, deps),
516
+ };
517
+
518
+ const handler = handlers[parsed.type];
519
+ if (handler) {
520
+ await handler();
521
+ return;
522
+ }
523
+
524
+ // For all other types (free-form, review-pr, fix-issue, simplify, validate) — task dispatch
525
+ await handleTaskMessage(msg, parsed, deps);
526
+ };
527
+ }
528
+
529
+ export function createEventHandler(deps: HandlerDeps): (event: IncomingEvent, adapter: EventAdapter) => Promise<void> {
530
+ return async (event: IncomingEvent, adapter: EventAdapter) => {
531
+ const parsed = parseMessage(event.text);
532
+
533
+ if (!parsed.repo) {
534
+ const resolved = resolveRepo(event.userId, undefined, deps);
535
+ if (resolved) {
536
+ parsed.repo = resolved;
537
+ } else if ("repo" in event.source && event.source.repo) {
538
+ const shortName = event.source.repo.split("/").pop() || event.source.repo;
539
+ if (isAuthorized(deps.config, event.userId, shortName)) {
540
+ parsed.repo = shortName;
541
+ }
542
+ }
543
+ }
544
+
545
+ if (!parsed.repo) {
546
+ await adapter.respondToEvent(event.eventId, "Couldn't determine which repo. Configure your user in config.json.");
547
+ return;
548
+ }
549
+
550
+ if (!isAuthorized(deps.config, event.userId, parsed.repo)) {
551
+ await adapter.respondToEvent(event.eventId, `Not authorized for ${parsed.repo}.`);
552
+ return;
553
+ }
554
+
555
+ const repoInfo = deps.getRepoInfo(parsed.repo);
556
+ if (!repoInfo) {
557
+ await adapter.respondToEvent(event.eventId, `Unknown repo: ${parsed.repo}.`);
558
+ return;
559
+ }
560
+
561
+ const prompt = buildContextualPrompt(parsed, [], OVE_PERSONA);
562
+ const taskId = deps.queue.enqueue({
563
+ userId: event.userId,
564
+ repo: parsed.repo,
565
+ prompt,
566
+ });
567
+
568
+ deps.pendingEventReplies.set(taskId, { adapter, event });
569
+ logger.info("event task enqueued", { taskId, eventId: event.eventId, repo: parsed.repo });
570
+ };
571
+ }