@agentprojectcontext/apx 1.33.0 → 1.34.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.
Files changed (172) hide show
  1. package/package.json +1 -1
  2. package/skills/apc-context/SKILL.md +2 -5
  3. package/skills/apx/SKILL.md +49 -61
  4. package/src/core/agent/a2a/reply.js +48 -0
  5. package/src/core/agent/build-agent-system.js +4 -3
  6. package/src/core/agent/channels/voice-context.js +98 -0
  7. package/src/core/agent/memory.js +2 -1
  8. package/src/core/agent/prompt-builder.js +2 -1
  9. package/src/core/agent/prompts/modes/code-build.md +1 -0
  10. package/src/core/agent/prompts/modes/code-plan.md +1 -0
  11. package/src/core/agent/prompts/modes/index.js +28 -0
  12. package/src/core/agent/skills/loader.js +22 -18
  13. package/src/core/agent/stream/turn-accumulator.js +73 -0
  14. package/src/core/agent/suggestions.js +37 -0
  15. package/src/core/agent/tools/handlers/add-project.js +5 -2
  16. package/src/core/agent/tools/handlers/call-runtime.js +3 -2
  17. package/src/core/agent/tools/handlers/transcribe-audio.js +1 -1
  18. package/src/core/agent/tools/helpers.js +2 -2
  19. package/src/core/agent/tools/names.js +138 -0
  20. package/src/core/agent/tools/registry-bridge.js +6 -14
  21. package/src/core/agent/tools/registry.js +68 -65
  22. package/src/core/apc/context-copy.js +27 -0
  23. package/src/core/apc/notes.js +19 -0
  24. package/src/core/apc/parser.js +13 -6
  25. package/src/core/apc/paths.js +87 -0
  26. package/src/core/apc/scaffold.js +82 -74
  27. package/src/core/apc/skill-sync.js +13 -1
  28. package/src/core/channels/telegram/dispatch.js +595 -0
  29. package/src/core/channels/telegram/helpers.js +130 -0
  30. package/src/core/config/index.js +3 -2
  31. package/src/core/config/redact.js +95 -0
  32. package/src/core/constants/channels.js +2 -0
  33. package/src/core/constants/code-modes.js +10 -0
  34. package/src/core/constants/index.js +1 -0
  35. package/src/core/deck/manifest.js +186 -0
  36. package/src/core/engines/catalog.js +83 -0
  37. package/src/core/engines/gemini.js +28 -11
  38. package/src/core/engines/index.js +11 -1
  39. package/src/core/{tools → http-tools}/browser.js +0 -1
  40. package/src/core/{tools → http-tools}/fetch.js +0 -1
  41. package/src/core/{tools → http-tools}/glob.js +0 -1
  42. package/src/core/{tools → http-tools}/grep.js +0 -1
  43. package/src/core/{tools → http-tools}/registry.js +0 -1
  44. package/src/core/{tools → http-tools}/search.js +0 -1
  45. package/src/core/i18n/en.js +9 -0
  46. package/src/core/i18n/es.js +12 -0
  47. package/src/core/i18n/index.js +54 -0
  48. package/src/core/i18n/pt.js +9 -0
  49. package/src/core/identity/telegram.js +2 -1
  50. package/src/core/mcp/runner.js +272 -14
  51. package/src/core/mcp/sources.js +3 -2
  52. package/src/core/routines/index.js +16 -0
  53. package/src/{host/daemon/routines.js → core/routines/runner.js} +36 -103
  54. package/src/core/runtime-skills/apc-context/SKILL.md +159 -0
  55. package/src/core/runtime-skills/apx/SKILL.md +95 -0
  56. package/src/core/runtime-skills/apx-mcp/SKILL.md +116 -0
  57. package/src/core/runtime-skills/{claude-code.md → claude-code/SKILL.md} +1 -0
  58. package/src/core/runtime-skills/{codex-cli.md → codex-cli/SKILL.md} +1 -0
  59. package/src/core/runtime-skills/{opencode-cli.md → opencode-cli/SKILL.md} +1 -0
  60. package/src/core/runtime-skills/{openrouter.md → openrouter/SKILL.md} +1 -0
  61. package/src/{host/daemon/env-detect.js → core/runtimes/detect.js} +1 -1
  62. package/src/core/stores/code-sessions.js +50 -2
  63. package/src/core/stores/routine-memory.js +1 -1
  64. package/src/core/stores/sessions-search.js +121 -0
  65. package/src/core/stores/sessions.js +38 -0
  66. package/src/core/vars/index.js +14 -0
  67. package/src/core/vars/interpolate.js +86 -0
  68. package/src/core/vars/sources.js +151 -0
  69. package/src/core/voice/audio-decode.js +38 -0
  70. package/src/core/voice/transcription.js +225 -0
  71. package/src/host/daemon/api/admin-config.js +5 -82
  72. package/src/host/daemon/api/agents.js +5 -5
  73. package/src/host/daemon/api/code.js +17 -169
  74. package/src/host/daemon/api/config.js +3 -4
  75. package/src/host/daemon/api/conversations.js +8 -29
  76. package/src/host/daemon/api/deck.js +37 -404
  77. package/src/host/daemon/api/engines.js +1 -50
  78. package/src/host/daemon/api/exec.js +1 -1
  79. package/src/host/daemon/api/mcps.js +32 -0
  80. package/src/host/daemon/api/routines.js +1 -1
  81. package/src/host/daemon/api/runtimes.js +4 -3
  82. package/src/host/daemon/api/sessions-search.js +24 -140
  83. package/src/host/daemon/api/sessions.js +12 -30
  84. package/src/host/daemon/api/shared.js +2 -1
  85. package/src/host/daemon/api/telegram.js +1 -11
  86. package/src/host/daemon/api/tools.js +6 -6
  87. package/src/host/daemon/api/transcribe.js +2 -2
  88. package/src/host/daemon/api/vars.js +137 -0
  89. package/src/host/daemon/api/voice.js +13 -290
  90. package/src/host/daemon/api.js +2 -0
  91. package/src/host/daemon/db.js +6 -6
  92. package/src/host/daemon/deck-exec.js +148 -0
  93. package/src/host/daemon/index.js +3 -3
  94. package/src/host/daemon/plugins/telegram/index.js +24 -687
  95. package/src/host/daemon/routines-scheduler.js +64 -0
  96. package/src/host/daemon/smoke.js +3 -2
  97. package/src/host/daemon/whisper-server.js +225 -0
  98. package/src/interfaces/cli/commands/agent.js +3 -2
  99. package/src/interfaces/cli/commands/command.js +2 -3
  100. package/src/interfaces/cli/commands/messages.js +6 -2
  101. package/src/interfaces/cli/commands/pair.js +5 -4
  102. package/src/interfaces/cli/commands/search.js +1 -1
  103. package/src/interfaces/cli/commands/sessions.js +3 -2
  104. package/src/interfaces/cli/commands/skills.js +36 -55
  105. package/src/interfaces/web/dist/assets/index-DdmSRtsz.css +1 -0
  106. package/src/interfaces/web/dist/assets/index-M4FspaCH.js +613 -0
  107. package/src/interfaces/web/dist/assets/index-M4FspaCH.js.map +1 -0
  108. package/src/interfaces/web/dist/index.html +2 -2
  109. package/src/interfaces/web/package-lock.json +182 -182
  110. package/src/interfaces/web/src/components/ModelCombobox.tsx +44 -8
  111. package/src/interfaces/web/src/components/TelegramChannelDialog.tsx +1 -1
  112. package/src/interfaces/web/src/components/chat/AskAnswersCard.tsx +76 -0
  113. package/src/interfaces/web/src/components/chat/MessageBubble.tsx +16 -3
  114. package/src/interfaces/web/src/components/chat/MessageList.tsx +23 -1
  115. package/src/interfaces/web/src/components/chat/ModelPicker.tsx +3 -1
  116. package/src/interfaces/web/src/components/code/CodeArtifactsTab.tsx +4 -4
  117. package/src/interfaces/web/src/components/code/CodeChangesTab.tsx +1 -1
  118. package/src/interfaces/web/src/components/code/CodeFileTree.tsx +3 -2
  119. package/src/interfaces/web/src/components/code/CodeFileViewer.tsx +3 -2
  120. package/src/interfaces/web/src/components/code/CodeTerminal.tsx +3 -2
  121. package/src/interfaces/web/src/components/config/GlobalConfigEditor.tsx +2 -1
  122. package/src/interfaces/web/src/components/deck/WidgetRow.tsx +2 -1
  123. package/src/interfaces/web/src/components/inputs/KeyValueList.tsx +93 -0
  124. package/src/interfaces/web/src/components/inputs/VarTokenInput.tsx +449 -0
  125. package/src/interfaces/web/src/components/settings/DefaultRouterCard.tsx +2 -1
  126. package/src/interfaces/web/src/components/settings/EnginesPanel.tsx +2 -2
  127. package/src/interfaces/web/src/components/settings/MemoryPanel.tsx +5 -4
  128. package/src/interfaces/web/src/components/settings/providers/ProviderCard.tsx +3 -2
  129. package/src/interfaces/web/src/components/settings/providers/ProviderModal.tsx +3 -2
  130. package/src/interfaces/web/src/components/ui/chat-input.tsx +5 -4
  131. package/src/interfaces/web/src/components/ui/sidebar.tsx +3 -2
  132. package/src/interfaces/web/src/components/voice/VoiceProviderModal.tsx +2 -1
  133. package/src/interfaces/web/src/constants/index.ts +1 -1
  134. package/src/interfaces/web/src/i18n/en.ts +174 -7
  135. package/src/interfaces/web/src/i18n/es.ts +179 -15
  136. package/src/interfaces/web/src/lib/api/mcps.ts +25 -0
  137. package/src/interfaces/web/src/lib/api/vars.ts +38 -0
  138. package/src/interfaces/web/src/lib/api.ts +1 -0
  139. package/src/interfaces/web/src/screens/ProjectScreen.tsx +8 -31
  140. package/src/interfaces/web/src/screens/modules/CodeScreen.tsx +1 -1
  141. package/src/interfaces/web/src/screens/modules/DeckScreen.tsx +4 -3
  142. package/src/interfaces/web/src/screens/modules/DesktopScreen.tsx +7 -6
  143. package/src/interfaces/web/src/screens/modules/VoiceScreen.tsx +4 -3
  144. package/src/interfaces/web/src/screens/project/AgentDetailScreen.tsx +1 -1
  145. package/src/interfaces/web/src/screens/project/ConfigTab.tsx +132 -1
  146. package/src/interfaces/web/src/screens/project/McpsTab.tsx +549 -104
  147. package/src/interfaces/web/src/screens/project/RoutinesTab.tsx +1 -1
  148. package/src/interfaces/web/src/screens/project/VarsTab.tsx +300 -0
  149. package/src/interfaces/web/src/types/daemon.ts +5 -0
  150. package/src/host/daemon/transcription.js +0 -538
  151. package/src/host/daemon/whisper-transcribe.py +0 -73
  152. package/src/interfaces/web/dist/assets/index-7dVT2O1S.css +0 -1
  153. package/src/interfaces/web/dist/assets/index-DWsE_8Nz.js +0 -602
  154. package/src/interfaces/web/dist/assets/index-DWsE_8Nz.js.map +0 -1
  155. /package/src/{host/daemon → core/apc}/projects-helpers.js +0 -0
  156. /package/src/{host/daemon/plugins → core/channels}/telegram/ask.js +0 -0
  157. /package/src/{host/daemon/plugins → core/channels}/telegram/media.js +0 -0
  158. /package/src/core/{tools → http-tools}/index.js +0 -0
  159. /package/{skills → src/core/runtime-skills}/apx-agency-agents/SKILL.md +0 -0
  160. /package/{skills → src/core/runtime-skills}/apx-agent/SKILL.md +0 -0
  161. /package/{skills → src/core/runtime-skills}/apx-mcp-builder/SKILL.md +0 -0
  162. /package/{skills → src/core/runtime-skills}/apx-project/SKILL.md +0 -0
  163. /package/{skills → src/core/runtime-skills}/apx-routine/SKILL.md +0 -0
  164. /package/{skills → src/core/runtime-skills}/apx-runtime/SKILL.md +0 -0
  165. /package/{skills → src/core/runtime-skills}/apx-sessions/SKILL.md +0 -0
  166. /package/{skills → src/core/runtime-skills}/apx-skill-builder/SKILL.md +0 -0
  167. /package/{skills → src/core/runtime-skills}/apx-task/SKILL.md +0 -0
  168. /package/{skills → src/core/runtime-skills}/apx-telegram/SKILL.md +0 -0
  169. /package/{skills → src/core/runtime-skills}/apx-voice/SKILL.md +0 -0
  170. /package/src/{host/daemon/compact.js → core/stores/conversations-compactor.js} +0 -0
  171. /package/src/{host/daemon → core/stores}/conversations.js +0 -0
  172. /package/src/{host/daemon → core/util}/thinking.js +0 -0
@@ -0,0 +1,595 @@
1
+ // Inbound Telegram update dispatcher.
2
+ //
3
+ // Extracted from the ChannelPoller class so index.js stays under ~800 lines
4
+ // and the routing logic for text/photo/voice/document updates lives on its
5
+ // own. Takes the poller instance as `self`; every `this.X` in the original
6
+ // method becomes `self.X` here. The poller exposes _handleUpdate as a thin
7
+ // facade that delegates to handleUpdate(this, u).
8
+ //
9
+ // IMPORTANT: this module needs the same imports the original index.js had
10
+ // in module scope, because the extracted body references identifiers like
11
+ // `appendGlobalMessage`, `CHANNELS`, `nowIso`, etc. Top-level imports here
12
+ // keep that scope intact — earlier splits forgot them and the bug only
13
+ // surfaced when a real telegram update arrived (ReferenceError at runtime).
14
+ import path from "node:path";
15
+ import { callEngine } from "#core/engines/index.js";
16
+ import { runSuperAgent, isSuperAgentEnabled } from "#core/agent/super-agent.js";
17
+ import { stripThinking } from "#core/util/thinking.js";
18
+ import { getRecentTelegramTurnsFromFs, appendGlobalMessage } from "#core/stores/messages.js";
19
+ import { compactChannelIfNeeded } from "#core/memory/index.js";
20
+ import { readAgents } from "#core/apc/parser.js";
21
+ import { buildAgentSystem } from "#core/agent/build-agent-system.js";
22
+ import { transcribe as transcribeAudioFile } from "#core/voice/transcription.js";
23
+ import { resolveAgentName, SUPERAGENT_ACTOR_ID } from "#core/identity/index.js";
24
+ import { registerSender, resolveAllowedTools } from "#core/identity/telegram.js";
25
+ import { buildRelationshipBlock } from "#core/agent/index.js";
26
+ import { getConfirmationStore as getConfirmStore } from "#core/confirmation/pending-store.js";
27
+ import { CHANNELS } from "#core/constants/channels.js";
28
+ import { tryResolveSkillCommand } from "#core/agent/skills/trigger.js";
29
+ import { createTelegramConfirmAdapter } from "#core/confirmation/adapters/telegram.js";
30
+ import * as askFlow from "./ask.js";
31
+ import { buildTelegramMeta, resolveBotToken, sleep } from "./helpers.js";
32
+ import { sendPhoto, sendVoice, sendDocument, sendAudio, downloadTelegramFile, API_BASE } from "./media.js";
33
+ import { t, resolveLang } from "#core/i18n/index.js";
34
+
35
+ const nowIso = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
36
+
37
+ export async function handleUpdate(self, u) {
38
+ self.lastUpdateAt = nowIso();
39
+
40
+ // Inline keyboard button press: route to the confirmation adapter.
41
+ if (u.callback_query) {
42
+ await self._handleCallbackQuery(u.callback_query);
43
+ return;
44
+ }
45
+
46
+ const msg = u.message || u.edited_message;
47
+ if (!msg) return;
48
+ const target = self.resolveProject();
49
+ if (!target) {
50
+ self.log(`telegram[${self.channel.name}] update ${u.update_id} ignored — no target project`);
51
+ return;
52
+ }
53
+ const author =
54
+ msg.from?.username
55
+ ? "@" + msg.from.username
56
+ : `${msg.from?.first_name || ""} ${msg.from?.last_name || ""}`.trim() || "unknown";
57
+ const chat_id = msg.chat?.id;
58
+
59
+ // Resolve WHO is writing (owner / known contact / guest), keyed by the
60
+ // stable Telegram user_id. Records unknown senders and, on a fresh private
61
+ // channel with no owner yet, claims this sender as the owner. Mutates the
62
+ // in-memory globalConfig in place so later messages in this daemon session
63
+ // see the update. The resulting block is injected into whichever agent
64
+ // answers (super-agent OR a routed project agent).
65
+ const { sender } = registerSender({
66
+ cfg: self.globalConfig,
67
+ channelName: self.channel.name,
68
+ from: msg.from,
69
+ chatType: msg.chat?.type,
70
+ });
71
+ const relationshipBlock = buildRelationshipBlock(sender);
72
+ // Role-based tool gating for the super-agent path (guests → no tools).
73
+ const allowedTools = resolveAllowedTools(self.globalConfig, sender);
74
+
75
+ // Default Interrupt: abort any running request for this chat_id
76
+ if (chat_id) {
77
+ const prev = self.activeRequests.get(chat_id);
78
+ if (prev) {
79
+ self.log(`telegram[${self.channel.name}] interrupting previous request for chat ${chat_id}`);
80
+ prev.abort();
81
+ }
82
+ }
83
+ const abortCtrl = new AbortController();
84
+ if (chat_id) self.activeRequests.set(chat_id, abortCtrl);
85
+
86
+ let text = msg.text || msg.caption || "";
87
+
88
+ // ── Incoming photo handling ───────────────────────────────────────────
89
+ if (msg.photo && msg.photo.length > 0) {
90
+ // Telegram sends multiple sizes; pick the largest
91
+ const bestPhoto = msg.photo.reduce((a, b) => (b.file_size > a.file_size ? b : a));
92
+ const token = resolveBotToken(self.channel);
93
+ const mediaDir = path.join(APX_HOME, "media");
94
+ fs.mkdirSync(mediaDir, { recursive: true });
95
+ try {
96
+ const localPath = await downloadTelegramFile(token, bestPhoto.file_id, mediaDir);
97
+ self.log(`telegram[${self.channel.name}] photo saved: ${localPath}`);
98
+ appendGlobalMessage({
99
+ channel: CHANNELS.TELEGRAM,
100
+ direction: "in",
101
+ type: "photo",
102
+ actor_id: msg.from?.id ? String(msg.from.id) : author,
103
+ external_id: String(u.update_id),
104
+ author,
105
+ body: text || "[photo]",
106
+ meta: {
107
+ chat_id,
108
+ user_id: msg.from?.id || null,
109
+ message_id: msg.message_id,
110
+ tg_channel: self.channel.name,
111
+ local_path: localPath,
112
+ file_id: bestPhoto.file_id,
113
+ width: bestPhoto.width,
114
+ height: bestPhoto.height,
115
+ },
116
+ });
117
+ } catch (e) {
118
+ self.log(`telegram[${self.channel.name}] photo download failed: ${e.message}`);
119
+ }
120
+ // If there's a caption, continue to handle it as text; otherwise return
121
+ if (!text) return;
122
+ }
123
+
124
+ // ── Incoming voice / audio handling ──────────────────────────────────
125
+ // Telegram sends `voice` for the press-and-hold mic recording (.oga/opus)
126
+ // and `audio` for uploaded audio files (mp3/m4a/etc.). Either way we
127
+ // download, run it through Whisper, prefix the result with `[audio] `
128
+ // and let the rest of the message flow handle it as plain text.
129
+ const incomingAudio = msg.voice || msg.audio;
130
+ if (incomingAudio && incomingAudio.file_id) {
131
+ const token = resolveBotToken(self.channel);
132
+ const mediaDir = path.join(APX_HOME, "media");
133
+ fs.mkdirSync(mediaDir, { recursive: true });
134
+ // Show "typing…" right away — download + transcription is the slow part of
135
+ // a voice message, and the reply-path typing (below) only starts after it,
136
+ // so without this the chat sits silent for seconds with no feedback.
137
+ const stopVoiceTyping = self._startTyping(chat_id);
138
+ let localPath = null;
139
+ let transcript = "";
140
+ let transcribeError = null;
141
+ let transcribeBackend = null;
142
+ try {
143
+ localPath = await downloadTelegramFile(token, incomingAudio.file_id, mediaDir);
144
+ self.log(`telegram[${self.channel.name}] audio saved: ${localPath}`);
145
+ } catch (e) {
146
+ self.log(`telegram[${self.channel.name}] audio download failed: ${e.message}`);
147
+ }
148
+ if (localPath) {
149
+ try {
150
+ const result = await transcribeAudioFile(localPath);
151
+ transcript = result.text || "";
152
+ transcribeBackend = result.backend;
153
+ self.log(`telegram[${self.channel.name}] audio transcribed via ${transcribeBackend} (${transcript.length} chars, lang=${result.language || "?"})`);
154
+ } catch (e) {
155
+ transcribeError = e.message;
156
+ self.log(`telegram[${self.channel.name}] audio transcription failed: ${e.message}`);
157
+ }
158
+ }
159
+ stopVoiceTyping(); // reply-path typing takes over from here
160
+ const audioBody = transcript
161
+ ? `[audio] ${transcript}`
162
+ : `[audio] (transcription unavailable${transcribeError ? ": " + transcribeError : ""})`;
163
+
164
+ appendGlobalMessage({
165
+ channel: CHANNELS.TELEGRAM,
166
+ direction: "in",
167
+ type: "audio",
168
+ actor_id: msg.from?.id ? String(msg.from.id) : author,
169
+ external_id: String(u.update_id),
170
+ author,
171
+ body: audioBody,
172
+ meta: {
173
+ chat_id,
174
+ user_id: msg.from?.id || null,
175
+ message_id: msg.message_id,
176
+ tg_channel: self.channel.name,
177
+ local_path: localPath,
178
+ file_id: incomingAudio.file_id,
179
+ duration: incomingAudio.duration,
180
+ mime_type: incomingAudio.mime_type,
181
+ transcription_backend: transcribeBackend,
182
+ transcription_error: transcribeError,
183
+ },
184
+ });
185
+
186
+ // Inject the transcribed text into `text` so the rest of the agent
187
+ // pipeline treats it identically to a typed message. If there was a
188
+ // caption alongside the audio, prepend the audio marker to it.
189
+ text = text ? `${audioBody}\n${text}` : audioBody;
190
+ }
191
+
192
+ // If there's a pending ask_questions flow for this chat AND the current
193
+ // question is free-text, treat this message as the answer rather than a
194
+ // brand-new turn. Returns true when the message was consumed.
195
+ if (chat_id && text && await self._maybeConsumeAskTextAnswer({ chat_id, text })) {
196
+ // Still log the inbound so the chat history records what the user said.
197
+ appendGlobalMessage({
198
+ channel: CHANNELS.TELEGRAM,
199
+ direction: "in",
200
+ type: "user",
201
+ actor_id: msg.from?.id ? String(msg.from.id) : author,
202
+ external_id: String(u.update_id),
203
+ author,
204
+ body: text,
205
+ meta: {
206
+ chat_id,
207
+ user_id: msg.from?.id || null,
208
+ message_id: msg.message_id,
209
+ tg_channel: self.channel.name,
210
+ ask_answer: true,
211
+ },
212
+ });
213
+ return;
214
+ }
215
+
216
+ // /reset or /new wipes the rolling context for this chat. We just
217
+ // remember a marker timestamp; subsequent inbounds will only consider
218
+ // history newer than self. Implemented by writing a synthetic message
219
+ // with a known marker so getRecentTelegramTurns naturally cuts off.
220
+ const isReset = /^\/(reset|new)\b/i.test(text.trim());
221
+
222
+ // Pull the prior conversation BEFORE we log this inbound — so the
223
+ // current message isn't part of its own history. We then prune anything
224
+ // older than the most recent /reset for this chat_id.
225
+ let previousMessages = [];
226
+ if (chat_id && !isReset) {
227
+ previousMessages = getRecentTelegramTurnsFromFs({
228
+ chat_id,
229
+ keepRecent: 40,
230
+ max_age_hours: 24,
231
+ });
232
+ // Progressive compaction (Pieza 3) runs OUT of the reply path: if this
233
+ // chat is over threshold, summarize the oldest turns in the background so
234
+ // the next turn reads a [RESUMEN COMPACTADO] instead of raw history. Never
235
+ // awaited — adds zero latency to this reply, degrades gracefully.
236
+ compactChannelIfNeeded({
237
+ channel: CHANNELS.TELEGRAM,
238
+ chat_id,
239
+ config: self.globalConfig,
240
+ log: self.log,
241
+ }).catch(() => {});
242
+ // Honour a /reset marker: drop everything up to and including it.
243
+ const lastResetIdx = (() => {
244
+ for (let i = previousMessages.length - 1; i >= 0; i--) {
245
+ if (
246
+ previousMessages[i].role === "user" &&
247
+ /^\/(reset|new)\b/i.test(previousMessages[i].content.trim())
248
+ ) {
249
+ return i;
250
+ }
251
+ }
252
+ return -1;
253
+ })();
254
+ if (lastResetIdx >= 0) {
255
+ previousMessages = previousMessages.slice(lastResetIdx + 1);
256
+ }
257
+ }
258
+
259
+ // Always log inbound to global store (~/.apx/messages/telegram/)
260
+ appendGlobalMessage({
261
+ channel: CHANNELS.TELEGRAM,
262
+ direction: "in",
263
+ type: "user",
264
+ actor_id: msg.from?.id ? String(msg.from.id) : author,
265
+ external_id: String(u.update_id),
266
+ author,
267
+ body: text,
268
+ meta: {
269
+ chat_id,
270
+ user_id: msg.from?.id || null,
271
+ message_id: msg.message_id,
272
+ tg_channel: self.channel.name,
273
+ },
274
+ });
275
+
276
+ // Super-agent is ALWAYS active on Telegram: respond_with_engine === false
277
+ // used to silently drop user messages, which looked to the user like the
278
+ // bot ignored them. Honour the legacy flag only as a soft hint (skip the
279
+ // routed-agent shortcut so we fall straight to super-agent) but never let
280
+ // it short-circuit the whole reply. To genuinely silence the bot, disable
281
+ // the channel entirely (telegram.enabled = false in config).
282
+ const skipRoutedAgent = self.channel.respond_with_engine === false;
283
+ if (!text) return;
284
+
285
+ // Short-circuit /reset / /new: send an ack and don't engage the engine.
286
+ // The marker we just logged is enough — getRecentTelegramTurns will
287
+ // honor it for future messages.
288
+ if (isReset) {
289
+ try {
290
+ const ack = t("telegram.reset_ack", { lang: resolveLang(self.globalConfig) });
291
+ await self._send({ chat_id, text: ack });
292
+ appendGlobalMessage({
293
+ channel: CHANNELS.TELEGRAM,
294
+ direction: "out",
295
+ type: "agent",
296
+ actor_id: SUPERAGENT_ACTOR_ID,
297
+ actor_kind: "superagent",
298
+ agent_slug: SUPERAGENT_ACTOR_ID,
299
+ author: resolveAgentName(self.globalConfig),
300
+ body: ack,
301
+ meta: { chat_id, tg_channel: self.channel.name, in_reply_to: u.update_id, reset: true },
302
+ });
303
+ } catch (e) {
304
+ self.log(`telegram[${self.channel.name}] reset ack failed: ${e.message}`);
305
+ }
306
+ return;
307
+ }
308
+
309
+ // Start "typing..." indicator. Stops when we send the reply (or fail).
310
+ const stopTyping = self._startTyping(chat_id);
311
+
312
+ let replyText;
313
+ let replyAuthor;
314
+ let replyActorId; // stable id: super_agent | agent slug
315
+ let replyKind; // actor_kind: superagent | agent
316
+ const projectCfg = target.config || self.globalConfig;
317
+ // Display name for the super-agent persona on this channel (from identity.json).
318
+ const agentDisplay = resolveAgentName(self.globalConfig);
319
+
320
+ // Try the project's chosen agent first (skipped if the legacy
321
+ // respond_with_engine === false hint asked to bypass routed agents).
322
+ const routeSlug = skipRoutedAgent ? null : self.channel.route_to_agent;
323
+ if (routeSlug) {
324
+ const agent = readAgents(target.path).find((a) => a.slug === routeSlug);
325
+ if (agent && agent.fields.Model) {
326
+ try {
327
+ const system = buildAgentSystem(target, agent, {
328
+ invocation: "telegram",
329
+ channel: self.channel.name,
330
+ caller: author,
331
+ extraParts: [relationshipBlock],
332
+ });
333
+ const result = await callEngine({
334
+ modelId: agent.fields.Model,
335
+ system,
336
+ messages: [{ role: "user", content: text }],
337
+ config: projectCfg,
338
+ });
339
+ replyText = result.text;
340
+ replyAuthor = agent.slug;
341
+ replyActorId = agent.slug;
342
+ replyKind = "agent";
343
+ } catch (e) {
344
+ self.log(`telegram[${self.channel.name}] agent reply failed: ${e.message}`);
345
+ replyText = `[apx error] ${e.message.slice(0, 200)}`;
346
+ replyAuthor = agentDisplay;
347
+ replyActorId = SUPERAGENT_ACTOR_ID;
348
+ replyKind = "superagent";
349
+ }
350
+ } else {
351
+ self.log(
352
+ `telegram[${self.channel.name}] route_to_agent="${routeSlug}" not usable (missing or no model) → trying super-agent`
353
+ );
354
+ }
355
+ }
356
+
357
+ // Fallback: super-agent — STREAMED.
358
+ // Each iteration's assistant text is sent to Telegram as its own message
359
+ // the moment the model produces it (its running commentary), so the user
360
+ // sees a real back-and-forth instead of one giant final dump. Tool calls
361
+ // are logged to the message store — visible via apx log / apx search and
362
+ // to channels that render tools — but NEVER sent to Telegram; tools are
363
+ // internal. The conversation saved on disk is the full, real exchange;
364
+ // Telegram is just the prose-only view of it.
365
+ let saUsage = null;
366
+ let streamedCount = 0;
367
+ let lastStreamedText = "";
368
+ // Telegram shows the user ONLY prose — never the tool calls. On an action
369
+ // request the model often jumps straight to a tool with no preamble text,
370
+ // so the user would stare at a silent chat until the final reply. Send one
371
+ // short localized heads-up the moment real work starts (first tool_start),
372
+ // but only if the agent didn't already write its own "on it" line.
373
+ let sentHeadsUp = false;
374
+ const headsUpPhrase = () => t("telegram.heads_up", { lang: resolveLang(self.globalConfig) });
375
+ if (!replyText && isSuperAgentEnabled(self.globalConfig)) {
376
+ const onEvent = async (ev) => {
377
+ try {
378
+ if (ev.type === "tool_start" && !sentHeadsUp && streamedCount === 0) {
379
+ sentHeadsUp = true;
380
+ const heads = headsUpPhrase();
381
+ await self._send({ chat_id, text: heads });
382
+ appendGlobalMessage({
383
+ channel: CHANNELS.TELEGRAM,
384
+ direction: "out",
385
+ type: "agent",
386
+ actor_id: SUPERAGENT_ACTOR_ID,
387
+ actor_kind: "superagent",
388
+ agent_slug: SUPERAGENT_ACTOR_ID,
389
+ author: agentDisplay,
390
+ body: heads,
391
+ meta: { chat_id, tg_channel: self.channel.name, in_reply_to: u.update_id, heads_up: true },
392
+ });
393
+ return;
394
+ }
395
+ if (ev.type === "assistant_text" && ev.text) {
396
+ const piece = stripThinking(ev.text).trim();
397
+ if (!piece) return;
398
+ await self._send({ chat_id, text: piece });
399
+ lastStreamedText = piece;
400
+ streamedCount += 1;
401
+ appendGlobalMessage({
402
+ channel: CHANNELS.TELEGRAM,
403
+ direction: "out",
404
+ type: "agent",
405
+ actor_id: SUPERAGENT_ACTOR_ID,
406
+ actor_kind: "superagent",
407
+ agent_slug: SUPERAGENT_ACTOR_ID,
408
+ author: agentDisplay,
409
+ body: piece,
410
+ meta: {
411
+ chat_id,
412
+ tg_channel: self.channel.name,
413
+ in_reply_to: u.update_id,
414
+ streamed: true,
415
+ iteration: ev.iteration,
416
+ },
417
+ });
418
+ } else if (ev.type === "tool_result" && ev.trace) {
419
+ // Logged for the audit trail / other channels — NOT sent to Telegram.
420
+ const t = ev.trace;
421
+ appendGlobalMessage({
422
+ channel: CHANNELS.TELEGRAM,
423
+ direction: "out",
424
+ type: "tool",
425
+ actor_id: t.tool,
426
+ actor_kind: "tool",
427
+ author: agentDisplay,
428
+ body: `${t.tool}(${JSON.stringify(t.args || {}).slice(0, 200)})`,
429
+ meta: {
430
+ chat_id,
431
+ tg_channel: self.channel.name,
432
+ in_reply_to: u.update_id,
433
+ tool: t.tool,
434
+ args: t.args,
435
+ result: t.result,
436
+ iteration: ev.iteration,
437
+ },
438
+ });
439
+ }
440
+ } catch (e) {
441
+ // A failed intermediate send must not abort the whole run.
442
+ self.log(`telegram[${self.channel.name}] stream event failed: ${e.message}`);
443
+ }
444
+ };
445
+
446
+ const confirmAdapter = createTelegramConfirmAdapter({
447
+ token: resolveBotToken(self.channel),
448
+ chatId: chat_id,
449
+ pendingStore: getConfirmStore(),
450
+ });
451
+
452
+ // `/slug ...` shortcut: load the matching skill body into contextNote
453
+ // and strip the prefix from the user prompt before sending to the loop.
454
+ const slashed = tryResolveSkillCommand(text, { projectPath: target?.path });
455
+ const slashedPrompt = slashed.handled ? slashed.prompt : text;
456
+ const slashedContextNote = slashed.handled ? slashed.contextNote : "";
457
+
458
+ try {
459
+ const sa = await runSuperAgent({
460
+ globalConfig: self.globalConfig,
461
+ projects: self.projects,
462
+ plugins: self.plugins,
463
+ registries: self.registries,
464
+ prompt: slashedPrompt,
465
+ previousMessages,
466
+ channel: CHANNELS.TELEGRAM,
467
+ relationshipBlock,
468
+ allowedTools,
469
+ contextNote: slashedContextNote || undefined,
470
+ channelMeta: buildTelegramMeta({
471
+ channelName: self.channel.name,
472
+ author,
473
+ chatId: chat_id,
474
+ target,
475
+ routeToAgent: self.channel.route_to_agent,
476
+ }),
477
+ signal: abortCtrl.signal,
478
+ onEvent,
479
+ requestConfirmation: confirmAdapter.requestConfirmation,
480
+ });
481
+ replyText = sa.text;
482
+ replyAuthor = sa.name || agentDisplay;
483
+ replyActorId = SUPERAGENT_ACTOR_ID;
484
+ replyKind = "superagent";
485
+ saUsage = sa.usage;
486
+
487
+ // ── ask_questions integration ────────────────────────────────────
488
+ // If the super-agent ended this turn by calling ask_questions, hand
489
+ // off to the inline-keyboard flow instead of sending the bare
490
+ // assistant text. The flow keeps state per chat_id and re-runs the
491
+ // super-agent once every answer is collected.
492
+ const askQuestions = askFlow.extractAskQuestionsFromTrace(sa.trace);
493
+ if (askQuestions && chat_id) {
494
+ if (chat_id) self.activeRequests.delete(chat_id);
495
+ stopTyping();
496
+ try {
497
+ await self._startAskFlow({
498
+ chat_id,
499
+ projectId: target?.id,
500
+ authorId: msg.from?.id,
501
+ questions: askQuestions,
502
+ author,
503
+ agentDisplay,
504
+ relationshipBlock,
505
+ allowedTools,
506
+ target,
507
+ sender,
508
+ update_id: u.update_id,
509
+ });
510
+ } catch (e) {
511
+ self.log(`telegram[${self.channel.name}] ask flow start failed: ${e.message}`);
512
+ }
513
+ return; // The reply for this turn IS the ask flow.
514
+ }
515
+ } catch (e) {
516
+ if (abortCtrl.signal.aborted) {
517
+ // A newer message superseded this one. Whatever streamed so far is
518
+ // already sent + logged; the newer message's run continues the
519
+ // thread from that history.
520
+ self.log(`telegram[${self.channel.name}] request aborted for chat ${chat_id}`);
521
+ if (chat_id) self.activeRequests.delete(chat_id);
522
+ stopTyping();
523
+ return;
524
+ }
525
+ self.log(`telegram[${self.channel.name}] super-agent failed: ${e.message}`);
526
+ // Surface the failure to the user instead of silently dropping the
527
+ // turn — otherwise from the chat side it looks like the bot ignored
528
+ // the message. Keep the message short and non-leaking.
529
+ replyText = `⚠️ Could not generate a reply right now (${e.message || "internal error"}).`;
530
+ replyAuthor = agentDisplay;
531
+ replyActorId = SUPERAGENT_ACTOR_ID;
532
+ replyKind = "superagent";
533
+ }
534
+ }
535
+
536
+ if (chat_id) self.activeRequests.delete(chat_id);
537
+
538
+ // Final answer. The intermediate prose was already streamed; only send the
539
+ // final text if it's non-empty AND not a duplicate of the last streamed
540
+ // piece (the loop can end on an iteration whose text was already sent).
541
+ // If nothing streamed and there's no final text, send a minimal ack so the
542
+ // turn isn't silently empty.
543
+ const finalClean = replyText ? stripThinking(replyText).trim() : "";
544
+ let toSend = "";
545
+ if (finalClean && finalClean !== lastStreamedText) toSend = finalClean;
546
+ else if (!finalClean && streamedCount === 0) {
547
+ toSend = t("telegram.fallback_listo", { lang: resolveLang(self.globalConfig) });
548
+ }
549
+
550
+ stopTyping();
551
+ if (!toSend) return; // everything was already streamed — nothing left to send
552
+
553
+ try {
554
+ await self._send({ chat_id, text: toSend });
555
+ const meta = {
556
+ chat_id,
557
+ tg_channel: self.channel.name,
558
+ in_reply_to: u.update_id,
559
+ final: true,
560
+ };
561
+ if (replyText && stripThinking(replyText) !== replyText) meta.thinking_stripped = true;
562
+ if (saUsage) meta.usage = saUsage;
563
+ appendGlobalMessage({
564
+ channel: CHANNELS.TELEGRAM,
565
+ direction: "out",
566
+ type: "agent",
567
+ actor_id: replyActorId || SUPERAGENT_ACTOR_ID,
568
+ actor_kind: replyKind || "superagent",
569
+ agent_slug: replyActorId || SUPERAGENT_ACTOR_ID,
570
+ author: replyAuthor || agentDisplay,
571
+ body: toSend,
572
+ meta,
573
+ });
574
+ } catch (e) {
575
+ self.log(`telegram[${self.channel.name}] send-back error: ${e.message}`);
576
+ appendGlobalMessage({
577
+ channel: CHANNELS.TELEGRAM,
578
+ direction: "out",
579
+ type: "agent",
580
+ actor_id: replyActorId || SUPERAGENT_ACTOR_ID,
581
+ actor_kind: replyKind || "superagent",
582
+ agent_slug: replyActorId || SUPERAGENT_ACTOR_ID,
583
+ author: replyAuthor || agentDisplay,
584
+ body: `[send_failed] ${toSend}`,
585
+ meta: {
586
+ chat_id,
587
+ tg_channel: self.channel.name,
588
+ in_reply_to: u.update_id,
589
+ send_error: e.message,
590
+ ...(saUsage ? { usage: saUsage } : {}),
591
+ },
592
+ });
593
+ }
594
+ }
595
+