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