opc-agent 0.6.0 → 0.8.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 (53) hide show
  1. package/dist/channels/email.d.ts +69 -0
  2. package/dist/channels/email.js +118 -0
  3. package/dist/channels/slack.d.ts +62 -0
  4. package/dist/channels/slack.js +107 -0
  5. package/dist/channels/web.d.ts +7 -1
  6. package/dist/channels/web.js +165 -4
  7. package/dist/channels/wechat.d.ts +62 -0
  8. package/dist/channels/wechat.js +104 -0
  9. package/dist/core/auth.d.ts +13 -0
  10. package/dist/core/auth.js +41 -0
  11. package/dist/core/compose.d.ts +35 -0
  12. package/dist/core/compose.js +49 -0
  13. package/dist/core/orchestrator.d.ts +68 -0
  14. package/dist/core/orchestrator.js +145 -0
  15. package/dist/index.d.ts +23 -0
  16. package/dist/index.js +34 -1
  17. package/dist/schema/oad.d.ts +69 -0
  18. package/dist/schema/oad.js +7 -1
  19. package/dist/skills/document.d.ts +27 -0
  20. package/dist/skills/document.js +80 -0
  21. package/dist/skills/http.d.ts +8 -0
  22. package/dist/skills/http.js +34 -0
  23. package/dist/skills/scheduler.d.ts +21 -0
  24. package/dist/skills/scheduler.js +70 -0
  25. package/dist/skills/webhook-trigger.d.ts +17 -0
  26. package/dist/skills/webhook-trigger.js +49 -0
  27. package/dist/tools/calculator.d.ts +7 -0
  28. package/dist/tools/calculator.js +70 -0
  29. package/dist/tools/datetime.d.ts +7 -0
  30. package/dist/tools/datetime.js +159 -0
  31. package/dist/tools/json-transform.d.ts +7 -0
  32. package/dist/tools/json-transform.js +184 -0
  33. package/dist/tools/text-analysis.d.ts +8 -0
  34. package/dist/tools/text-analysis.js +113 -0
  35. package/package.json +1 -1
  36. package/src/channels/email.ts +177 -0
  37. package/src/channels/slack.ts +160 -0
  38. package/src/channels/web.ts +175 -4
  39. package/src/channels/wechat.ts +149 -0
  40. package/src/core/auth.ts +57 -0
  41. package/src/core/compose.ts +77 -0
  42. package/src/core/orchestrator.ts +215 -0
  43. package/src/index.ts +27 -0
  44. package/src/schema/oad.ts +7 -0
  45. package/src/skills/document.ts +100 -0
  46. package/src/skills/http.ts +35 -0
  47. package/src/skills/scheduler.ts +80 -0
  48. package/src/skills/webhook-trigger.ts +59 -0
  49. package/src/tools/calculator.ts +73 -0
  50. package/src/tools/datetime.ts +149 -0
  51. package/src/tools/json-transform.ts +187 -0
  52. package/src/tools/text-analysis.ts +116 -0
  53. package/tests/v070.test.ts +76 -0
@@ -0,0 +1,69 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+ /**
4
+ * Email Channel — v0.8.0
5
+ * IMAP polling for incoming emails, SMTP for sending replies.
6
+ * Parses email threads as conversations.
7
+ */
8
+ export interface EmailChannelConfig {
9
+ imap: {
10
+ host: string;
11
+ port: number;
12
+ user: string;
13
+ password: string;
14
+ tls?: boolean;
15
+ /** Mailbox to monitor (default: INBOX) */
16
+ mailbox?: string;
17
+ /** Poll interval in ms (default: 30000) */
18
+ pollInterval?: number;
19
+ };
20
+ smtp: {
21
+ host: string;
22
+ port: number;
23
+ user: string;
24
+ password: string;
25
+ tls?: boolean;
26
+ from: string;
27
+ };
28
+ /** Filter: only process emails matching these patterns */
29
+ filters?: {
30
+ from?: string[];
31
+ subject?: string[];
32
+ };
33
+ }
34
+ export interface EmailMessage {
35
+ messageId: string;
36
+ from: string;
37
+ to: string[];
38
+ cc?: string[];
39
+ subject: string;
40
+ body: string;
41
+ html?: string;
42
+ date: Date;
43
+ inReplyTo?: string;
44
+ references?: string[];
45
+ threadId?: string;
46
+ }
47
+ export declare class EmailChannel extends BaseChannel {
48
+ type: string;
49
+ private config;
50
+ private pollTimer;
51
+ private running;
52
+ private processedIds;
53
+ constructor(config: EmailChannelConfig);
54
+ start(): Promise<void>;
55
+ stop(): Promise<void>;
56
+ /** Poll IMAP for new emails */
57
+ private poll;
58
+ /** Convert email to Message format */
59
+ private emailToMessage;
60
+ /** Check if email matches configured filters */
61
+ private matchesFilters;
62
+ /** Fetch emails via IMAP — stub for actual implementation */
63
+ private fetchEmails;
64
+ /** Send reply via SMTP — stub for actual implementation */
65
+ sendReply(originalEmail: EmailMessage, reply: Message): Promise<void>;
66
+ /** Send a standalone email */
67
+ send(to: string, subject: string, body: string): Promise<void>;
68
+ }
69
+ //# sourceMappingURL=email.d.ts.map
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EmailChannel = void 0;
4
+ const index_1 = require("./index");
5
+ class EmailChannel extends index_1.BaseChannel {
6
+ type = 'email';
7
+ config;
8
+ pollTimer = null;
9
+ running = false;
10
+ processedIds = new Set();
11
+ constructor(config) {
12
+ super();
13
+ this.config = config;
14
+ }
15
+ async start() {
16
+ this.running = true;
17
+ const interval = this.config.imap.pollInterval ?? 30000;
18
+ // Initial poll
19
+ await this.poll();
20
+ // Set up recurring poll
21
+ this.pollTimer = setInterval(() => {
22
+ if (this.running)
23
+ this.poll().catch(console.error);
24
+ }, interval);
25
+ }
26
+ async stop() {
27
+ this.running = false;
28
+ if (this.pollTimer) {
29
+ clearInterval(this.pollTimer);
30
+ this.pollTimer = null;
31
+ }
32
+ }
33
+ /** Poll IMAP for new emails */
34
+ async poll() {
35
+ // In production, use a library like `imapflow` or `imap-simple`
36
+ // This is the integration point — actual IMAP connection logic goes here
37
+ const emails = await this.fetchEmails();
38
+ for (const email of emails) {
39
+ if (this.processedIds.has(email.messageId))
40
+ continue;
41
+ this.processedIds.add(email.messageId);
42
+ if (!this.matchesFilters(email))
43
+ continue;
44
+ const message = this.emailToMessage(email);
45
+ if (this.handler) {
46
+ const reply = await this.handler(message);
47
+ await this.sendReply(email, reply);
48
+ }
49
+ }
50
+ }
51
+ /** Convert email to Message format */
52
+ emailToMessage(email) {
53
+ return {
54
+ id: email.messageId,
55
+ role: 'user',
56
+ content: email.body,
57
+ timestamp: email.date.getTime(),
58
+ metadata: {
59
+ channel: 'email',
60
+ from: email.from,
61
+ to: email.to,
62
+ subject: email.subject,
63
+ threadId: email.threadId ?? email.messageId,
64
+ inReplyTo: email.inReplyTo,
65
+ },
66
+ };
67
+ }
68
+ /** Check if email matches configured filters */
69
+ matchesFilters(email) {
70
+ if (!this.config.filters)
71
+ return true;
72
+ if (this.config.filters.from?.length) {
73
+ const fromMatch = this.config.filters.from.some((f) => email.from.toLowerCase().includes(f.toLowerCase()));
74
+ if (!fromMatch)
75
+ return false;
76
+ }
77
+ if (this.config.filters.subject?.length) {
78
+ const subjectMatch = this.config.filters.subject.some((s) => email.subject.toLowerCase().includes(s.toLowerCase()));
79
+ if (!subjectMatch)
80
+ return false;
81
+ }
82
+ return true;
83
+ }
84
+ /** Fetch emails via IMAP — stub for actual implementation */
85
+ async fetchEmails() {
86
+ // TODO: Implement with imapflow or similar library
87
+ // const { ImapFlow } = await import('imapflow');
88
+ // const client = new ImapFlow({ ...this.config.imap });
89
+ // await client.connect();
90
+ // ...
91
+ return [];
92
+ }
93
+ /** Send reply via SMTP — stub for actual implementation */
94
+ async sendReply(originalEmail, reply) {
95
+ // TODO: Implement with nodemailer or similar library
96
+ // const nodemailer = await import('nodemailer');
97
+ // const transport = nodemailer.createTransport({ ...this.config.smtp });
98
+ // await transport.sendMail({
99
+ // from: this.config.smtp.from,
100
+ // to: originalEmail.from,
101
+ // subject: `Re: ${originalEmail.subject}`,
102
+ // text: reply.content,
103
+ // inReplyTo: originalEmail.messageId,
104
+ // references: [originalEmail.messageId],
105
+ // });
106
+ void originalEmail;
107
+ void reply;
108
+ }
109
+ /** Send a standalone email */
110
+ async send(to, subject, body) {
111
+ void to;
112
+ void subject;
113
+ void body;
114
+ // TODO: Implement with nodemailer
115
+ }
116
+ }
117
+ exports.EmailChannel = EmailChannel;
118
+ //# sourceMappingURL=email.js.map
@@ -0,0 +1,62 @@
1
+ import { BaseChannel } from './index';
2
+ /**
3
+ * Slack Channel — v0.8.0
4
+ * Slack Bot with Socket Mode / Events API support, threads, and slash commands.
5
+ */
6
+ export interface SlackChannelConfig {
7
+ /** Bot token (xoxb-...) */
8
+ botToken: string;
9
+ /** App-level token for Socket Mode (xapp-...) */
10
+ appToken?: string;
11
+ /** Signing secret for Events API verification */
12
+ signingSecret?: string;
13
+ /** Use Socket Mode (true) or Events API (false) */
14
+ socketMode?: boolean;
15
+ /** Port for Events API webhook server (default: 3001) */
16
+ port?: number;
17
+ /** Slash commands to register */
18
+ slashCommands?: SlashCommandConfig[];
19
+ }
20
+ export interface SlashCommandConfig {
21
+ command: string;
22
+ description: string;
23
+ handler?: (payload: SlashCommandPayload) => Promise<string>;
24
+ }
25
+ export interface SlashCommandPayload {
26
+ command: string;
27
+ text: string;
28
+ userId: string;
29
+ channelId: string;
30
+ triggerId: string;
31
+ }
32
+ export interface SlackMessageEvent {
33
+ type: string;
34
+ channel: string;
35
+ user: string;
36
+ text: string;
37
+ ts: string;
38
+ threadTs?: string;
39
+ botId?: string;
40
+ }
41
+ export declare class SlackChannel extends BaseChannel {
42
+ type: string;
43
+ private config;
44
+ private running;
45
+ private slashHandlers;
46
+ constructor(config: SlackChannelConfig);
47
+ start(): Promise<void>;
48
+ stop(): Promise<void>;
49
+ /** Start Socket Mode connection */
50
+ private startSocketMode;
51
+ /** Start Events API HTTP server */
52
+ private startEventsAPI;
53
+ /** Handle incoming Slack message */
54
+ handleMessage(event: SlackMessageEvent): Promise<void>;
55
+ /** Handle slash command */
56
+ handleSlashCommand(payload: SlashCommandPayload): Promise<string>;
57
+ /** Convert Slack event to Message */
58
+ private slackToMessage;
59
+ /** Send a message to a Slack channel */
60
+ sendMessage(channel: string, text: string, threadTs?: string): Promise<void>;
61
+ }
62
+ //# sourceMappingURL=slack.d.ts.map
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SlackChannel = void 0;
4
+ const index_1 = require("./index");
5
+ class SlackChannel extends index_1.BaseChannel {
6
+ type = 'slack';
7
+ config;
8
+ running = false;
9
+ slashHandlers = new Map();
10
+ constructor(config) {
11
+ super();
12
+ this.config = config;
13
+ for (const cmd of config.slashCommands ?? []) {
14
+ this.slashHandlers.set(cmd.command, cmd);
15
+ }
16
+ }
17
+ async start() {
18
+ this.running = true;
19
+ if (this.config.socketMode && this.config.appToken) {
20
+ await this.startSocketMode();
21
+ }
22
+ else {
23
+ await this.startEventsAPI();
24
+ }
25
+ }
26
+ async stop() {
27
+ this.running = false;
28
+ // Cleanup connections
29
+ }
30
+ /** Start Socket Mode connection */
31
+ async startSocketMode() {
32
+ // TODO: Implement with @slack/socket-mode
33
+ // const { SocketModeClient } = await import('@slack/socket-mode');
34
+ // const client = new SocketModeClient({ appToken: this.config.appToken! });
35
+ // client.on('message', (event) => this.handleMessage(event));
36
+ // await client.start();
37
+ }
38
+ /** Start Events API HTTP server */
39
+ async startEventsAPI() {
40
+ // TODO: Implement with express or http
41
+ // const port = this.config.port ?? 3001;
42
+ // Listen for POST /slack/events and /slack/commands
43
+ }
44
+ /** Handle incoming Slack message */
45
+ async handleMessage(event) {
46
+ // Ignore bot messages
47
+ if (event.botId)
48
+ return;
49
+ const message = this.slackToMessage(event);
50
+ if (this.handler) {
51
+ const reply = await this.handler(message);
52
+ await this.sendMessage(event.channel, reply.content, event.threadTs ?? event.ts);
53
+ }
54
+ }
55
+ /** Handle slash command */
56
+ async handleSlashCommand(payload) {
57
+ const cmd = this.slashHandlers.get(payload.command);
58
+ if (cmd?.handler) {
59
+ return cmd.handler(payload);
60
+ }
61
+ // Default: pass to message handler
62
+ const message = {
63
+ id: `slack-cmd-${Date.now()}`,
64
+ role: 'user',
65
+ content: `${payload.command} ${payload.text}`.trim(),
66
+ timestamp: Date.now(),
67
+ metadata: {
68
+ channel: 'slack',
69
+ channelId: payload.channelId,
70
+ userId: payload.userId,
71
+ isSlashCommand: true,
72
+ },
73
+ };
74
+ if (this.handler) {
75
+ const reply = await this.handler(message);
76
+ return reply.content;
77
+ }
78
+ return 'Command received.';
79
+ }
80
+ /** Convert Slack event to Message */
81
+ slackToMessage(event) {
82
+ return {
83
+ id: event.ts,
84
+ role: 'user',
85
+ content: event.text,
86
+ timestamp: parseFloat(event.ts) * 1000,
87
+ metadata: {
88
+ channel: 'slack',
89
+ channelId: event.channel,
90
+ userId: event.user,
91
+ threadTs: event.threadTs,
92
+ },
93
+ };
94
+ }
95
+ /** Send a message to a Slack channel */
96
+ async sendMessage(channel, text, threadTs) {
97
+ // TODO: Implement with @slack/web-api
98
+ // const { WebClient } = await import('@slack/web-api');
99
+ // const client = new WebClient(this.config.botToken);
100
+ // await client.chat.postMessage({ channel, text, thread_ts: threadTs });
101
+ void channel;
102
+ void text;
103
+ void threadTs;
104
+ }
105
+ }
106
+ exports.SlackChannel = SlackChannel;
107
+ //# sourceMappingURL=slack.js.map
@@ -1,6 +1,7 @@
1
1
  import { type Response } from 'express';
2
2
  import type { Message } from '../core/types';
3
3
  import { BaseChannel } from './index';
4
+ import { type AuthConfig } from '../core/auth';
4
5
  export declare class WebChannel extends BaseChannel {
5
6
  readonly type = "web";
6
7
  private app;
@@ -11,11 +12,16 @@ export declare class WebChannel extends BaseChannel {
11
12
  private currentProvider;
12
13
  private stats;
13
14
  private eventHandlers;
15
+ private conversations;
16
+ private requestCount;
17
+ private llmLatencySum;
18
+ private llmCalls;
14
19
  private emit;
15
20
  onConfigChange(handler: (config: any) => void): void;
16
21
  trackMessage(responseMs: number, tokens?: number): void;
22
+ trackError(): void;
17
23
  trackSession(): void;
18
- constructor(port?: number);
24
+ constructor(port?: number, authConfig?: AuthConfig);
19
25
  setAgentName(name: string): void;
20
26
  onStreamMessage(handler: (msg: Message, res: Response) => Promise<void>): void;
21
27
  private setupRoutes;
@@ -7,6 +7,57 @@ exports.WebChannel = void 0;
7
7
  const express_1 = __importDefault(require("express"));
8
8
  const index_1 = require("./index");
9
9
  const knowledge_1 = require("../core/knowledge");
10
+ const auth_1 = require("../core/auth");
11
+ const AGENT_TEMPLATES = [
12
+ { id: 'customer-service', name: 'Customer Service', description: 'Handle support tickets, FAQs, and customer inquiries', icon: '🎧', category: 'Business' },
13
+ { id: 'code-reviewer', name: 'Code Reviewer', description: 'Review PRs, suggest improvements, check for bugs', icon: '🔍', category: 'Engineering' },
14
+ { id: 'content-writer', name: 'Content Writer', description: 'Write blogs, social media posts, and marketing copy', icon: '✍️', category: 'Marketing' },
15
+ { id: 'executive-assistant', name: 'Executive Assistant', description: 'Schedule management, email drafting, meeting prep', icon: '📋', category: 'Business' },
16
+ { id: 'knowledge-base', name: 'Knowledge Base', description: 'RAG-powered Q&A over your documents', icon: '📚', category: 'Knowledge' },
17
+ { id: 'project-manager', name: 'Project Manager', description: 'Track tasks, milestones, and team coordination', icon: '📊', category: 'Business' },
18
+ { id: 'sales-assistant', name: 'Sales Assistant', description: 'Lead qualification, outreach drafting, CRM updates', icon: '💼', category: 'Sales' },
19
+ { id: 'financial-advisor', name: 'Financial Advisor', description: 'Budget analysis, financial planning, cost optimization', icon: '💰', category: 'Finance' },
20
+ { id: 'hr-recruiter', name: 'HR Recruiter', description: 'Resume screening, interview scheduling, candidate comms', icon: '👥', category: 'HR' },
21
+ { id: 'legal-assistant', name: 'Legal Assistant', description: 'Contract review, compliance checks, legal research', icon: '⚖️', category: 'Legal' },
22
+ ];
23
+ const TEMPLATES_HTML = `<!DOCTYPE html>
24
+ <html lang="en">
25
+ <head>
26
+ <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
27
+ <title>Agent Templates</title>
28
+ <style>
29
+ *{margin:0;padding:0;box-sizing:border-box}
30
+ body{background:#0a0a0f;color:#e0e0e0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:24px}
31
+ h1{font-size:28px;margin-bottom:8px;color:#fff}
32
+ .sub{color:#888;margin-bottom:32px;font-size:14px}
33
+ nav{margin-bottom:24px}
34
+ nav a{color:#818cf8;text-decoration:none;margin-right:16px;font-size:14px}
35
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px}
36
+ .card{background:#12121a;border:1px solid #1e1e2e;border-radius:12px;padding:24px;cursor:pointer;transition:all .2s}
37
+ .card:hover{border-color:#818cf8;transform:translateY(-2px)}
38
+ .card .icon{font-size:32px;margin-bottom:12px}
39
+ .card h3{font-size:16px;color:#fff;margin-bottom:8px}
40
+ .card p{font-size:13px;color:#888;line-height:1.5}
41
+ .card .cat{font-size:11px;color:#818cf8;text-transform:uppercase;letter-spacing:1px;margin-top:12px}
42
+ .btn{display:inline-block;background:#2563eb;color:#fff;border:none;border-radius:8px;padding:8px 16px;font-size:13px;cursor:pointer;margin-top:12px}
43
+ .btn:hover{background:#1d4ed8}
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <nav><a href="/">← Chat</a><a href="/dashboard">Dashboard</a><a href="/templates">Templates</a></nav>
48
+ <h1>🧩 Agent Templates</h1>
49
+ <p class="sub">Create a new agent from a pre-built template in one click.</p>
50
+ <div class="grid" id="grid"></div>
51
+ <script>
52
+ fetch('/api/templates').then(r=>r.json()).then(d=>{
53
+ const g=document.getElementById('grid');
54
+ d.templates.forEach(t=>{
55
+ g.innerHTML+=\`<div class="card"><div class="icon">\${t.icon}</div><h3>\${t.name}</h3><p>\${t.description}</p><div class="cat">\${t.category}</div><button class="btn" onclick="alert('Creating agent from template: '+'\${t.id}'+'\\\\nRun: opc init --template \${t.id}')">Use Template</button></div>\`;
56
+ });
57
+ });
58
+ </script>
59
+ </body>
60
+ </html>`;
10
61
  const CHAT_HTML = `<!DOCTYPE html>
11
62
  <html lang="en">
12
63
  <head>
@@ -157,8 +208,12 @@ class WebChannel extends index_1.BaseChannel {
157
208
  streamHandler = null;
158
209
  agentName = 'OPC Agent';
159
210
  currentProvider = 'openai';
160
- stats = { sessions: 0, messages: 0, totalResponseMs: 0, tokenUsage: 0, knowledgeFiles: 0, startedAt: Date.now() };
211
+ stats = { sessions: 0, messages: 0, totalResponseMs: 0, tokenUsage: 0, knowledgeFiles: 0, startedAt: Date.now(), errors: 0 };
161
212
  eventHandlers = new Map();
213
+ conversations = new Map();
214
+ requestCount = 0;
215
+ llmLatencySum = 0;
216
+ llmCalls = 0;
162
217
  emit(event, data) {
163
218
  const handlers = this.eventHandlers.get(event) ?? [];
164
219
  for (const h of handlers)
@@ -173,13 +228,20 @@ class WebChannel extends index_1.BaseChannel {
173
228
  this.stats.messages++;
174
229
  this.stats.totalResponseMs += responseMs;
175
230
  this.stats.tokenUsage += tokens;
231
+ this.requestCount++;
232
+ this.llmLatencySum += responseMs;
233
+ this.llmCalls++;
176
234
  }
235
+ trackError() { this.stats.errors++; }
177
236
  trackSession() { this.stats.sessions++; }
178
- constructor(port = 3000) {
237
+ constructor(port = 3000, authConfig) {
179
238
  super();
180
239
  this.port = port;
181
240
  this.app = (0, express_1.default)();
182
- this.app.use(express_1.default.json());
241
+ this.app.use(express_1.default.json({ limit: '10mb' }));
242
+ if (authConfig && authConfig.apiKeys.length > 0) {
243
+ this.app.use((0, auth_1.createAuthMiddleware)(authConfig));
244
+ }
183
245
  this.setupRoutes();
184
246
  }
185
247
  setAgentName(name) {
@@ -201,6 +263,7 @@ class WebChannel extends index_1.BaseChannel {
201
263
  // Streaming chat endpoint
202
264
  this.app.post('/api/chat', async (req, res) => {
203
265
  const { message, sessionId } = req.body;
266
+ const sid = sessionId ?? 'default';
204
267
  if (!message) {
205
268
  res.status(400).json({ error: 'message is required' });
206
269
  return;
@@ -210,8 +273,12 @@ class WebChannel extends index_1.BaseChannel {
210
273
  role: 'user',
211
274
  content: message,
212
275
  timestamp: Date.now(),
213
- metadata: { sessionId: sessionId ?? 'default' },
276
+ metadata: { sessionId: sid },
214
277
  };
278
+ // Track conversation
279
+ if (!this.conversations.has(sid))
280
+ this.conversations.set(sid, []);
281
+ this.conversations.get(sid).push(msg);
215
282
  if (this.streamHandler) {
216
283
  try {
217
284
  await this.streamHandler(msg, res);
@@ -290,6 +357,100 @@ class WebChannel extends index_1.BaseChannel {
290
357
  res.json({ totalEntries: 0, sources: [] });
291
358
  }
292
359
  });
360
+ // --- Health Check (detailed) ---
361
+ this.app.get('/api/health', (_req, res) => {
362
+ const uptimeMs = Date.now() - this.stats.startedAt;
363
+ res.json({
364
+ status: 'ok',
365
+ timestamp: Date.now(),
366
+ uptime: uptimeMs,
367
+ uptimeHuman: `${Math.floor(uptimeMs / 3600000)}h ${Math.floor((uptimeMs % 3600000) / 60000)}m`,
368
+ version: '0.7.0',
369
+ agent: this.agentName,
370
+ stats: {
371
+ sessions: this.stats.sessions,
372
+ messages: this.stats.messages,
373
+ errors: this.stats.errors,
374
+ avgResponseMs: this.stats.messages > 0 ? Math.round(this.stats.totalResponseMs / this.stats.messages) : 0,
375
+ },
376
+ memory: {
377
+ rss: process.memoryUsage().rss,
378
+ heapUsed: process.memoryUsage().heapUsed,
379
+ },
380
+ });
381
+ });
382
+ // --- Prometheus Metrics ---
383
+ this.app.get('/api/metrics', (_req, res) => {
384
+ const uptimeMs = Date.now() - this.stats.startedAt;
385
+ const avgLatency = this.llmCalls > 0 ? this.llmLatencySum / this.llmCalls : 0;
386
+ const mem = process.memoryUsage();
387
+ res.type('text/plain').send(`# HELP opc_uptime_seconds Agent uptime in seconds\n` +
388
+ `# TYPE opc_uptime_seconds gauge\n` +
389
+ `opc_uptime_seconds ${(uptimeMs / 1000).toFixed(1)}\n` +
390
+ `# HELP opc_requests_total Total requests\n` +
391
+ `# TYPE opc_requests_total counter\n` +
392
+ `opc_requests_total ${this.requestCount}\n` +
393
+ `# HELP opc_messages_total Total messages processed\n` +
394
+ `# TYPE opc_messages_total counter\n` +
395
+ `opc_messages_total ${this.stats.messages}\n` +
396
+ `# HELP opc_errors_total Total errors\n` +
397
+ `# TYPE opc_errors_total counter\n` +
398
+ `opc_errors_total ${this.stats.errors}\n` +
399
+ `# HELP opc_llm_latency_avg_ms Average LLM response latency\n` +
400
+ `# TYPE opc_llm_latency_avg_ms gauge\n` +
401
+ `opc_llm_latency_avg_ms ${avgLatency.toFixed(1)}\n` +
402
+ `# HELP opc_sessions_total Total sessions\n` +
403
+ `# TYPE opc_sessions_total counter\n` +
404
+ `opc_sessions_total ${this.stats.sessions}\n` +
405
+ `# HELP opc_token_usage_total Total token usage\n` +
406
+ `# TYPE opc_token_usage_total counter\n` +
407
+ `opc_token_usage_total ${this.stats.tokenUsage}\n` +
408
+ `# HELP process_resident_memory_bytes Resident memory size\n` +
409
+ `# TYPE process_resident_memory_bytes gauge\n` +
410
+ `process_resident_memory_bytes ${mem.rss}\n`);
411
+ });
412
+ // --- Conversation tracking & export ---
413
+ this.app.get('/api/conversations/export', (req, res) => {
414
+ const sessionId = req.query.sessionId;
415
+ const format = req.query.format ?? 'json';
416
+ const messages = sessionId ? (this.conversations.get(sessionId) ?? []) : Array.from(this.conversations.values()).flat();
417
+ if (format === 'markdown') {
418
+ const md = messages.map(m => `**${m.role}** (${new Date(m.timestamp).toISOString()}):\n${m.content}`).join('\n\n---\n\n');
419
+ res.type('text/markdown').send(md);
420
+ }
421
+ else if (format === 'csv') {
422
+ const header = 'id,role,content,timestamp\n';
423
+ const rows = messages.map(m => `"${m.id}","${m.role}","${m.content.replace(/"/g, '""')}",${m.timestamp}`).join('\n');
424
+ res.type('text/csv').send(header + rows);
425
+ }
426
+ else {
427
+ res.json({ sessionId: sessionId ?? 'all', messages, count: messages.length });
428
+ }
429
+ });
430
+ // --- Document Upload ---
431
+ this.app.post('/api/documents/upload', async (req, res) => {
432
+ try {
433
+ const { content, filename, mimeType } = req.body;
434
+ if (!content || !filename) {
435
+ res.status(400).json({ error: 'content and filename are required' });
436
+ return;
437
+ }
438
+ const kb = new knowledge_1.KnowledgeBase('.');
439
+ const result = await kb.addText(content, filename);
440
+ this.stats.knowledgeFiles++;
441
+ res.json({ ok: true, filename, chunks: result.chunks, chars: content.length });
442
+ }
443
+ catch (err) {
444
+ res.status(500).json({ error: err instanceof Error ? err.message : 'Upload failed' });
445
+ }
446
+ });
447
+ // --- Agent Templates Gallery ---
448
+ this.app.get('/api/templates', (_req, res) => {
449
+ res.json({ templates: AGENT_TEMPLATES });
450
+ });
451
+ this.app.get('/templates', (_req, res) => {
452
+ res.type('html').send(TEMPLATES_HTML);
453
+ });
293
454
  // Legacy endpoint
294
455
  this.app.post('/chat', async (req, res) => {
295
456
  if (!this.handler) {
@@ -0,0 +1,62 @@
1
+ import { BaseChannel } from './index';
2
+ /**
3
+ * WeChat Channel (Stub) — v0.8.0
4
+ * WeChat Official Account message handling, template messages, QR code login.
5
+ */
6
+ export interface WeChatChannelConfig {
7
+ /** WeChat Official Account AppID */
8
+ appId: string;
9
+ /** WeChat Official Account AppSecret */
10
+ appSecret: string;
11
+ /** Verification token for message validation */
12
+ token: string;
13
+ /** AES encoding key for encrypted messages */
14
+ encodingAESKey?: string;
15
+ /** HTTP server port (default: 3002) */
16
+ port?: number;
17
+ }
18
+ export interface WeChatMessage {
19
+ toUserName: string;
20
+ fromUserName: string;
21
+ createTime: number;
22
+ msgType: 'text' | 'image' | 'voice' | 'video' | 'event';
23
+ content?: string;
24
+ msgId?: string;
25
+ event?: string;
26
+ eventKey?: string;
27
+ }
28
+ export interface TemplateMessageData {
29
+ toUser: string;
30
+ templateId: string;
31
+ url?: string;
32
+ data: Record<string, {
33
+ value: string;
34
+ color?: string;
35
+ }>;
36
+ }
37
+ export declare class WeChatChannel extends BaseChannel {
38
+ type: string;
39
+ private config;
40
+ private accessToken;
41
+ private tokenExpiry;
42
+ constructor(config: WeChatChannelConfig);
43
+ start(): Promise<void>;
44
+ stop(): Promise<void>;
45
+ /** Get or refresh access token */
46
+ getAccessToken(): Promise<string>;
47
+ /** Handle incoming WeChat message */
48
+ handleMessage(wxMsg: WeChatMessage): Promise<string>;
49
+ /** Handle WeChat events (subscribe, scan, etc.) */
50
+ private handleEvent;
51
+ /** Convert WeChat message to internal Message */
52
+ private wechatToMessage;
53
+ /** Send template message */
54
+ sendTemplateMessage(data: TemplateMessageData): Promise<boolean>;
55
+ /** Generate QR code for login (stub) */
56
+ generateLoginQR(): Promise<{
57
+ ticket: string;
58
+ url: string;
59
+ expireSeconds: number;
60
+ }>;
61
+ }
62
+ //# sourceMappingURL=wechat.d.ts.map