@osovv/vv-opencode 2.2.1 → 2.3.0-rc.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +46 -2
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +6 -3
  5. package/dist/index.js.map +1 -1
  6. package/dist/lib/plugin-toggle-config.d.ts +1 -1
  7. package/dist/lib/plugin-toggle-config.js +3 -1
  8. package/dist/lib/plugin-toggle-config.js.map +1 -1
  9. package/dist/lib/vvoc-config.d.ts +89 -0
  10. package/dist/lib/vvoc-config.js +121 -1
  11. package/dist/lib/vvoc-config.js.map +1 -1
  12. package/dist/plugins/telegram/bot-api.d.ts +162 -0
  13. package/dist/plugins/telegram/bot-api.js +273 -0
  14. package/dist/plugins/telegram/bot-api.js.map +1 -0
  15. package/dist/plugins/telegram/commands.d.ts +167 -0
  16. package/dist/plugins/telegram/commands.js +709 -0
  17. package/dist/plugins/telegram/commands.js.map +1 -0
  18. package/dist/plugins/telegram/config.d.ts +38 -0
  19. package/dist/plugins/telegram/config.js +86 -0
  20. package/dist/plugins/telegram/config.js.map +1 -0
  21. package/dist/plugins/telegram/delivery.d.ts +121 -0
  22. package/dist/plugins/telegram/delivery.js +395 -0
  23. package/dist/plugins/telegram/delivery.js.map +1 -0
  24. package/dist/plugins/telegram/gateway.d.ts +61 -0
  25. package/dist/plugins/telegram/gateway.js +230 -0
  26. package/dist/plugins/telegram/gateway.js.map +1 -0
  27. package/dist/plugins/telegram/index.d.ts +110 -0
  28. package/dist/plugins/telegram/index.js +454 -0
  29. package/dist/plugins/telegram/index.js.map +1 -0
  30. package/dist/plugins/telegram/sessions.d.ts +147 -0
  31. package/dist/plugins/telegram/sessions.js +322 -0
  32. package/dist/plugins/telegram/sessions.js.map +1 -0
  33. package/dist/plugins/telegram/topology.d.ts +116 -0
  34. package/dist/plugins/telegram/topology.js +339 -0
  35. package/dist/plugins/telegram/topology.js.map +1 -0
  36. package/dist/plugins/web-tools/schemas.d.ts +19 -19
  37. package/dist/plugins/workflow/results.d.ts +39 -39
  38. package/package.json +6 -1
  39. package/schemas/vvoc/v3.json +89 -9
  40. package/templates/skills/vv-execute/references/tool-contracts.md +1 -1
@@ -0,0 +1,709 @@
1
+ // FILE: src/plugins/telegram/commands.ts
2
+ // VERSION: 1.0.0
3
+ // START_MODULE_CONTRACT
4
+ // PURPOSE: Own the Telegram-facing interaction and command surface: manual permission and question prompts with an input gate, General control commands with a project picker and /sync, session-topic commands including the model picker, rename, message history with revert and fork, abort, runtime settings, and bounded inbound attachments.
5
+ // SCOPE: Injectable native project, model, history, permission, and question surfaces; callback-data builders and parsing; per-topic interaction state with truthful closure; the custom-answer input gate consumed before prompt admission; per-topic merge windows with an injectable scheduler; attachment download with size and count caps; unknown-command fallbacks.
6
+ // DEPENDS: [src/plugins/telegram/bot-api.ts, src/plugins/telegram/topology.ts, src/plugins/telegram/delivery.ts, src/plugins/telegram/sessions.ts, src/plugins/telegram/config.ts]
7
+ // LINKS: [M-TELEGRAM-GATEWAY, M-TELEGRAM-DELIVERY, M-TELEGRAM-TOPICS, V-M-TELEGRAM-GATEWAY]
8
+ // ROLE: RUNTIME
9
+ // MAP_MODE: EXPORTS
10
+ // END_MODULE_CONTRACT
11
+ //
12
+ // START_MODULE_MAP
13
+ // NativeProjectSurface - Injectable native project listing and session creation.
14
+ // NativeModelSurface - Injectable native model listing.
15
+ // NativeHistorySurface - Injectable native message listing, revert, and fork.
16
+ // NativePermissionSurface - Injectable native permission list and reply.
17
+ // NativeQuestionSurface - Injectable native question reply.
18
+ // permissionCallbackData - Pure callback-data builder for permission actions.
19
+ // questionCallbackData - Pure callback-data builder for question options.
20
+ // questionCustomCallbackData - Pure callback-data builder for the custom-answer action.
21
+ // parseCallbackData - Pure callback-data parser shared by interactions and pickers.
22
+ // TelegramInteractions - Permission and question prompts with the per-topic input gate.
23
+ // TelegramCommands - Command dispatch for the General and session topics with pickers and attachments.
24
+ // END_MODULE_MAP
25
+ //
26
+ // START_CHANGE_SUMMARY
27
+ // LAST_CHANGE: [C-TELEGRAM-BRIDGE-PLUGIN T-006/T-007 - Created the interactions layer with manual permission and question flows plus the custom-answer gate, and the command surface with project and model pickers, /sync, /status, rename, revert, fork, abort, settings, and bounded attachments.]
28
+ // END_CHANGE_SUMMARY
29
+ import { TelegramInputMerger } from "./delivery.js";
30
+ // START_BLOCK_CALLBACK_DATA
31
+ const PERMISSION_PREFIX = "vvocp";
32
+ const QUESTION_PREFIX = "vvocq";
33
+ const QUESTION_CUSTOM_PREFIX = "vvocqc";
34
+ /** Pure callback-data builder for permission actions. */
35
+ export function permissionCallbackData(requestID, action) {
36
+ return `${PERMISSION_PREFIX}:${requestID}:${action}`;
37
+ }
38
+ /** Pure callback-data builder for question options. */
39
+ export function questionCallbackData(questionID, optionIndex) {
40
+ return `${QUESTION_PREFIX}:${questionID}:${optionIndex}`;
41
+ }
42
+ /** Pure callback-data builder for the custom-answer action. */
43
+ export function questionCustomCallbackData(questionID) {
44
+ return `${QUESTION_CUSTOM_PREFIX}:${questionID}`;
45
+ }
46
+ /** Pure callback-data parser shared by interactions and pickers. */
47
+ export function parseCallbackData(data) {
48
+ const parts = data.split(":");
49
+ if (parts.length === 3 &&
50
+ parts[0] === PERMISSION_PREFIX &&
51
+ ["once", "always", "reject"].includes(parts[2])) {
52
+ return { kind: "permission", id: parts[1], action: parts[2] };
53
+ }
54
+ if (parts.length === 3 && parts[0] === QUESTION_PREFIX && /^\d+$/.test(parts[2])) {
55
+ return { kind: "question", id: parts[1], optionIndex: Number(parts[2]) };
56
+ }
57
+ if (parts.length === 2 && parts[0] === QUESTION_CUSTOM_PREFIX) {
58
+ return { kind: "question-custom", id: parts[1] };
59
+ }
60
+ return undefined;
61
+ }
62
+ /**
63
+ * Permission and question prompts. Every decision is manual: buttons call the
64
+ * native surfaces, a failed reply keeps the prompt answerable with a warning,
65
+ * and a prompt that disappears outside Telegram closes truthfully. Choosing the
66
+ * custom answer opens the topic input gate so the next plain message becomes
67
+ * the answer instead of a prompt.
68
+ */
69
+ export class TelegramInteractions {
70
+ #transport;
71
+ #topology;
72
+ #permissions;
73
+ #questions;
74
+ #prompts = new Map();
75
+ #gates = new Map();
76
+ constructor(deps) {
77
+ this.#transport = deps.transport;
78
+ this.#topology = deps.topology;
79
+ this.#permissions = deps.permissions;
80
+ this.#questions = deps.questions;
81
+ }
82
+ /** Whether a topic currently holds the input gate for a custom answer. */
83
+ isGated(threadId) {
84
+ return this.#gates.has(threadId);
85
+ }
86
+ async onPermissionEvent(input) {
87
+ const threadId = this.#topology.topicIdFor(input.sessionID);
88
+ if (threadId === undefined)
89
+ return;
90
+ if (input.phase === "resolved") {
91
+ await this.#closePrompt(threadId, "resolved outside Telegram");
92
+ return;
93
+ }
94
+ if (input.requestID === undefined)
95
+ return;
96
+ const existing = this.#prompts.get(threadId);
97
+ if (existing !== undefined && existing.id === input.requestID)
98
+ return;
99
+ const label = input.summary ?? "permission request";
100
+ const sent = await this.#transport.sendMessage({
101
+ threadId,
102
+ text: `🔐 Permission required\n${label}`,
103
+ replyMarkup: [
104
+ [
105
+ { text: "✅ Once", callbackData: permissionCallbackData(input.requestID, "once") },
106
+ { text: "♾ Always", callbackData: permissionCallbackData(input.requestID, "always") },
107
+ { text: "❌ Reject", callbackData: permissionCallbackData(input.requestID, "reject") },
108
+ ],
109
+ ],
110
+ });
111
+ this.#prompts.set(threadId, {
112
+ kind: "permission",
113
+ sessionID: input.sessionID,
114
+ id: input.requestID,
115
+ tgMessageId: sent.messageId,
116
+ label,
117
+ options: [],
118
+ });
119
+ }
120
+ async onQuestionEvent(input) {
121
+ const threadId = this.#topology.topicIdFor(input.sessionID);
122
+ if (threadId === undefined)
123
+ return;
124
+ if (input.phase === "resolved") {
125
+ await this.#closePrompt(threadId, "answered or cancelled outside Telegram");
126
+ return;
127
+ }
128
+ if (input.questionID === undefined)
129
+ return;
130
+ const existing = this.#prompts.get(threadId);
131
+ if (existing !== undefined && existing.id === input.questionID)
132
+ return;
133
+ const label = input.prompt ?? "question";
134
+ const rows = input.options.map((option, index) => [
135
+ {
136
+ text: option.slice(0, 60),
137
+ callbackData: questionCallbackData(input.questionID, index),
138
+ },
139
+ ]);
140
+ rows.push([
141
+ { text: "✍️ Custom answer", callbackData: questionCustomCallbackData(input.questionID) },
142
+ ]);
143
+ const sent = await this.#transport.sendMessage({
144
+ threadId,
145
+ text: `❓ ${label}`,
146
+ replyMarkup: rows,
147
+ });
148
+ this.#prompts.set(threadId, {
149
+ kind: "question",
150
+ sessionID: input.sessionID,
151
+ id: input.questionID,
152
+ tgMessageId: sent.messageId,
153
+ label,
154
+ options: input.options,
155
+ });
156
+ }
157
+ /** Handle one owner callback query routed here by the command layer. */
158
+ async handleCallback(query) {
159
+ if (query.data === undefined)
160
+ return;
161
+ const threadId = query.message?.message_thread_id;
162
+ const prompt = threadId === undefined ? undefined : this.#prompts.get(threadId);
163
+ try {
164
+ const parsed = parseCallbackData(query.data);
165
+ if (parsed === undefined || prompt === undefined) {
166
+ await this.#transport.answerCallback(query.id, "stale prompt");
167
+ return;
168
+ }
169
+ if (parsed.kind === "permission") {
170
+ await this.#permissions.reply({
171
+ sessionID: prompt.sessionID,
172
+ requestID: parsed.id,
173
+ reply: parsed.action,
174
+ });
175
+ await this.#transport.answerCallback(query.id, parsed.action === "reject" ? "rejected" : "allowed");
176
+ await this.#closePrompt(threadId, parsed.action === "reject" ? "❌ rejected" : `✅ ${parsed.action}`);
177
+ return;
178
+ }
179
+ if (parsed.kind === "question") {
180
+ const option = prompt.options[parsed.optionIndex];
181
+ if (option === undefined) {
182
+ await this.#transport.answerCallback(query.id, "stale option");
183
+ return;
184
+ }
185
+ await this.#questions.reply({
186
+ sessionID: prompt.sessionID,
187
+ questionID: parsed.id,
188
+ answer: option,
189
+ });
190
+ await this.#transport.answerCallback(query.id, "answered");
191
+ await this.#closePrompt(threadId, `✅ answered: ${option}`);
192
+ return;
193
+ }
194
+ this.#gates.set(threadId, {
195
+ kind: "custom",
196
+ id: parsed.id,
197
+ sessionID: prompt.sessionID,
198
+ });
199
+ await this.#transport.answerCallback(query.id, "type your answer");
200
+ await this.#editPrompt(threadId, prompt, `${prompt.label}\n\n✍️ type your answer now (/cancel to abort)`);
201
+ }
202
+ catch {
203
+ await this.#transport.answerCallback(query.id, "⚠️ failed, try again");
204
+ }
205
+ }
206
+ /** Consume a gated plain message as the custom answer; returns true when consumed. */
207
+ async consumeGatedText(threadId, text) {
208
+ const gate = this.#gates.get(threadId);
209
+ const prompt = this.#prompts.get(threadId);
210
+ if (gate === undefined)
211
+ return false;
212
+ this.#gates.delete(threadId);
213
+ if (text.trim() === "/cancel") {
214
+ if (prompt !== undefined) {
215
+ await this.#editPrompt(threadId, prompt, `${prompt.label}\n\n⏹ custom answer cancelled`);
216
+ }
217
+ return true;
218
+ }
219
+ try {
220
+ await this.#questions.reply({ sessionID: gate.sessionID, questionID: gate.id, answer: text });
221
+ if (prompt !== undefined) {
222
+ await this.#editPrompt(threadId, prompt, `${prompt.label}\n\n✅ answered: ${text.slice(0, 80)}`);
223
+ }
224
+ }
225
+ catch {
226
+ this.#gates.set(threadId, gate);
227
+ if (prompt !== undefined) {
228
+ await this.#editPrompt(threadId, prompt, `${prompt.label}\n\n⚠️ answer failed, type again`);
229
+ }
230
+ }
231
+ return true;
232
+ }
233
+ /** Re-render still-pending native permission prompts after a restart. */
234
+ async resurfacePending(sessionIDs) {
235
+ for (const sessionID of sessionIDs) {
236
+ const threadId = this.#topology.topicIdFor(sessionID);
237
+ if (threadId === undefined)
238
+ continue;
239
+ const pending = await this.#permissions.listPending({ sessionID });
240
+ for (const request of pending) {
241
+ await this.onPermissionEvent({
242
+ sessionID,
243
+ requestID: request.requestID,
244
+ phase: "requested",
245
+ summary: request.summary,
246
+ });
247
+ }
248
+ }
249
+ }
250
+ async #closePrompt(threadId, outcome) {
251
+ const prompt = this.#prompts.get(threadId);
252
+ this.#prompts.delete(threadId);
253
+ this.#gates.delete(threadId);
254
+ if (prompt === undefined)
255
+ return;
256
+ await this.#editPrompt(threadId, prompt, `${prompt.label}\n\n${outcome}`);
257
+ }
258
+ async #editPrompt(threadId, prompt, text) {
259
+ try {
260
+ await this.#transport.editMessageText({ messageId: prompt.tgMessageId, text });
261
+ }
262
+ catch {
263
+ // Editing a prompt is best-effort; the native state stays truthful.
264
+ }
265
+ }
266
+ }
267
+ /**
268
+ * Command dispatch for the General and session topics. Plain text in a session
269
+ * topic is consumed by the custom-answer gate first, then coalesced through the
270
+ * per-topic merge window before admission as a prompt.
271
+ */
272
+ export class TelegramCommands {
273
+ #transport;
274
+ #topology;
275
+ #delivery;
276
+ #bridge;
277
+ #interactions;
278
+ #projects;
279
+ #models;
280
+ #history;
281
+ #reads;
282
+ #clock;
283
+ #schedule;
284
+ #mergers = new Map();
285
+ #maxAttachmentBytes;
286
+ #maxAttachments;
287
+ constructor(deps) {
288
+ this.#transport = deps.transport;
289
+ this.#topology = deps.topology;
290
+ this.#delivery = deps.delivery;
291
+ this.#bridge = deps.bridge;
292
+ this.#interactions = deps.interactions;
293
+ this.#projects = deps.projects;
294
+ this.#models = deps.models;
295
+ this.#history = deps.history;
296
+ this.#reads = deps.reads;
297
+ this.#clock = deps.clock;
298
+ this.#schedule = deps.schedule ?? ((fn, ms) => setTimeout(fn, ms));
299
+ this.#maxAttachmentBytes = deps.maxAttachmentBytes ?? 8 * 1024 * 1024;
300
+ this.#maxAttachments = deps.maxAttachments ?? 10;
301
+ }
302
+ /** Route one owner message; the caller has already verified the sender. */
303
+ async handleMessage(input) {
304
+ const text = input.text?.trim() ?? "";
305
+ if (text.startsWith("/")) {
306
+ await this.#command(input.threadId, text);
307
+ return;
308
+ }
309
+ const sessionID = this.#topology.sessionFor(input.threadId);
310
+ if (sessionID === undefined) {
311
+ if (text.length > 0) {
312
+ await this.#delivery.sendTransient({
313
+ threadId: input.threadId,
314
+ text: "ℹ️ commands live in General; session topics take prompts",
315
+ });
316
+ }
317
+ return;
318
+ }
319
+ if (text.length > 0 && (await this.#interactions.consumeGatedText(input.threadId, text)))
320
+ return;
321
+ if (input.attachments !== undefined && input.attachments.length > 0) {
322
+ await this.#promptWithAttachments(sessionID, input.threadId, text, input.attachments);
323
+ return;
324
+ }
325
+ if (text.length === 0)
326
+ return;
327
+ const merger = this.#mergerFor(input.threadId);
328
+ merger.add(text, this.#clock.now());
329
+ this.#schedule(() => {
330
+ void this.#flushMerger(input.threadId, sessionID, true);
331
+ }, this.#delivery.settings.mergeWindowMs + 50);
332
+ if (merger.due(this.#clock.now())) {
333
+ await this.#flushMerger(input.threadId, sessionID, false);
334
+ }
335
+ }
336
+ /** Route one owner callback query to pickers or the interactions layer. */
337
+ async handleCallback(query) {
338
+ if (query.data === undefined)
339
+ return;
340
+ const threadId = query.message?.message_thread_id;
341
+ if (threadId === undefined)
342
+ return;
343
+ if (query.data.startsWith("vvocnp:")) {
344
+ await this.#pickProject(query, threadId, Number(query.data.slice("vvocnp:".length)));
345
+ return;
346
+ }
347
+ if (query.data.startsWith("vvocm:")) {
348
+ await this.#pickModel(query, threadId, query.data.slice("vvocm:".length));
349
+ return;
350
+ }
351
+ if (query.data.startsWith("vvocmsg:")) {
352
+ await this.#pickMessage(query, threadId, query.data.slice("vvocmsg:".length));
353
+ return;
354
+ }
355
+ if (query.data.startsWith("vvocs:")) {
356
+ await this.#toggleSetting(query, threadId, query.data.slice("vvocs:".length));
357
+ return;
358
+ }
359
+ await this.#interactions.handleCallback(query);
360
+ }
361
+ async #command(threadId, raw) {
362
+ const [command, ...rest] = raw.slice(1).split(/\s+/);
363
+ const argument = rest.join(" ").trim();
364
+ const body = command?.split("@")[0] ?? "";
365
+ const sessionID = this.#topology.sessionFor(threadId);
366
+ switch (body) {
367
+ case "new": {
368
+ if (threadId !== this.#topology.generalThreadId) {
369
+ await this.#delivery.sendTransient({ threadId, text: "ℹ️ /new lives in General" });
370
+ return;
371
+ }
372
+ await this.#startProjectPicker(threadId);
373
+ return;
374
+ }
375
+ case "sync": {
376
+ await this.#bridge.resync();
377
+ const sessions = await this.#reads.listSessions();
378
+ const running = new Set(await this.#reads.activeSessionIds());
379
+ const active = sessions.filter((session) => running.has(session.id) ||
380
+ this.#topology.isActive(session.id, {
381
+ running: false,
382
+ timeUpdatedMs: session.timeUpdatedMs,
383
+ }));
384
+ const report = await this.#topology.reconcile(active.map((session) => ({
385
+ sessionID: session.id,
386
+ title: session.title ?? session.id,
387
+ timeUpdatedMs: session.timeUpdatedMs,
388
+ running: running.has(session.id),
389
+ })));
390
+ await this.#delivery.sendTransient({
391
+ threadId,
392
+ text: `🔄 synced: ${report.created} created, ${report.closed} closed, ${report.reused} reused, ${report.failures} failed`,
393
+ });
394
+ return;
395
+ }
396
+ case "status": {
397
+ const sessions = await this.#reads.listSessions();
398
+ const running = new Set(await this.#reads.activeSessionIds());
399
+ if (sessionID === undefined) {
400
+ const lines = sessions
401
+ .filter((session) => running.has(session.id) ||
402
+ this.#topology.isActive(session.id, {
403
+ running: false,
404
+ timeUpdatedMs: session.timeUpdatedMs,
405
+ }))
406
+ .map((session) => `${running.has(session.id) ? "⚙️" : "💤"} ${session.title ?? session.id}${this.#topology.topicIdFor(session.id) === undefined ? " (no topic)" : ""}`);
407
+ await this.#delivery.sendTransient({
408
+ threadId,
409
+ text: `📊 active sessions (${lines.length}):\n${lines.length > 0 ? lines.join("\n") : "none"}`,
410
+ });
411
+ return;
412
+ }
413
+ const session = sessions.find((entry) => entry.id === sessionID);
414
+ await this.#delivery.sendTransient({
415
+ threadId,
416
+ text: `📊 ${session?.title ?? sessionID}\nstate: ${running.has(sessionID) ? "running" : "idle"}\nsession: ${sessionID}`,
417
+ });
418
+ return;
419
+ }
420
+ case "help": {
421
+ await this.#delivery.sendTransient({
422
+ threadId,
423
+ text: [
424
+ "General: /new, /sync, /status, /help, /settings",
425
+ "Session topic: text = prompt, /model, /rename <title>, /messages, /abort",
426
+ "Answers: buttons on prompts; ✍️ Custom then plain text (/cancel aborts)",
427
+ ].join("\n"),
428
+ });
429
+ return;
430
+ }
431
+ case "settings": {
432
+ const settings = this.#delivery.settings;
433
+ await this.#transport.sendMessage({
434
+ threadId,
435
+ text: "⚙️ settings",
436
+ replyMarkup: [
437
+ [
438
+ {
439
+ text: `reasoning: ${settings.showReasoning ? "on" : "off"}`,
440
+ callbackData: "vvocs:reasoning",
441
+ },
442
+ {
443
+ text: `tool calls: ${settings.showToolCalls ? "on" : "off"}`,
444
+ callbackData: "vvocs:tools",
445
+ },
446
+ ],
447
+ [{ text: `format: ${settings.formatMode}`, callbackData: "vvocs:format" }],
448
+ ],
449
+ });
450
+ return;
451
+ }
452
+ case "model": {
453
+ if (sessionID === undefined)
454
+ return;
455
+ const models = await this.#models.listModels();
456
+ const providers = [...new Set(models.map((model) => model.providerID))];
457
+ await this.#transport.sendMessage({
458
+ threadId,
459
+ text: "🗂 pick a provider",
460
+ replyMarkup: providers
461
+ .slice(0, 20)
462
+ .map((provider, index) => [{ text: provider, callbackData: `vvocm:prov:${index}` }]),
463
+ });
464
+ this.#providerCache.set(threadId, providers);
465
+ this.#modelCache.set(threadId, models);
466
+ return;
467
+ }
468
+ case "rename": {
469
+ if (sessionID === undefined || argument.length === 0)
470
+ return;
471
+ const bounded = argument.slice(0, 120);
472
+ await this.#topology.setStatus(sessionID, "none", bounded);
473
+ await this.#bridge.adoptSession({ sessionID, title: bounded });
474
+ await this.#delivery.sendTransient({ threadId, text: `✏️ renamed to ${bounded}` });
475
+ return;
476
+ }
477
+ case "messages": {
478
+ if (sessionID === undefined)
479
+ return;
480
+ const messages = await this.#history.listUserMessages({ sessionID });
481
+ if (messages.length === 0) {
482
+ await this.#delivery.sendTransient({ threadId, text: "📭 no user messages" });
483
+ return;
484
+ }
485
+ this.#messageCache.set(threadId, messages.map((message) => ({ ...message })));
486
+ await this.#transport.sendMessage({
487
+ threadId,
488
+ text: "📜 pick a message",
489
+ replyMarkup: messages.slice(0, 15).map((message, index) => [
490
+ {
491
+ text: message.text.slice(0, 48) || "(empty)",
492
+ callbackData: `vvocmsg:open:${index}`,
493
+ },
494
+ ]),
495
+ });
496
+ return;
497
+ }
498
+ case "abort": {
499
+ if (sessionID === undefined)
500
+ return;
501
+ await this.#bridge.abort(sessionID);
502
+ await this.#delivery.sendTransient({ threadId, text: "⏹ aborted" });
503
+ return;
504
+ }
505
+ default: {
506
+ await this.#delivery.sendTransient({ threadId, text: `🤷 unknown command /${body}` });
507
+ }
508
+ }
509
+ }
510
+ #providerCache = new Map();
511
+ #modelCache = new Map();
512
+ #messageCache = new Map();
513
+ async #startProjectPicker(threadId) {
514
+ const projects = await this.#projects.listProjects();
515
+ if (projects.length === 0) {
516
+ await this.#delivery.sendTransient({ threadId, text: "📭 no known projects" });
517
+ return;
518
+ }
519
+ this.#projectCache.set(threadId, projects.map((project) => ({ ...project })));
520
+ await this.#transport.sendMessage({
521
+ threadId,
522
+ text: "📁 pick a project",
523
+ replyMarkup: projects.slice(0, 15).map((project, index) => [
524
+ {
525
+ text: project.directory.split("/").pop() ?? project.directory,
526
+ callbackData: `vvocnp:${index}`,
527
+ },
528
+ ]),
529
+ });
530
+ }
531
+ #projectCache = new Map();
532
+ async #pickProject(query, threadId, index) {
533
+ const project = this.#projectCache.get(threadId)?.[index];
534
+ if (project === undefined) {
535
+ await this.#transport.answerCallback(query.id, "stale picker");
536
+ return;
537
+ }
538
+ const created = await this.#projects.createSession({ directory: project.directory });
539
+ await this.#bridge.adoptSession({
540
+ sessionID: created.id,
541
+ title: project.directory.split("/").pop() ?? created.id,
542
+ });
543
+ await this.#transport.answerCallback(query.id, "session created");
544
+ const topicId = this.#topology.topicIdFor(created.id);
545
+ await this.#delivery.sendTransient({
546
+ threadId,
547
+ text: `✅ session created — continue in its topic (${topicId ?? "?"})`,
548
+ });
549
+ }
550
+ async #pickModel(query, threadId, payload) {
551
+ const sessionID = this.#topology.sessionFor(threadId);
552
+ if (sessionID === undefined)
553
+ return;
554
+ const parts = payload.split(":");
555
+ if (parts[0] === "prov") {
556
+ const provider = this.#providerCache.get(threadId)?.[Number(parts[1])];
557
+ const models = this.#modelCache
558
+ .get(threadId)
559
+ ?.filter((model) => model.providerID === provider);
560
+ if (provider === undefined || models === undefined || models.length === 0) {
561
+ await this.#transport.answerCallback(query.id, "stale picker");
562
+ return;
563
+ }
564
+ await this.#transport.answerCallback(query.id, provider);
565
+ await this.#transport.sendMessage({
566
+ threadId,
567
+ text: `🧠 models of ${provider}`,
568
+ replyMarkup: models
569
+ .slice(0, 20)
570
+ .map((model, index) => [
571
+ { text: model.modelID.slice(0, 48), callbackData: `vvocm:model:${index}` },
572
+ ]),
573
+ });
574
+ this.#modelSelection.set(threadId, models);
575
+ return;
576
+ }
577
+ if (parts[0] === "model") {
578
+ const model = this.#modelSelection.get(threadId)?.[Number(parts[1])];
579
+ if (model === undefined) {
580
+ await this.#transport.answerCallback(query.id, "stale picker");
581
+ return;
582
+ }
583
+ await this.#bridge.switchModel({ sessionID, model });
584
+ await this.#transport.answerCallback(query.id, `switched to ${model.modelID}`);
585
+ await this.#delivery.sendTransient({
586
+ threadId,
587
+ text: `🧠 model switched to ${model.providerID}/${model.modelID}`,
588
+ });
589
+ return;
590
+ }
591
+ await this.#transport.answerCallback(query.id, "unknown");
592
+ }
593
+ #modelSelection = new Map();
594
+ async #pickMessage(query, threadId, payload) {
595
+ const sessionID = this.#topology.sessionFor(threadId);
596
+ if (sessionID === undefined)
597
+ return;
598
+ const parts = payload.split(":");
599
+ const message = this.#messageCache.get(threadId)?.[Number(parts[1])];
600
+ if (parts[0] !== "open" && parts[0] !== "revert" && parts[0] !== "fork")
601
+ return;
602
+ if (parts[0] === "open") {
603
+ if (message === undefined) {
604
+ await this.#transport.answerCallback(query.id, "stale");
605
+ return;
606
+ }
607
+ await this.#transport.answerCallback(query.id, "message");
608
+ await this.#transport.sendMessage({
609
+ threadId,
610
+ text: message.text.slice(0, 3_000),
611
+ replyMarkup: [
612
+ [
613
+ { text: "⏪ Revert here", callbackData: `vvocmsg:revert:${parts[1]}` },
614
+ { text: "🌿 Fork here", callbackData: `vvocmsg:fork:${parts[1]}` },
615
+ ],
616
+ ],
617
+ });
618
+ return;
619
+ }
620
+ if (message === undefined) {
621
+ await this.#transport.answerCallback(query.id, "stale");
622
+ return;
623
+ }
624
+ if (parts[0] === "revert") {
625
+ await this.#history.revert({ sessionID, messageID: message.messageID });
626
+ await this.#transport.answerCallback(query.id, "reverted");
627
+ await this.#delivery.sendTransient({ threadId, text: "⏪ session reverted" });
628
+ return;
629
+ }
630
+ const forked = await this.#history.fork({ sessionID, messageID: message.messageID });
631
+ await this.#bridge.adoptSession({
632
+ sessionID: forked.id,
633
+ title: `fork of ${sessionID.slice(-6)}`,
634
+ });
635
+ await this.#transport.answerCallback(query.id, "forked");
636
+ await this.#delivery.sendTransient({ threadId, text: `🌿 forked session ${forked.id}` });
637
+ }
638
+ async #toggleSetting(query, threadId, key) {
639
+ const settings = this.#delivery.settings;
640
+ if (key === "reasoning") {
641
+ await this.#delivery.updateSettings({ showReasoning: !settings.showReasoning });
642
+ }
643
+ else if (key === "tools") {
644
+ await this.#delivery.updateSettings({ showToolCalls: !settings.showToolCalls });
645
+ }
646
+ else if (key === "format") {
647
+ await this.#delivery.updateSettings({
648
+ formatMode: settings.formatMode === "markdown" ? "raw" : "markdown",
649
+ });
650
+ }
651
+ else {
652
+ await this.#transport.answerCallback(query.id, "unknown setting");
653
+ return;
654
+ }
655
+ await this.#transport.answerCallback(query.id, "updated");
656
+ await this.#delivery.sendTransient({ threadId, text: "⚙️ setting updated" });
657
+ }
658
+ #mergerFor(threadId) {
659
+ let merger = this.#mergers.get(threadId);
660
+ if (merger === undefined) {
661
+ merger = new TelegramInputMerger(this.#delivery.settings.mergeWindowMs);
662
+ this.#mergers.set(threadId, merger);
663
+ }
664
+ return merger;
665
+ }
666
+ async #flushMerger(threadId, sessionID, forced) {
667
+ const merger = this.#mergers.get(threadId);
668
+ if (merger === undefined)
669
+ return;
670
+ const text = forced ? merger.flush() : merger.take(this.#clock.now());
671
+ if (text === null || text.trim().length === 0)
672
+ return;
673
+ await this.#bridge.promptFromTelegram({ sessionID, text });
674
+ }
675
+ async #promptWithAttachments(sessionID, threadId, caption, attachments) {
676
+ if (attachments.length > this.#maxAttachments) {
677
+ await this.#delivery.sendTransient({
678
+ threadId,
679
+ text: `⚠️ too many attachments (max ${this.#maxAttachments}); nothing sent`,
680
+ });
681
+ return;
682
+ }
683
+ const files = [];
684
+ for (const attachment of attachments) {
685
+ try {
686
+ const bytes = await this.#transport.downloadFile(attachment.fileId, this.#maxAttachmentBytes);
687
+ files.push({
688
+ filename: attachment.filename ?? `attachment-${files.length + 1}`,
689
+ mimeType: attachment.mimeType ?? "application/octet-stream",
690
+ base64: Buffer.from(bytes).toString("base64"),
691
+ });
692
+ }
693
+ catch {
694
+ await this.#delivery.sendTransient({
695
+ threadId,
696
+ text: `⚠️ attachment ${attachment.filename ?? attachment.fileId} exceeded the size cap and was rejected`,
697
+ });
698
+ }
699
+ }
700
+ if (files.length === 0)
701
+ return;
702
+ await this.#bridge.promptFromTelegram({
703
+ sessionID,
704
+ text: caption.length > 0 ? caption : `(see ${files.length} attachment(s))`,
705
+ files,
706
+ });
707
+ }
708
+ }
709
+ //# sourceMappingURL=commands.js.map