@agentprojectcontext/apx 1.32.2 → 1.33.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 (48) hide show
  1. package/package.json +1 -1
  2. package/skills/apc-context/SKILL.md +2 -5
  3. package/src/core/agent/prompts/action-discipline.md +12 -5
  4. package/src/core/agent/prompts/channels/telegram.md +9 -5
  5. package/src/core/apc/parser.js +1 -1
  6. package/src/core/apc/scaffold.js +3 -1
  7. package/src/core/apc/skill-sync.js +3 -1
  8. package/src/core/engines/gemini.js +28 -11
  9. package/src/core/engines/index.js +11 -1
  10. package/src/core/stores/code-sessions.js +4 -1
  11. package/src/host/daemon/api/artifacts.js +25 -0
  12. package/src/host/daemon/api/code.js +14 -1
  13. package/src/host/daemon/api/engines.js +31 -1
  14. package/src/host/daemon/api/exec.js +17 -2
  15. package/src/host/daemon/plugins/telegram/dispatch.js +573 -0
  16. package/src/host/daemon/plugins/telegram/helpers.js +130 -0
  17. package/src/host/daemon/plugins/telegram/index.js +19 -694
  18. package/src/interfaces/web/dist/assets/index-Aaiw8BZN.css +1 -0
  19. package/src/interfaces/web/dist/assets/index-DPqtjDjh.js +602 -0
  20. package/src/interfaces/web/dist/assets/index-DPqtjDjh.js.map +1 -0
  21. package/src/interfaces/web/dist/index.html +2 -2
  22. package/src/interfaces/web/package-lock.json +3 -3
  23. package/src/interfaces/web/src/App.tsx +3 -1
  24. package/src/interfaces/web/src/components/ModelCombobox.tsx +42 -7
  25. package/src/interfaces/web/src/components/UiSelect.tsx +12 -2
  26. package/src/interfaces/web/src/components/code/CodeArtifactsTab.tsx +253 -111
  27. package/src/interfaces/web/src/components/code/CodeChangesTab.tsx +10 -8
  28. package/src/interfaces/web/src/components/code/CodeComposer.tsx +20 -17
  29. package/src/interfaces/web/src/components/code/CodeContextTab.tsx +43 -18
  30. package/src/interfaces/web/src/components/code/CodeFileTree.tsx +212 -0
  31. package/src/interfaces/web/src/components/code/CodeFileViewer.tsx +121 -0
  32. package/src/interfaces/web/src/components/code/CodeSessionList.tsx +30 -26
  33. package/src/interfaces/web/src/components/code/CodeSidePanel.tsx +23 -19
  34. package/src/interfaces/web/src/components/code/CodeTerminal.tsx +140 -0
  35. package/src/interfaces/web/src/components/common/TabLayout.tsx +3 -3
  36. package/src/interfaces/web/src/components/ui/chat-input.tsx +17 -6
  37. package/src/interfaces/web/src/hooks/useChat.ts +1 -0
  38. package/src/interfaces/web/src/hooks/useNavCollapseCtx.tsx +25 -1
  39. package/src/interfaces/web/src/i18n/es.ts +1 -1
  40. package/src/interfaces/web/src/lib/api/agents.ts +1 -1
  41. package/src/interfaces/web/src/lib/api/artifacts.ts +10 -0
  42. package/src/interfaces/web/src/lib/api/code.ts +4 -2
  43. package/src/interfaces/web/src/screens/modules/CodeScreen.tsx +423 -79
  44. package/src/interfaces/web/src/screens/project/ChatTab.tsx +7 -10
  45. package/src/core/util/text-similarity.js +0 -52
  46. package/src/interfaces/web/dist/assets/index-34U_Mp1M.css +0 -1
  47. package/src/interfaces/web/dist/assets/index-BkybwwRn.js +0 -570
  48. package/src/interfaces/web/dist/assets/index-BkybwwRn.js.map +0 -1
@@ -44,131 +44,29 @@ import { buildRelationshipBlock } from "#core/agent/index.js";
44
44
  import { getConfirmationStore as getConfirmStore } from "#core/confirmation/pending-store.js";
45
45
  import { CHANNELS } from "#core/constants/channels.js";
46
46
  import { tryResolveSkillCommand } from "#core/agent/skills/trigger.js";
47
- import { isLikelyDuplicate } from "#core/util/text-similarity.js";
48
47
  import { createTelegramConfirmAdapter } from "#core/confirmation/adapters/telegram.js";
49
48
  import * as askFlow from "./ask.js";
50
49
 
51
50
  // API_BASE re-imported from ./media.js below
52
51
  const nowIso = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
53
52
 
54
- // Build the channelMeta passed to the super-agent loop. The prompt template at
55
- // src/core/agent/prompts/channels/telegram.md interpolates {{projectBlock}}
56
- // and {{routeBlock}} verbatim, so we pre-render them as plain text here
57
- // (the template engine doesn't do conditionals).
58
- function buildTelegramMeta({ channelName, author, chatId, target, routeToAgent }) {
59
- const projectBlock = target
60
- ? `\nProject pin: **${target.name || "(unnamed)"}** (\`${target.path || "?"}\`).\n` +
61
- "This Telegram channel belongs to that project. Default any " +
62
- "project-scoped tool call (list_agents, list_tasks, list_mcps, " +
63
- "list_skills, create_task, list_routines, …) to " +
64
- `\`${target.name || target.path}\` without asking the user "which ` +
65
- 'project?". Only ask when they explicitly reference another project ' +
66
- "by name."
67
- : "";
68
- const routeBlock = routeToAgent
69
- ? `\nMaster agent for this channel: **${routeToAgent}**. Prefer ` +
70
- `delegating substantive work to that agent via call_agent({ project: ` +
71
- `"${target?.name || target?.path || ""}", agent: "${routeToAgent}", ` +
72
- "prompt: <user message> }) rather than answering yourself, unless " +
73
- "the message is small-talk or a quick factual reply."
74
- : "";
75
- return {
76
- channelName,
77
- author,
78
- chatId,
79
- projectBlock,
80
- routeBlock,
81
- // Also expose raw fields for any future surface / log that wants them.
82
- ...(target ? {
83
- projectId: String(target.id),
84
- projectName: target.name || "",
85
- projectPath: target.path || "",
86
- } : {}),
87
- ...(routeToAgent ? { routeToAgent } : {}),
88
- };
89
- }
90
-
91
- // Media sending helpers moved to ./media.js.
53
+ // All non-class-bound helpers live in ./helpers.js so the file stays
54
+ // focused on the poller class + dispatch wiring.
55
+ import {
56
+ buildTelegramMeta,
57
+ loadState,
58
+ saveState,
59
+ resolveBotToken,
60
+ resolveChatId,
61
+ tokenSource,
62
+ resolveChannels,
63
+ sleep,
64
+ } from "./helpers.js";
65
+ import { handleUpdate } from "./dispatch.js";
66
+
67
+ // ---------- media sending helpers (re-exports) ------------------------------
92
68
  import { sendPhoto, sendVoice, sendDocument, sendAudio, downloadTelegramFile, API_BASE } from "./media.js";
93
69
  export { sendPhoto, sendVoice, sendDocument, sendAudio };
94
- function loadState() {
95
- if (!fs.existsSync(TELEGRAM_STATE_PATH)) return { channels: {} };
96
- try {
97
- const raw = JSON.parse(fs.readFileSync(TELEGRAM_STATE_PATH, "utf8"));
98
- return { channels: raw.channels || {}, _legacy_offset: raw.offset || 0 };
99
- } catch {
100
- return { channels: {} };
101
- }
102
- }
103
-
104
- function saveState(state) {
105
- fs.writeFileSync(
106
- TELEGRAM_STATE_PATH,
107
- JSON.stringify({ ...state, updated_at: nowIso() }, null, 2) + "\n"
108
- );
109
- }
110
-
111
- // ---------- env-fallback helpers --------------------------------------------
112
-
113
- function resolveBotToken(channel) {
114
- return (
115
- channel.bot_token ||
116
- process.env.BOT_TELEGRAM_TOKEN ||
117
- process.env.TELEGRAM_BOT_TOKEN ||
118
- ""
119
- );
120
- }
121
-
122
- function resolveChatId(channel) {
123
- return (
124
- channel.chat_id ||
125
- process.env.TELEGRAM_CHAT_ID ||
126
- process.env.BOT_TELEGRAM_CHAT_ID ||
127
- ""
128
- );
129
- }
130
-
131
- function tokenSource(channel) {
132
- if (channel.bot_token) return "config";
133
- if (process.env.BOT_TELEGRAM_TOKEN) return "env:BOT_TELEGRAM_TOKEN";
134
- if (process.env.TELEGRAM_BOT_TOKEN) return "env:TELEGRAM_BOT_TOKEN";
135
- return null;
136
- }
137
-
138
- // ---------- channel-list resolution -----------------------------------------
139
-
140
- function resolveChannels(globalConfig) {
141
- const tg = globalConfig.telegram || {};
142
- if (Array.isArray(tg.channels) && tg.channels.length > 0) {
143
- return tg.channels.map((c, i) => ({
144
- name: c.name || `channel-${i + 1}`,
145
- bot_token: c.bot_token || "",
146
- chat_id: c.chat_id || "",
147
- route_to_agent: c.route_to_agent || "",
148
- project: c.project || null,
149
- respond_with_engine:
150
- c.respond_with_engine !== undefined
151
- ? c.respond_with_engine
152
- : tg.respond_with_engine !== false,
153
- poll_interval_ms: c.poll_interval_ms || tg.poll_interval_ms || 1500,
154
- }));
155
- }
156
- // Legacy single-channel mode
157
- if (!tg.bot_token && !process.env.BOT_TELEGRAM_TOKEN && !process.env.TELEGRAM_BOT_TOKEN) {
158
- return [];
159
- }
160
- return [
161
- {
162
- name: "default",
163
- bot_token: tg.bot_token || "",
164
- chat_id: tg.chat_id || "",
165
- route_to_agent: tg.route_to_agent || "",
166
- project: null,
167
- respond_with_engine: tg.respond_with_engine !== false,
168
- poll_interval_ms: tg.poll_interval_ms || 1500,
169
- },
170
- ];
171
- }
172
70
 
173
71
  // ---------- per-channel poller ----------------------------------------------
174
72
 
@@ -276,580 +174,11 @@ class ChannelPoller {
276
174
  return json.result || [];
277
175
  }
278
176
 
177
+ // Method body lives in ./dispatch.js as `handleUpdate(self, u)` so this file
178
+ // stays focused on poller lifecycle. The function reaches every internal
179
+ // poller field through the `self` it receives.
279
180
  async _handleUpdate(u) {
280
- this.lastUpdateAt = nowIso();
281
-
282
- // Inline keyboard button press: route to the confirmation adapter.
283
- if (u.callback_query) {
284
- await this._handleCallbackQuery(u.callback_query);
285
- return;
286
- }
287
-
288
- const msg = u.message || u.edited_message;
289
- if (!msg) return;
290
- const target = this.resolveProject();
291
- if (!target) {
292
- this.log(`telegram[${this.channel.name}] update ${u.update_id} ignored — no target project`);
293
- return;
294
- }
295
- const author =
296
- msg.from?.username
297
- ? "@" + msg.from.username
298
- : `${msg.from?.first_name || ""} ${msg.from?.last_name || ""}`.trim() || "unknown";
299
- const chat_id = msg.chat?.id;
300
-
301
- // Resolve WHO is writing (owner / known contact / guest), keyed by the
302
- // stable Telegram user_id. Records unknown senders and, on a fresh private
303
- // channel with no owner yet, claims this sender as the owner. Mutates the
304
- // in-memory globalConfig in place so later messages in this daemon session
305
- // see the update. The resulting block is injected into whichever agent
306
- // answers (super-agent OR a routed project agent).
307
- const { sender } = registerSender({
308
- cfg: this.globalConfig,
309
- channelName: this.channel.name,
310
- from: msg.from,
311
- chatType: msg.chat?.type,
312
- });
313
- const relationshipBlock = buildRelationshipBlock(sender);
314
- // Role-based tool gating for the super-agent path (guests → no tools).
315
- const allowedTools = resolveAllowedTools(this.globalConfig, sender);
316
-
317
- // Default Interrupt: abort any running request for this chat_id
318
- if (chat_id) {
319
- const prev = this.activeRequests.get(chat_id);
320
- if (prev) {
321
- this.log(`telegram[${this.channel.name}] interrupting previous request for chat ${chat_id}`);
322
- prev.abort();
323
- }
324
- }
325
- const abortCtrl = new AbortController();
326
- if (chat_id) this.activeRequests.set(chat_id, abortCtrl);
327
-
328
- let text = msg.text || msg.caption || "";
329
-
330
- // ── Incoming photo handling ───────────────────────────────────────────
331
- if (msg.photo && msg.photo.length > 0) {
332
- // Telegram sends multiple sizes; pick the largest
333
- const bestPhoto = msg.photo.reduce((a, b) => (b.file_size > a.file_size ? b : a));
334
- const token = resolveBotToken(this.channel);
335
- const mediaDir = path.join(APX_HOME, "media");
336
- fs.mkdirSync(mediaDir, { recursive: true });
337
- try {
338
- const localPath = await downloadTelegramFile(token, bestPhoto.file_id, mediaDir);
339
- this.log(`telegram[${this.channel.name}] photo saved: ${localPath}`);
340
- appendGlobalMessage({
341
- channel: CHANNELS.TELEGRAM,
342
- direction: "in",
343
- type: "photo",
344
- actor_id: msg.from?.id ? String(msg.from.id) : author,
345
- external_id: String(u.update_id),
346
- author,
347
- body: text || "[photo]",
348
- meta: {
349
- chat_id,
350
- user_id: msg.from?.id || null,
351
- message_id: msg.message_id,
352
- tg_channel: this.channel.name,
353
- local_path: localPath,
354
- file_id: bestPhoto.file_id,
355
- width: bestPhoto.width,
356
- height: bestPhoto.height,
357
- },
358
- });
359
- } catch (e) {
360
- this.log(`telegram[${this.channel.name}] photo download failed: ${e.message}`);
361
- }
362
- // If there's a caption, continue to handle it as text; otherwise return
363
- if (!text) return;
364
- }
365
-
366
- // ── Incoming voice / audio handling ──────────────────────────────────
367
- // Telegram sends `voice` for the press-and-hold mic recording (.oga/opus)
368
- // and `audio` for uploaded audio files (mp3/m4a/etc.). Either way we
369
- // download, run it through Whisper, prefix the result with `[audio] `
370
- // and let the rest of the message flow handle it as plain text.
371
- const incomingAudio = msg.voice || msg.audio;
372
- if (incomingAudio && incomingAudio.file_id) {
373
- const token = resolveBotToken(this.channel);
374
- const mediaDir = path.join(APX_HOME, "media");
375
- fs.mkdirSync(mediaDir, { recursive: true });
376
- // Show "typing…" right away — download + transcription is the slow part of
377
- // a voice message, and the reply-path typing (below) only starts after it,
378
- // so without this the chat sits silent for seconds with no feedback.
379
- const stopVoiceTyping = this._startTyping(chat_id);
380
- let localPath = null;
381
- let transcript = "";
382
- let transcribeError = null;
383
- let transcribeBackend = null;
384
- try {
385
- localPath = await downloadTelegramFile(token, incomingAudio.file_id, mediaDir);
386
- this.log(`telegram[${this.channel.name}] audio saved: ${localPath}`);
387
- } catch (e) {
388
- this.log(`telegram[${this.channel.name}] audio download failed: ${e.message}`);
389
- }
390
- if (localPath) {
391
- try {
392
- const result = await transcribeAudioFile(localPath);
393
- transcript = result.text || "";
394
- transcribeBackend = result.backend;
395
- this.log(`telegram[${this.channel.name}] audio transcribed via ${transcribeBackend} (${transcript.length} chars, lang=${result.language || "?"})`);
396
- } catch (e) {
397
- transcribeError = e.message;
398
- this.log(`telegram[${this.channel.name}] audio transcription failed: ${e.message}`);
399
- }
400
- }
401
- stopVoiceTyping(); // reply-path typing takes over from here
402
- const audioBody = transcript
403
- ? `[audio] ${transcript}`
404
- : `[audio] (transcription unavailable${transcribeError ? ": " + transcribeError : ""})`;
405
-
406
- appendGlobalMessage({
407
- channel: CHANNELS.TELEGRAM,
408
- direction: "in",
409
- type: "audio",
410
- actor_id: msg.from?.id ? String(msg.from.id) : author,
411
- external_id: String(u.update_id),
412
- author,
413
- body: audioBody,
414
- meta: {
415
- chat_id,
416
- user_id: msg.from?.id || null,
417
- message_id: msg.message_id,
418
- tg_channel: this.channel.name,
419
- local_path: localPath,
420
- file_id: incomingAudio.file_id,
421
- duration: incomingAudio.duration,
422
- mime_type: incomingAudio.mime_type,
423
- transcription_backend: transcribeBackend,
424
- transcription_error: transcribeError,
425
- },
426
- });
427
-
428
- // Inject the transcribed text into `text` so the rest of the agent
429
- // pipeline treats it identically to a typed message. If there was a
430
- // caption alongside the audio, prepend the audio marker to it.
431
- text = text ? `${audioBody}\n${text}` : audioBody;
432
- }
433
-
434
- // If there's a pending ask_questions flow for this chat AND the current
435
- // question is free-text, treat this message as the answer rather than a
436
- // brand-new turn. Returns true when the message was consumed.
437
- if (chat_id && text && await this._maybeConsumeAskTextAnswer({ chat_id, text })) {
438
- // Still log the inbound so the chat history records what the user said.
439
- appendGlobalMessage({
440
- channel: CHANNELS.TELEGRAM,
441
- direction: "in",
442
- type: "user",
443
- actor_id: msg.from?.id ? String(msg.from.id) : author,
444
- external_id: String(u.update_id),
445
- author,
446
- body: text,
447
- meta: {
448
- chat_id,
449
- user_id: msg.from?.id || null,
450
- message_id: msg.message_id,
451
- tg_channel: this.channel.name,
452
- ask_answer: true,
453
- },
454
- });
455
- return;
456
- }
457
-
458
- // /reset or /new wipes the rolling context for this chat. We just
459
- // remember a marker timestamp; subsequent inbounds will only consider
460
- // history newer than this. Implemented by writing a synthetic message
461
- // with a known marker so getRecentTelegramTurns naturally cuts off.
462
- const isReset = /^\/(reset|new)\b/i.test(text.trim());
463
-
464
- // Pull the prior conversation BEFORE we log this inbound — so the
465
- // current message isn't part of its own history. We then prune anything
466
- // older than the most recent /reset for this chat_id.
467
- let previousMessages = [];
468
- if (chat_id && !isReset) {
469
- previousMessages = getRecentTelegramTurnsFromFs({
470
- chat_id,
471
- keepRecent: 40,
472
- max_age_hours: 24,
473
- });
474
- // Progressive compaction (Pieza 3) runs OUT of the reply path: if this
475
- // chat is over threshold, summarize the oldest turns in the background so
476
- // the next turn reads a [RESUMEN COMPACTADO] instead of raw history. Never
477
- // awaited — adds zero latency to this reply, degrades gracefully.
478
- compactChannelIfNeeded({
479
- channel: CHANNELS.TELEGRAM,
480
- chat_id,
481
- config: this.globalConfig,
482
- log: this.log,
483
- }).catch(() => {});
484
- // Honour a /reset marker: drop everything up to and including it.
485
- const lastResetIdx = (() => {
486
- for (let i = previousMessages.length - 1; i >= 0; i--) {
487
- if (
488
- previousMessages[i].role === "user" &&
489
- /^\/(reset|new)\b/i.test(previousMessages[i].content.trim())
490
- ) {
491
- return i;
492
- }
493
- }
494
- return -1;
495
- })();
496
- if (lastResetIdx >= 0) {
497
- previousMessages = previousMessages.slice(lastResetIdx + 1);
498
- }
499
- }
500
-
501
- // Always log inbound to global store (~/.apx/messages/telegram/)
502
- appendGlobalMessage({
503
- channel: CHANNELS.TELEGRAM,
504
- direction: "in",
505
- type: "user",
506
- actor_id: msg.from?.id ? String(msg.from.id) : author,
507
- external_id: String(u.update_id),
508
- author,
509
- body: text,
510
- meta: {
511
- chat_id,
512
- user_id: msg.from?.id || null,
513
- message_id: msg.message_id,
514
- tg_channel: this.channel.name,
515
- },
516
- });
517
-
518
- // Super-agent is ALWAYS active on Telegram: respond_with_engine === false
519
- // used to silently drop user messages, which looked to the user like the
520
- // bot ignored them. Honour the legacy flag only as a soft hint (skip the
521
- // routed-agent shortcut so we fall straight to super-agent) but never let
522
- // it short-circuit the whole reply. To genuinely silence the bot, disable
523
- // the channel entirely (telegram.enabled = false in config).
524
- const skipRoutedAgent = this.channel.respond_with_engine === false;
525
- if (!text) return;
526
-
527
- // Short-circuit /reset / /new: send an ack and don't engage the engine.
528
- // The marker we just logged is enough — getRecentTelegramTurns will
529
- // honor it for future messages.
530
- if (isReset) {
531
- try {
532
- const ack = "Done, context cleared. Starting fresh. What do you need?";
533
- await this._send({ chat_id, text: ack });
534
- appendGlobalMessage({
535
- channel: CHANNELS.TELEGRAM,
536
- direction: "out",
537
- type: "agent",
538
- actor_id: SUPERAGENT_ACTOR_ID,
539
- actor_kind: "superagent",
540
- agent_slug: SUPERAGENT_ACTOR_ID,
541
- author: resolveAgentName(this.globalConfig),
542
- body: ack,
543
- meta: { chat_id, tg_channel: this.channel.name, in_reply_to: u.update_id, reset: true },
544
- });
545
- } catch (e) {
546
- this.log(`telegram[${this.channel.name}] reset ack failed: ${e.message}`);
547
- }
548
- return;
549
- }
550
-
551
- // Start "typing..." indicator. Stops when we send the reply (or fail).
552
- const stopTyping = this._startTyping(chat_id);
553
-
554
- let replyText;
555
- let replyAuthor;
556
- let replyActorId; // stable id: super_agent | agent slug
557
- let replyKind; // actor_kind: superagent | agent
558
- const projectCfg = target.config || this.globalConfig;
559
- // Display name for the super-agent persona on this channel (from identity.json).
560
- const agentDisplay = resolveAgentName(this.globalConfig);
561
-
562
- // Try the project's chosen agent first (skipped if the legacy
563
- // respond_with_engine === false hint asked to bypass routed agents).
564
- const routeSlug = skipRoutedAgent ? null : this.channel.route_to_agent;
565
- if (routeSlug) {
566
- const agent = readAgents(target.path).find((a) => a.slug === routeSlug);
567
- if (agent && agent.fields.Model) {
568
- try {
569
- const system = buildAgentSystem(target, agent, {
570
- invocation: "telegram",
571
- channel: this.channel.name,
572
- caller: author,
573
- extraParts: [relationshipBlock],
574
- });
575
- const result = await callEngine({
576
- modelId: agent.fields.Model,
577
- system,
578
- messages: [{ role: "user", content: text }],
579
- config: projectCfg,
580
- });
581
- replyText = result.text;
582
- replyAuthor = agent.slug;
583
- replyActorId = agent.slug;
584
- replyKind = "agent";
585
- } catch (e) {
586
- this.log(`telegram[${this.channel.name}] agent reply failed: ${e.message}`);
587
- replyText = `[apx error] ${e.message.slice(0, 200)}`;
588
- replyAuthor = agentDisplay;
589
- replyActorId = SUPERAGENT_ACTOR_ID;
590
- replyKind = "superagent";
591
- }
592
- } else {
593
- this.log(
594
- `telegram[${this.channel.name}] route_to_agent="${routeSlug}" not usable (missing or no model) → trying super-agent`
595
- );
596
- }
597
- }
598
-
599
- // Fallback: super-agent — STREAMED.
600
- // Each iteration's assistant text is sent to Telegram as its own message
601
- // the moment the model produces it (its running commentary), so the user
602
- // sees a real back-and-forth instead of one giant final dump. Tool calls
603
- // are logged to the message store — visible via apx log / apx search and
604
- // to channels that render tools — but NEVER sent to Telegram; tools are
605
- // internal. The conversation saved on disk is the full, real exchange;
606
- // Telegram is just the prose-only view of it.
607
- let saUsage = null;
608
- let streamedCount = 0;
609
- let lastStreamedText = "";
610
- // Telegram shows the user ONLY prose — never the tool calls. On an action
611
- // request the model often jumps straight to a tool with no preamble text,
612
- // so the user would stare at a silent chat until the final reply. Send one
613
- // short localized heads-up the moment real work starts (first tool_start),
614
- // but only if the agent didn't already write its own "on it" line.
615
- let sentHeadsUp = false;
616
- const headsUpPhrase = () => {
617
- const lang = (this.globalConfig?.user?.language || "es").slice(0, 2);
618
- const byLang = {
619
- es: "Dale, estoy con eso… 🛠️",
620
- en: "On it — working on that… 🛠️",
621
- pt: "Já estou nisso… 🛠️",
622
- };
623
- return byLang[lang] || byLang.es;
624
- };
625
- if (!replyText && isSuperAgentEnabled(this.globalConfig)) {
626
- const onEvent = async (ev) => {
627
- try {
628
- if (ev.type === "tool_start" && !sentHeadsUp && streamedCount === 0) {
629
- sentHeadsUp = true;
630
- const heads = headsUpPhrase();
631
- await this._send({ chat_id, text: heads });
632
- appendGlobalMessage({
633
- channel: CHANNELS.TELEGRAM,
634
- direction: "out",
635
- type: "agent",
636
- actor_id: SUPERAGENT_ACTOR_ID,
637
- actor_kind: "superagent",
638
- agent_slug: SUPERAGENT_ACTOR_ID,
639
- author: agentDisplay,
640
- body: heads,
641
- meta: { chat_id, tg_channel: this.channel.name, in_reply_to: u.update_id, heads_up: true },
642
- });
643
- return;
644
- }
645
- if (ev.type === "assistant_text" && ev.text) {
646
- const piece = stripThinking(ev.text).trim();
647
- if (!piece) return;
648
- // Skip post-tool segments that just restate the pre-tool intro —
649
- // weaker models (gemini-flash et al.) frequently paraphrase the
650
- // same content twice within a single turn.
651
- if (lastStreamedText && isLikelyDuplicate(piece, lastStreamedText)) {
652
- return;
653
- }
654
- await this._send({ chat_id, text: piece });
655
- lastStreamedText = piece;
656
- streamedCount += 1;
657
- appendGlobalMessage({
658
- channel: CHANNELS.TELEGRAM,
659
- direction: "out",
660
- type: "agent",
661
- actor_id: SUPERAGENT_ACTOR_ID,
662
- actor_kind: "superagent",
663
- agent_slug: SUPERAGENT_ACTOR_ID,
664
- author: agentDisplay,
665
- body: piece,
666
- meta: {
667
- chat_id,
668
- tg_channel: this.channel.name,
669
- in_reply_to: u.update_id,
670
- streamed: true,
671
- iteration: ev.iteration,
672
- },
673
- });
674
- } else if (ev.type === "tool_result" && ev.trace) {
675
- // Logged for the audit trail / other channels — NOT sent to Telegram.
676
- const t = ev.trace;
677
- appendGlobalMessage({
678
- channel: CHANNELS.TELEGRAM,
679
- direction: "out",
680
- type: "tool",
681
- actor_id: t.tool,
682
- actor_kind: "tool",
683
- author: agentDisplay,
684
- body: `${t.tool}(${JSON.stringify(t.args || {}).slice(0, 200)})`,
685
- meta: {
686
- chat_id,
687
- tg_channel: this.channel.name,
688
- in_reply_to: u.update_id,
689
- tool: t.tool,
690
- args: t.args,
691
- result: t.result,
692
- iteration: ev.iteration,
693
- },
694
- });
695
- }
696
- } catch (e) {
697
- // A failed intermediate send must not abort the whole run.
698
- this.log(`telegram[${this.channel.name}] stream event failed: ${e.message}`);
699
- }
700
- };
701
-
702
- const confirmAdapter = createTelegramConfirmAdapter({
703
- token: resolveBotToken(this.channel),
704
- chatId: chat_id,
705
- pendingStore: getConfirmStore(),
706
- });
707
-
708
- // `/slug ...` shortcut: load the matching skill body into contextNote
709
- // and strip the prefix from the user prompt before sending to the loop.
710
- const slashed = tryResolveSkillCommand(text, { projectPath: target?.path });
711
- const slashedPrompt = slashed.handled ? slashed.prompt : text;
712
- const slashedContextNote = slashed.handled ? slashed.contextNote : "";
713
-
714
- try {
715
- const sa = await runSuperAgent({
716
- globalConfig: this.globalConfig,
717
- projects: this.projects,
718
- plugins: this.plugins,
719
- registries: this.registries,
720
- prompt: slashedPrompt,
721
- previousMessages,
722
- channel: CHANNELS.TELEGRAM,
723
- relationshipBlock,
724
- allowedTools,
725
- contextNote: slashedContextNote || undefined,
726
- channelMeta: buildTelegramMeta({
727
- channelName: this.channel.name,
728
- author,
729
- chatId: chat_id,
730
- target,
731
- routeToAgent: this.channel.route_to_agent,
732
- }),
733
- signal: abortCtrl.signal,
734
- onEvent,
735
- requestConfirmation: confirmAdapter.requestConfirmation,
736
- });
737
- replyText = sa.text;
738
- replyAuthor = sa.name || agentDisplay;
739
- replyActorId = SUPERAGENT_ACTOR_ID;
740
- replyKind = "superagent";
741
- saUsage = sa.usage;
742
-
743
- // ── ask_questions integration ────────────────────────────────────
744
- // If the super-agent ended this turn by calling ask_questions, hand
745
- // off to the inline-keyboard flow instead of sending the bare
746
- // assistant text. The flow keeps state per chat_id and re-runs the
747
- // super-agent once every answer is collected.
748
- const askQuestions = askFlow.extractAskQuestionsFromTrace(sa.trace);
749
- if (askQuestions && chat_id) {
750
- if (chat_id) this.activeRequests.delete(chat_id);
751
- stopTyping();
752
- try {
753
- await this._startAskFlow({
754
- chat_id,
755
- projectId: target?.id,
756
- authorId: msg.from?.id,
757
- questions: askQuestions,
758
- author,
759
- agentDisplay,
760
- relationshipBlock,
761
- allowedTools,
762
- target,
763
- sender,
764
- update_id: u.update_id,
765
- });
766
- } catch (e) {
767
- this.log(`telegram[${this.channel.name}] ask flow start failed: ${e.message}`);
768
- }
769
- return; // The reply for this turn IS the ask flow.
770
- }
771
- } catch (e) {
772
- if (abortCtrl.signal.aborted) {
773
- // A newer message superseded this one. Whatever streamed so far is
774
- // already sent + logged; the newer message's run continues the
775
- // thread from that history.
776
- this.log(`telegram[${this.channel.name}] request aborted for chat ${chat_id}`);
777
- if (chat_id) this.activeRequests.delete(chat_id);
778
- stopTyping();
779
- return;
780
- }
781
- this.log(`telegram[${this.channel.name}] super-agent failed: ${e.message}`);
782
- // Surface the failure to the user instead of silently dropping the
783
- // turn — otherwise from the chat side it looks like the bot ignored
784
- // the message. Keep the message short and non-leaking.
785
- replyText = `⚠️ Could not generate a reply right now (${e.message || "internal error"}).`;
786
- replyAuthor = agentDisplay;
787
- replyActorId = SUPERAGENT_ACTOR_ID;
788
- replyKind = "superagent";
789
- }
790
- }
791
-
792
- if (chat_id) this.activeRequests.delete(chat_id);
793
-
794
- // Final answer. The intermediate prose was already streamed; only send the
795
- // final text if it's non-empty AND not a duplicate of the last streamed
796
- // piece (the loop can end on an iteration whose text was already sent).
797
- // If nothing streamed and there's no final text, send a minimal ack so the
798
- // turn isn't silently empty.
799
- const finalClean = replyText ? stripThinking(replyText).trim() : "";
800
- let toSend = "";
801
- // Fuzzy dedupe against the last streamed segment: catches paraphrases
802
- // (Jaccard ≥ 0.4 or short-mostly-inside-long), not just exact matches.
803
- if (finalClean && !isLikelyDuplicate(finalClean, lastStreamedText) && finalClean !== lastStreamedText) {
804
- toSend = finalClean;
805
- } else if (!finalClean && streamedCount === 0) {
806
- toSend = "Listo.";
807
- }
808
-
809
- stopTyping();
810
- if (!toSend) return; // everything was already streamed — nothing left to send
811
-
812
- try {
813
- await this._send({ chat_id, text: toSend });
814
- const meta = {
815
- chat_id,
816
- tg_channel: this.channel.name,
817
- in_reply_to: u.update_id,
818
- final: true,
819
- };
820
- if (replyText && stripThinking(replyText) !== replyText) meta.thinking_stripped = true;
821
- if (saUsage) meta.usage = saUsage;
822
- appendGlobalMessage({
823
- channel: CHANNELS.TELEGRAM,
824
- direction: "out",
825
- type: "agent",
826
- actor_id: replyActorId || SUPERAGENT_ACTOR_ID,
827
- actor_kind: replyKind || "superagent",
828
- agent_slug: replyActorId || SUPERAGENT_ACTOR_ID,
829
- author: replyAuthor || agentDisplay,
830
- body: toSend,
831
- meta,
832
- });
833
- } catch (e) {
834
- this.log(`telegram[${this.channel.name}] send-back error: ${e.message}`);
835
- appendGlobalMessage({
836
- channel: CHANNELS.TELEGRAM,
837
- direction: "out",
838
- type: "agent",
839
- actor_id: replyActorId || SUPERAGENT_ACTOR_ID,
840
- actor_kind: replyKind || "superagent",
841
- agent_slug: replyActorId || SUPERAGENT_ACTOR_ID,
842
- author: replyAuthor || agentDisplay,
843
- body: `[send_failed] ${toSend}`,
844
- meta: {
845
- chat_id,
846
- tg_channel: this.channel.name,
847
- in_reply_to: u.update_id,
848
- send_error: e.message,
849
- ...(saUsage ? { usage: saUsage } : {}),
850
- },
851
- });
852
- }
181
+ return handleUpdate(this, u);
853
182
  }
854
183
 
855
184
  async _handleCallbackQuery(callbackQuery) {
@@ -1220,10 +549,6 @@ class ChannelPoller {
1220
549
  }
1221
550
  }
1222
551
 
1223
- function sleep(ms) {
1224
- return new Promise((r) => setTimeout(r, ms));
1225
- }
1226
-
1227
552
  // ---------- plugin export ---------------------------------------------------
1228
553
 
1229
554
  export default {