apteva 0.4.17 → 0.4.19

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 (78) hide show
  1. package/dist/ActivityPage.9a1qg4bp.js +3 -0
  2. package/dist/ApiDocsPage.rfpf7ws1.js +4 -0
  3. package/dist/App.1nmg2h01.js +4 -0
  4. package/dist/App.5qw2dtxs.js +4 -0
  5. package/dist/App.6nc5acvk.js +4 -0
  6. package/dist/App.7vzbaz56.js +4 -0
  7. package/dist/App.8rfz30p1.js +4 -0
  8. package/dist/App.amwp54wf.js +4 -0
  9. package/dist/App.e4202qb4.js +267 -0
  10. package/dist/App.errxz2q4.js +4 -0
  11. package/dist/App.f8qsyhpr.js +4 -0
  12. package/dist/App.g8vq68n0.js +20 -0
  13. package/dist/App.kfyrnznw.js +13 -0
  14. package/dist/{App.mq6jqare.js → App.p02f4ret.js} +1 -1
  15. package/dist/App.p93mmyqw.js +4 -0
  16. package/dist/App.qmg33p02.js +4 -0
  17. package/dist/App.sdsc0258.js +4 -0
  18. package/dist/ConnectionsPage.7zqba1r0.js +3 -0
  19. package/dist/McpPage.kf2g327t.js +3 -0
  20. package/dist/SettingsPage.472c15ep.js +3 -0
  21. package/dist/SkillsPage.xdxnh68a.js +3 -0
  22. package/dist/TasksPage.7g0b8xwc.js +3 -0
  23. package/dist/TelemetryPage.pr7rbz4r.js +3 -0
  24. package/dist/TestsPage.zhc6rqjm.js +3 -0
  25. package/dist/apteva-kit.css +1 -1
  26. package/dist/index.html +1 -1
  27. package/dist/styles.css +1 -1
  28. package/package.json +9 -4
  29. package/src/auth/middleware.ts +2 -0
  30. package/src/channels/index.ts +40 -0
  31. package/src/channels/telegram.ts +306 -0
  32. package/src/db.ts +342 -11
  33. package/src/integrations/agentdojo.ts +1 -1
  34. package/src/mcp-handler.ts +31 -24
  35. package/src/mcp-platform.ts +41 -1
  36. package/src/providers.ts +22 -9
  37. package/src/routes/api/agent-utils.ts +38 -2
  38. package/src/routes/api/agents.ts +65 -2
  39. package/src/routes/api/channels.ts +182 -0
  40. package/src/routes/api/integrations.ts +13 -5
  41. package/src/routes/api/mcp.ts +27 -9
  42. package/src/routes/api/projects.ts +19 -2
  43. package/src/routes/api/system.ts +26 -12
  44. package/src/routes/api/telemetry.ts +30 -0
  45. package/src/routes/api/triggers.ts +478 -0
  46. package/src/routes/api/webhooks.ts +171 -0
  47. package/src/routes/api.ts +7 -1
  48. package/src/routes/static.ts +12 -3
  49. package/src/server.ts +43 -6
  50. package/src/triggers/agentdojo.ts +253 -0
  51. package/src/triggers/composio.ts +264 -0
  52. package/src/triggers/index.ts +71 -0
  53. package/src/tui/AgentList.tsx +145 -0
  54. package/src/tui/App.tsx +102 -0
  55. package/src/tui/Login.tsx +104 -0
  56. package/src/tui/api.ts +72 -0
  57. package/src/tui/index.tsx +7 -0
  58. package/src/web/App.tsx +18 -11
  59. package/src/web/components/agents/AgentCard.tsx +14 -7
  60. package/src/web/components/agents/AgentPanel.tsx +94 -137
  61. package/src/web/components/common/Icons.tsx +16 -0
  62. package/src/web/components/common/index.ts +1 -0
  63. package/src/web/components/connections/ConnectionsPage.tsx +54 -0
  64. package/src/web/components/connections/IntegrationsTab.tsx +144 -0
  65. package/src/web/components/connections/OverviewTab.tsx +137 -0
  66. package/src/web/components/connections/TriggersTab.tsx +1169 -0
  67. package/src/web/components/index.ts +1 -0
  68. package/src/web/components/layout/Header.tsx +196 -4
  69. package/src/web/components/layout/Sidebar.tsx +7 -1
  70. package/src/web/components/mcp/IntegrationsPanel.tsx +19 -3
  71. package/src/web/components/settings/SettingsPage.tsx +364 -2
  72. package/src/web/components/tasks/TasksPage.tsx +2 -2
  73. package/src/web/components/tests/TestsPage.tsx +1 -2
  74. package/src/web/context/TelemetryContext.tsx +14 -1
  75. package/src/web/context/index.ts +1 -1
  76. package/src/web/hooks/useAgents.ts +15 -11
  77. package/src/web/types.ts +1 -1
  78. package/dist/App.fq4xbpcz.js +0 -228
@@ -0,0 +1,306 @@
1
+ import { Bot } from "grammy";
2
+ import { AgentDB, ChannelDB } from "../db";
3
+ import { decryptObject } from "../crypto";
4
+ import { agentFetch } from "../routes/api/agent-utils";
5
+
6
+ interface TelegramConfig {
7
+ botToken: string;
8
+ allowList?: string[]; // Telegram user IDs allowed to chat
9
+ }
10
+
11
+ // In-memory map of running bot instances
12
+ const activeBots = new Map<string, Bot>();
13
+
14
+ export function isChannelActive(channelId: string): boolean {
15
+ return activeBots.has(channelId);
16
+ }
17
+
18
+ export async function startTelegramChannel(channelId: string): Promise<{ success: boolean; error?: string }> {
19
+ // Stop existing if running
20
+ if (activeBots.has(channelId)) {
21
+ await stopTelegramChannel(channelId);
22
+ }
23
+
24
+ const channel = ChannelDB.findById(channelId);
25
+ if (!channel) return { success: false, error: "Channel not found" };
26
+
27
+ let config: TelegramConfig;
28
+ try {
29
+ config = decryptObject(channel.config) as unknown as TelegramConfig;
30
+ } catch {
31
+ ChannelDB.setStatus(channelId, "error", "Failed to decrypt config");
32
+ return { success: false, error: "Failed to decrypt config" };
33
+ }
34
+
35
+ if (!config.botToken) {
36
+ ChannelDB.setStatus(channelId, "error", "Missing bot token");
37
+ return { success: false, error: "Missing bot token" };
38
+ }
39
+
40
+ const agent = AgentDB.findById(channel.agent_id);
41
+ if (!agent) {
42
+ ChannelDB.setStatus(channelId, "error", "Agent not found");
43
+ return { success: false, error: "Agent not found" };
44
+ }
45
+
46
+ try {
47
+ const bot = new Bot(config.botToken);
48
+
49
+ // /start command
50
+ bot.command("start", async (ctx) => {
51
+ await ctx.reply(`Connected to agent: ${agent.name}`);
52
+ });
53
+
54
+ // Handle text messages
55
+ bot.on("message:text", async (ctx) => {
56
+ // Access control
57
+ if (config.allowList?.length) {
58
+ const senderId = String(ctx.from.id);
59
+ if (!config.allowList.includes(senderId)) return;
60
+ }
61
+
62
+ // Check agent is running
63
+ const currentAgent = AgentDB.findById(channel.agent_id);
64
+ if (!currentAgent || currentAgent.status !== "running" || !currentAgent.port) {
65
+ await ctx.reply("Agent is not running.");
66
+ return;
67
+ }
68
+
69
+ // Send typing indicator
70
+ await ctx.replyWithChatAction("typing");
71
+
72
+ try {
73
+ // Map telegram chat → agent thread
74
+ const threadId = `telegram-${ctx.chat.id}`;
75
+
76
+ // Proxy to agent via agentFetch (same path as web UI chat)
77
+ const res = await agentFetch(currentAgent.id, currentAgent.port, "/chat", {
78
+ method: "POST",
79
+ headers: { "Content-Type": "application/json" },
80
+ body: JSON.stringify({
81
+ message: ctx.message.text,
82
+ thread_id: threadId,
83
+ }),
84
+ });
85
+
86
+ if (!res.ok) {
87
+ await ctx.reply("Error: agent returned an error.");
88
+ return;
89
+ }
90
+
91
+ // Stream response and send messages progressively as segments complete
92
+ await streamAndSend(res, ctx);
93
+ } catch (err) {
94
+ console.error(`[telegram:${channelId}] Message handling error:`, err);
95
+ await ctx.reply("Error processing your message.");
96
+ }
97
+ });
98
+
99
+ // Error handler
100
+ bot.catch((err) => {
101
+ console.error(`[telegram:${channelId}] Bot error:`, err);
102
+ });
103
+
104
+ // Start long-polling (non-blocking)
105
+ bot.start({
106
+ onStart: () => {
107
+ console.log(`[telegram:${channelId}] Bot started for agent ${agent.name}`);
108
+ },
109
+ });
110
+
111
+ activeBots.set(channelId, bot);
112
+ ChannelDB.setStatus(channelId, "running");
113
+ return { success: true };
114
+ } catch (err: any) {
115
+ const errorMsg = err.message || String(err);
116
+ console.error(`[telegram:${channelId}] Failed to start:`, errorMsg);
117
+ ChannelDB.setStatus(channelId, "error", errorMsg);
118
+ return { success: false, error: errorMsg };
119
+ }
120
+ }
121
+
122
+ export async function stopTelegramChannel(channelId: string): Promise<void> {
123
+ const bot = activeBots.get(channelId);
124
+ if (bot) {
125
+ try {
126
+ await bot.stop();
127
+ } catch {
128
+ // Ignore stop errors
129
+ }
130
+ activeBots.delete(channelId);
131
+ }
132
+ ChannelDB.setStatus(channelId, "stopped");
133
+ console.log(`[telegram:${channelId}] Bot stopped`);
134
+ }
135
+
136
+ /**
137
+ * Stream SSE response from agent and send Telegram messages progressively.
138
+ * Mirrors the chunk types from apteva-kit's chat component:
139
+ * content/token → accumulate text, send when a boundary is hit
140
+ * tool_call → flush pending text, send tool indicator immediately
141
+ * tool_use, tool_input_delta, tool_result, tool_stream → skipped
142
+ *
143
+ * Messages are sent as soon as each segment completes (tool boundary or end of stream),
144
+ * so the user sees them appear progressively in real-time.
145
+ */
146
+ async function streamAndSend(
147
+ res: Response,
148
+ ctx: { reply: (text: string, opts?: any) => Promise<any>; replyWithChatAction: (action: string) => Promise<any> },
149
+ onActivity?: () => void,
150
+ ): Promise<void> {
151
+ if (!res.body) {
152
+ await ctx.reply("(No response from agent)");
153
+ return;
154
+ }
155
+
156
+ const reader = res.body.getReader();
157
+ const decoder = new TextDecoder();
158
+ let textBuffer = "";
159
+ let buffer = "";
160
+ let messagesSent = 0;
161
+
162
+ async function flushText() {
163
+ const trimmed = textBuffer.trim();
164
+ if (trimmed) {
165
+ const chunks = splitMessage(trimmed, 4096);
166
+ for (const chunk of chunks) {
167
+ try {
168
+ await ctx.reply(chunk, { parse_mode: "Markdown" });
169
+ } catch {
170
+ await ctx.reply(chunk);
171
+ }
172
+ messagesSent++;
173
+ }
174
+ }
175
+ textBuffer = "";
176
+ }
177
+
178
+ // Periodically send typing indicator while streaming
179
+ const typingInterval = setInterval(() => {
180
+ ctx.replyWithChatAction("typing").catch(() => {});
181
+ }, 4000);
182
+
183
+ try {
184
+ while (true) {
185
+ const { done, value } = await reader.read();
186
+ if (done) break;
187
+
188
+ buffer += decoder.decode(value, { stream: true });
189
+
190
+ const lines = buffer.split("\n");
191
+ buffer = lines.pop() || "";
192
+
193
+ for (const line of lines) {
194
+ if (!line.startsWith("data: ")) continue;
195
+ const data = line.slice(6).trim();
196
+ if (data === "[DONE]") continue;
197
+
198
+ try {
199
+ const chunk = JSON.parse(data);
200
+
201
+ switch (chunk.type) {
202
+ // Text content — accumulate
203
+ case "content":
204
+ case "token":
205
+ if (chunk.content) textBuffer += chunk.content;
206
+ else if (chunk.text) textBuffer += chunk.text;
207
+ break;
208
+
209
+ // Tool starting — flush text immediately, then send tool indicator
210
+ case "tool_call": {
211
+ await flushText();
212
+ const name = chunk.tool_display_name || chunk.tool_name || "tool";
213
+ try {
214
+ await ctx.reply(`🔧 _${escapeMarkdown(name)}_`, { parse_mode: "Markdown" });
215
+ } catch {
216
+ await ctx.reply(`🔧 ${name}`);
217
+ }
218
+ messagesSent++;
219
+ break;
220
+ }
221
+
222
+ // Intermediate tool events — skip, but signal activity
223
+ case "tool_input_delta":
224
+ case "tool_use":
225
+ case "tool_stream":
226
+ case "tool_result":
227
+ onActivity?.();
228
+ break;
229
+
230
+ // Fallback: older SSE formats
231
+ case "message_delta":
232
+ if (chunk.delta?.text) textBuffer += chunk.delta.text;
233
+ break;
234
+ case "content_block_delta":
235
+ if (chunk.delta?.text) textBuffer += chunk.delta.text;
236
+ break;
237
+
238
+ default:
239
+ if (chunk.content && typeof chunk.content === "string") {
240
+ textBuffer += chunk.content;
241
+ } else if (typeof chunk.text === "string") {
242
+ textBuffer += chunk.text;
243
+ }
244
+ break;
245
+ }
246
+ } catch {
247
+ if (data && data !== "[DONE]") {
248
+ textBuffer += data;
249
+ }
250
+ }
251
+ }
252
+ }
253
+ } catch {
254
+ // Stream read error — flush what we have
255
+ } finally {
256
+ clearInterval(typingInterval);
257
+ }
258
+
259
+ // Flush remaining text
260
+ await flushText();
261
+
262
+ if (messagesSent === 0) {
263
+ await ctx.reply("(No response from agent)");
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Escape special Markdown characters for Telegram Markdown parse mode.
269
+ */
270
+ function escapeMarkdown(text: string): string {
271
+ return text.replace(/([_*\[\]()~`>#+\-=|{}.!\\])/g, "\\$1");
272
+ }
273
+
274
+ /**
275
+ * Split a message into chunks respecting the max length.
276
+ * Tries to split at newlines when possible.
277
+ */
278
+ function splitMessage(text: string, maxLength: number): string[] {
279
+ if (text.length <= maxLength) return [text];
280
+
281
+ const chunks: string[] = [];
282
+ let remaining = text;
283
+
284
+ while (remaining.length > 0) {
285
+ if (remaining.length <= maxLength) {
286
+ chunks.push(remaining);
287
+ break;
288
+ }
289
+
290
+ // Try to find a newline near the limit
291
+ let splitAt = remaining.lastIndexOf("\n", maxLength);
292
+ if (splitAt < maxLength * 0.5) {
293
+ // No good newline found — split at space
294
+ splitAt = remaining.lastIndexOf(" ", maxLength);
295
+ }
296
+ if (splitAt < maxLength * 0.3) {
297
+ // No good split point — hard split
298
+ splitAt = maxLength;
299
+ }
300
+
301
+ chunks.push(remaining.slice(0, splitAt));
302
+ remaining = remaining.slice(splitAt).trimStart();
303
+ }
304
+
305
+ return chunks;
306
+ }