opc-agent 1.0.0 → 1.1.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  All notable changes to OPC Agent will be documented in this file.
4
4
 
5
+ ## [1.1.0] - 2026-04-16
6
+
7
+ ### Added
8
+ - **Feishu/Lark Channel**: Full Feishu bot integration with event subscription webhook, tenant access token caching, text & interactive card messaging, group + P2P support. Also works with Lark international via `apiBase` config. (`src/channels/feishu.ts`)
9
+ - **Discord Channel**: Discord bot via Gateway WebSocket with auto-reconnect, heartbeat, message content intent, and 2000-char message splitting. (`src/channels/discord.ts`)
10
+ - **ProcessWatcher**: Background process output monitoring with regex pattern matching — watch stdout/stderr for specific patterns (errors, "server ready", build completion) and get instant callbacks without polling. Supports `once` patterns, match history, and dynamic pattern add/remove. Inspired by Hermes Agent's `watch_patterns`. (`src/core/watch.ts`)
11
+
5
12
  ## [0.2.0] - 2026-04-15
6
13
 
7
14
  ### Added
@@ -0,0 +1,44 @@
1
+ import { BaseChannel } from './index';
2
+ /**
3
+ * Discord Channel — v1.1.0
4
+ *
5
+ * Supports:
6
+ * - Discord Bot via Gateway (WebSocket) or HTTP interactions
7
+ * - Slash commands, message content intent
8
+ * - Thread-based conversations
9
+ * - Reactions, embeds
10
+ *
11
+ * Env vars:
12
+ * DISCORD_BOT_TOKEN — bot token
13
+ * DISCORD_APPLICATION_ID — application ID for slash commands
14
+ */
15
+ export interface DiscordChannelConfig {
16
+ /** Bot token */
17
+ botToken?: string;
18
+ /** Application ID */
19
+ applicationId?: string;
20
+ /** Guild IDs to register slash commands (empty = global) */
21
+ guildIds?: string[];
22
+ /** Whether to use threads for conversations */
23
+ useThreads?: boolean;
24
+ }
25
+ export declare class DiscordChannel extends BaseChannel {
26
+ readonly type = "discord";
27
+ private config;
28
+ private ws;
29
+ private heartbeatInterval;
30
+ private sequenceNumber;
31
+ private sessionId;
32
+ private resumeUrl;
33
+ constructor(config?: DiscordChannelConfig);
34
+ start(): Promise<void>;
35
+ stop(): Promise<void>;
36
+ private identify;
37
+ private startHeartbeat;
38
+ private stopHeartbeat;
39
+ private sendHeartbeat;
40
+ private handleMessage;
41
+ sendMessage(channelId: string, content: string): Promise<void>;
42
+ private splitMessage;
43
+ }
44
+ //# sourceMappingURL=discord.d.ts.map
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DiscordChannel = void 0;
37
+ const index_1 = require("./index");
38
+ class DiscordChannel extends index_1.BaseChannel {
39
+ type = 'discord';
40
+ config;
41
+ ws = null;
42
+ heartbeatInterval = null;
43
+ sequenceNumber = null;
44
+ sessionId = null;
45
+ resumeUrl = null;
46
+ constructor(config = {}) {
47
+ super();
48
+ this.config = {
49
+ botToken: config.botToken ?? process.env.DISCORD_BOT_TOKEN ?? '',
50
+ applicationId: config.applicationId ?? process.env.DISCORD_APPLICATION_ID ?? '',
51
+ guildIds: config.guildIds ?? [],
52
+ useThreads: config.useThreads ?? true,
53
+ };
54
+ }
55
+ async start() {
56
+ if (!this.config.botToken) {
57
+ console.warn('[DiscordChannel] No bot token. Set DISCORD_BOT_TOKEN.');
58
+ return;
59
+ }
60
+ // Get gateway URL
61
+ const gatewayResp = await fetch('https://discord.com/api/v10/gateway/bot', {
62
+ headers: { Authorization: `Bot ${this.config.botToken}` },
63
+ });
64
+ const gatewayData = await gatewayResp.json();
65
+ const wsUrl = `${gatewayData.url}?v=10&encoding=json`;
66
+ const { WebSocket } = await Promise.resolve().then(() => __importStar(require('ws')));
67
+ this.ws = new WebSocket(wsUrl);
68
+ this.ws.on('message', async (data) => {
69
+ const payload = JSON.parse(data.toString());
70
+ this.sequenceNumber = payload.s ?? this.sequenceNumber;
71
+ switch (payload.op) {
72
+ case 10: // Hello
73
+ this.startHeartbeat(payload.d.heartbeat_interval);
74
+ this.identify();
75
+ break;
76
+ case 11: // Heartbeat ACK
77
+ break;
78
+ case 0: // Dispatch
79
+ if (payload.t === 'READY') {
80
+ this.sessionId = payload.d.session_id;
81
+ this.resumeUrl = payload.d.resume_gateway_url;
82
+ console.log(`[DiscordChannel] Connected as ${payload.d.user.username}`);
83
+ }
84
+ else if (payload.t === 'MESSAGE_CREATE') {
85
+ await this.handleMessage(payload.d);
86
+ }
87
+ break;
88
+ }
89
+ });
90
+ this.ws.on('close', (code) => {
91
+ console.log(`[DiscordChannel] WebSocket closed: ${code}`);
92
+ this.stopHeartbeat();
93
+ // Auto-reconnect after 5s for resumable codes
94
+ if (code !== 4004 && code !== 4014) {
95
+ setTimeout(() => this.start(), 5000);
96
+ }
97
+ });
98
+ this.ws.on('error', (err) => {
99
+ console.error('[DiscordChannel] WebSocket error:', err.message);
100
+ });
101
+ }
102
+ async stop() {
103
+ this.stopHeartbeat();
104
+ if (this.ws) {
105
+ this.ws.close(1000);
106
+ this.ws = null;
107
+ }
108
+ }
109
+ identify() {
110
+ this.ws?.send(JSON.stringify({
111
+ op: 2,
112
+ d: {
113
+ token: this.config.botToken,
114
+ intents: (1 << 9) | (1 << 15), // GUILD_MESSAGES | MESSAGE_CONTENT
115
+ properties: {
116
+ os: process.platform,
117
+ browser: 'opc-agent',
118
+ device: 'opc-agent',
119
+ },
120
+ },
121
+ }));
122
+ }
123
+ startHeartbeat(intervalMs) {
124
+ this.stopHeartbeat();
125
+ // Send first heartbeat with jitter
126
+ setTimeout(() => {
127
+ this.sendHeartbeat();
128
+ this.heartbeatInterval = setInterval(() => this.sendHeartbeat(), intervalMs);
129
+ }, intervalMs * Math.random());
130
+ }
131
+ stopHeartbeat() {
132
+ if (this.heartbeatInterval) {
133
+ clearInterval(this.heartbeatInterval);
134
+ this.heartbeatInterval = null;
135
+ }
136
+ }
137
+ sendHeartbeat() {
138
+ this.ws?.send(JSON.stringify({ op: 1, d: this.sequenceNumber }));
139
+ }
140
+ async handleMessage(d) {
141
+ // Ignore bot messages
142
+ const author = d.author;
143
+ if (author?.bot)
144
+ return;
145
+ if (!d.content || !this.handler)
146
+ return;
147
+ const msg = {
148
+ id: `discord_${d.id}`,
149
+ role: 'user',
150
+ content: d.content,
151
+ timestamp: new Date(d.timestamp).getTime(),
152
+ metadata: {
153
+ sessionId: `discord_${d.channel_id}`,
154
+ chatId: d.channel_id,
155
+ userId: author.id,
156
+ platform: 'discord',
157
+ guildId: d.guild_id,
158
+ threadId: d.thread?.toString(),
159
+ },
160
+ };
161
+ const response = await this.handler(msg);
162
+ await this.sendMessage(d.channel_id, response.content);
163
+ }
164
+ async sendMessage(channelId, content) {
165
+ // Discord max message length is 2000
166
+ const chunks = this.splitMessage(content, 2000);
167
+ for (const chunk of chunks) {
168
+ await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
169
+ method: 'POST',
170
+ headers: {
171
+ 'Content-Type': 'application/json',
172
+ Authorization: `Bot ${this.config.botToken}`,
173
+ },
174
+ body: JSON.stringify({ content: chunk }),
175
+ });
176
+ }
177
+ }
178
+ splitMessage(text, maxLen) {
179
+ if (text.length <= maxLen)
180
+ return [text];
181
+ const parts = [];
182
+ for (let i = 0; i < text.length; i += maxLen) {
183
+ parts.push(text.slice(i, i + maxLen));
184
+ }
185
+ return parts;
186
+ }
187
+ }
188
+ exports.DiscordChannel = DiscordChannel;
189
+ //# sourceMappingURL=discord.js.map
@@ -0,0 +1,47 @@
1
+ import { BaseChannel } from './index';
2
+ /**
3
+ * Feishu / Lark Channel — v1.1.0
4
+ *
5
+ * Supports:
6
+ * - Event Subscription (webhook) mode for receiving messages
7
+ * - Bot send via Feishu Open API
8
+ * - URL verification challenge
9
+ * - Message card (interactive) responses
10
+ * - Group chat & P2P messaging
11
+ *
12
+ * Env vars:
13
+ * FEISHU_APP_ID, FEISHU_APP_SECRET — app credentials
14
+ * FEISHU_VERIFICATION_TOKEN — event subscription verification
15
+ * FEISHU_ENCRYPT_KEY — (optional) event encryption key
16
+ */
17
+ export interface FeishuChannelConfig {
18
+ /** Feishu App ID */
19
+ appId?: string;
20
+ /** Feishu App Secret */
21
+ appSecret?: string;
22
+ /** Verification token for event subscription */
23
+ verificationToken?: string;
24
+ /** Encrypt key (optional, for encrypted events) */
25
+ encryptKey?: string;
26
+ /** Webhook server port (default: 3002) */
27
+ port?: number;
28
+ /** API base URL (use 'https://open.larksuite.com' for Lark international) */
29
+ apiBase?: string;
30
+ }
31
+ export declare class FeishuChannel extends BaseChannel {
32
+ readonly type = "feishu";
33
+ private config;
34
+ private server;
35
+ private tokenCache;
36
+ private processedEvents;
37
+ constructor(config?: FeishuChannelConfig);
38
+ start(): Promise<void>;
39
+ stop(): Promise<void>;
40
+ /** Get tenant access token (cached) */
41
+ private getAccessToken;
42
+ /** Send a text message to a chat */
43
+ sendTextMessage(chatId: string, text: string): Promise<void>;
44
+ /** Send an interactive card message */
45
+ sendCardMessage(chatId: string, card: Record<string, unknown>): Promise<void>;
46
+ }
47
+ //# sourceMappingURL=feishu.d.ts.map
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FeishuChannel = void 0;
37
+ const index_1 = require("./index");
38
+ class FeishuChannel extends index_1.BaseChannel {
39
+ type = 'feishu';
40
+ config;
41
+ server = null;
42
+ tokenCache = null;
43
+ processedEvents = new Set();
44
+ constructor(config = {}) {
45
+ super();
46
+ this.config = {
47
+ appId: config.appId ?? process.env.FEISHU_APP_ID ?? '',
48
+ appSecret: config.appSecret ?? process.env.FEISHU_APP_SECRET ?? '',
49
+ verificationToken: config.verificationToken ?? process.env.FEISHU_VERIFICATION_TOKEN ?? '',
50
+ encryptKey: config.encryptKey ?? process.env.FEISHU_ENCRYPT_KEY,
51
+ port: config.port ?? 3002,
52
+ apiBase: config.apiBase ?? 'https://open.feishu.cn',
53
+ };
54
+ }
55
+ async start() {
56
+ if (!this.config.appId || !this.config.appSecret) {
57
+ console.warn('[FeishuChannel] Missing appId/appSecret. Set FEISHU_APP_ID and FEISHU_APP_SECRET.');
58
+ return;
59
+ }
60
+ const express = (await Promise.resolve().then(() => __importStar(require('express')))).default;
61
+ const app = express();
62
+ app.use(express.json());
63
+ // Event subscription endpoint
64
+ app.post('/feishu/event', async (req, res) => {
65
+ try {
66
+ const body = req.body;
67
+ // URL verification challenge
68
+ if (body.type === 'url_verification') {
69
+ res.json({ challenge: body.challenge });
70
+ return;
71
+ }
72
+ // Deduplicate events
73
+ const eventId = body.header?.event_id;
74
+ if (eventId && this.processedEvents.has(eventId)) {
75
+ res.json({ ok: true });
76
+ return;
77
+ }
78
+ if (eventId) {
79
+ this.processedEvents.add(eventId);
80
+ // Prune old events (keep last 1000)
81
+ if (this.processedEvents.size > 1000) {
82
+ const arr = [...this.processedEvents];
83
+ this.processedEvents = new Set(arr.slice(-500));
84
+ }
85
+ }
86
+ // Verify token
87
+ if (this.config.verificationToken && body.header?.token !== this.config.verificationToken) {
88
+ res.status(403).json({ error: 'Invalid verification token' });
89
+ return;
90
+ }
91
+ // Handle im.message.receive_v1
92
+ const event = body.event;
93
+ if (body.header?.event_type === 'im.message.receive_v1' && this.handler) {
94
+ const msgBody = event?.message;
95
+ if (!msgBody) {
96
+ res.json({ ok: true });
97
+ return;
98
+ }
99
+ // Only handle text messages for now
100
+ const msgType = msgBody.message_type;
101
+ let content = '';
102
+ if (msgType === 'text') {
103
+ try {
104
+ const parsed = JSON.parse(msgBody.content);
105
+ content = parsed.text ?? '';
106
+ }
107
+ catch {
108
+ content = msgBody.content ?? '';
109
+ }
110
+ }
111
+ else {
112
+ // Acknowledge non-text silently
113
+ res.json({ ok: true });
114
+ return;
115
+ }
116
+ // Strip @bot mentions
117
+ content = content.replace(/@_user_\d+/g, '').trim();
118
+ if (!content) {
119
+ res.json({ ok: true });
120
+ return;
121
+ }
122
+ const chatId = msgBody.chat_id;
123
+ const senderId = event.sender?.sender_id?.open_id ?? 'unknown';
124
+ const msg = {
125
+ id: `feishu_${msgBody.message_id}`,
126
+ role: 'user',
127
+ content,
128
+ timestamp: parseInt(msgBody.create_time, 10) || Date.now(),
129
+ metadata: {
130
+ sessionId: `feishu_${chatId}`,
131
+ chatId,
132
+ userId: senderId,
133
+ platform: 'feishu',
134
+ messageId: msgBody.message_id,
135
+ chatType: msgBody.chat_type, // 'p2p' or 'group'
136
+ },
137
+ };
138
+ const response = await this.handler(msg);
139
+ await this.sendTextMessage(chatId, response.content);
140
+ }
141
+ res.json({ ok: true });
142
+ }
143
+ catch (err) {
144
+ console.error('[FeishuChannel] Error handling event:', err);
145
+ res.status(500).json({ error: 'Internal error' });
146
+ }
147
+ });
148
+ app.get('/health', (_req, res) => {
149
+ res.json({ status: 'ok', channel: 'feishu' });
150
+ });
151
+ this.server = app.listen(this.config.port, () => {
152
+ console.log(`[FeishuChannel] Listening on port ${this.config.port}`);
153
+ });
154
+ }
155
+ async stop() {
156
+ if (this.server) {
157
+ this.server.close();
158
+ this.server = null;
159
+ }
160
+ }
161
+ /** Get tenant access token (cached) */
162
+ async getAccessToken() {
163
+ if (this.tokenCache && Date.now() < this.tokenCache.expiresAt) {
164
+ return this.tokenCache.token;
165
+ }
166
+ const resp = await fetch(`${this.config.apiBase}/open-apis/auth/v3/tenant_access_token/internal`, {
167
+ method: 'POST',
168
+ headers: { 'Content-Type': 'application/json' },
169
+ body: JSON.stringify({
170
+ app_id: this.config.appId,
171
+ app_secret: this.config.appSecret,
172
+ }),
173
+ });
174
+ const data = await resp.json();
175
+ if (data.code !== 0) {
176
+ throw new Error(`[FeishuChannel] Failed to get access token: ${JSON.stringify(data)}`);
177
+ }
178
+ this.tokenCache = {
179
+ token: data.tenant_access_token,
180
+ expiresAt: Date.now() + (data.expire - 60) * 1000, // refresh 60s early
181
+ };
182
+ return this.tokenCache.token;
183
+ }
184
+ /** Send a text message to a chat */
185
+ async sendTextMessage(chatId, text) {
186
+ const token = await this.getAccessToken();
187
+ const resp = await fetch(`${this.config.apiBase}/open-apis/im/v1/messages?receive_id_type=chat_id`, {
188
+ method: 'POST',
189
+ headers: {
190
+ 'Content-Type': 'application/json',
191
+ 'Authorization': `Bearer ${token}`,
192
+ },
193
+ body: JSON.stringify({
194
+ receive_id: chatId,
195
+ msg_type: 'text',
196
+ content: JSON.stringify({ text }),
197
+ }),
198
+ });
199
+ if (!resp.ok) {
200
+ console.error('[FeishuChannel] Failed to send message:', await resp.text());
201
+ }
202
+ }
203
+ /** Send an interactive card message */
204
+ async sendCardMessage(chatId, card) {
205
+ const token = await this.getAccessToken();
206
+ await fetch(`${this.config.apiBase}/open-apis/im/v1/messages?receive_id_type=chat_id`, {
207
+ method: 'POST',
208
+ headers: {
209
+ 'Content-Type': 'application/json',
210
+ 'Authorization': `Bearer ${token}`,
211
+ },
212
+ body: JSON.stringify({
213
+ receive_id: chatId,
214
+ msg_type: 'interactive',
215
+ content: JSON.stringify(card),
216
+ }),
217
+ });
218
+ }
219
+ }
220
+ exports.FeishuChannel = FeishuChannel;
221
+ //# sourceMappingURL=feishu.js.map
@@ -0,0 +1,73 @@
1
+ import { EventEmitter } from 'events';
2
+ /**
3
+ * ProcessWatcher — Background process output monitoring with pattern matching.
4
+ *
5
+ * Inspired by Hermes Agent's watch_patterns feature.
6
+ * Set patterns to watch for in background process output and get callbacks
7
+ * when they match — no polling needed.
8
+ *
9
+ * Usage:
10
+ * const watcher = new ProcessWatcher();
11
+ * watcher.watch(childProcess.stdout, {
12
+ * patterns: [
13
+ * { regex: /listening on port (\d+)/, label: 'server-ready' },
14
+ * { regex: /error|Error|ERROR/, label: 'error-detected' },
15
+ * { regex: /build completed/, label: 'build-done', once: true },
16
+ * ],
17
+ * onMatch: (match) => console.log(`[${match.label}] ${match.line}`),
18
+ * });
19
+ */
20
+ export interface WatchPattern {
21
+ /** Regex to match against each line of output */
22
+ regex: RegExp;
23
+ /** Human-readable label for this pattern */
24
+ label: string;
25
+ /** If true, auto-remove after first match */
26
+ once?: boolean;
27
+ }
28
+ export interface WatchMatch {
29
+ /** Pattern label */
30
+ label: string;
31
+ /** The full line that matched */
32
+ line: string;
33
+ /** Regex match groups */
34
+ groups: string[];
35
+ /** Timestamp of match */
36
+ timestamp: number;
37
+ /** Stream source */
38
+ stream: 'stdout' | 'stderr';
39
+ }
40
+ export interface WatchOptions {
41
+ /** Patterns to match */
42
+ patterns: WatchPattern[];
43
+ /** Callback on match */
44
+ onMatch: (match: WatchMatch) => void;
45
+ /** Optional: max matches to keep in history (default: 100) */
46
+ maxHistory?: number;
47
+ }
48
+ export declare class ProcessWatcher extends EventEmitter {
49
+ private watchers;
50
+ private watcherIdCounter;
51
+ /**
52
+ * Start watching a readable stream for patterns.
53
+ * Returns a watcher ID that can be used to stop watching.
54
+ */
55
+ watch(stream: NodeJS.ReadableStream, options: WatchOptions, streamName?: 'stdout' | 'stderr'): string;
56
+ /**
57
+ * Watch both stdout and stderr of a ChildProcess.
58
+ */
59
+ watchProcess(proc: {
60
+ stdout?: NodeJS.ReadableStream | null;
61
+ stderr?: NodeJS.ReadableStream | null;
62
+ }, options: WatchOptions): string[];
63
+ /** Stop a specific watcher */
64
+ unwatch(id: string): void;
65
+ /** Get match history for a watcher */
66
+ getHistory(id: string): WatchMatch[];
67
+ /** Add a pattern to an existing watcher */
68
+ addPattern(id: string, pattern: WatchPattern): void;
69
+ /** Remove a pattern by label from a watcher */
70
+ removePattern(id: string, label: string): void;
71
+ private matchLine;
72
+ }
73
+ //# sourceMappingURL=watch.d.ts.map
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProcessWatcher = void 0;
4
+ const events_1 = require("events");
5
+ class ProcessWatcher extends events_1.EventEmitter {
6
+ watchers = new Map();
7
+ watcherIdCounter = 0;
8
+ /**
9
+ * Start watching a readable stream for patterns.
10
+ * Returns a watcher ID that can be used to stop watching.
11
+ */
12
+ watch(stream, options, streamName = 'stdout') {
13
+ const id = `watcher_${++this.watcherIdCounter}`;
14
+ const state = {
15
+ patterns: [...options.patterns],
16
+ onMatch: options.onMatch,
17
+ history: [],
18
+ maxHistory: options.maxHistory ?? 100,
19
+ };
20
+ this.watchers.set(id, state);
21
+ let buffer = '';
22
+ const onData = (chunk) => {
23
+ buffer += chunk.toString();
24
+ const lines = buffer.split('\n');
25
+ buffer = lines.pop() ?? ''; // Keep incomplete line in buffer
26
+ for (const line of lines) {
27
+ this.matchLine(id, line, streamName);
28
+ }
29
+ };
30
+ stream.on('data', onData);
31
+ stream.on('end', () => {
32
+ // Process remaining buffer
33
+ if (buffer)
34
+ this.matchLine(id, buffer, streamName);
35
+ this.watchers.delete(id);
36
+ this.emit('watcher:end', id);
37
+ });
38
+ return id;
39
+ }
40
+ /**
41
+ * Watch both stdout and stderr of a ChildProcess.
42
+ */
43
+ watchProcess(proc, options) {
44
+ const ids = [];
45
+ if (proc.stdout)
46
+ ids.push(this.watch(proc.stdout, options, 'stdout'));
47
+ if (proc.stderr)
48
+ ids.push(this.watch(proc.stderr, options, 'stderr'));
49
+ return ids;
50
+ }
51
+ /** Stop a specific watcher */
52
+ unwatch(id) {
53
+ this.watchers.delete(id);
54
+ }
55
+ /** Get match history for a watcher */
56
+ getHistory(id) {
57
+ return this.watchers.get(id)?.history ?? [];
58
+ }
59
+ /** Add a pattern to an existing watcher */
60
+ addPattern(id, pattern) {
61
+ const state = this.watchers.get(id);
62
+ if (state)
63
+ state.patterns.push(pattern);
64
+ }
65
+ /** Remove a pattern by label from a watcher */
66
+ removePattern(id, label) {
67
+ const state = this.watchers.get(id);
68
+ if (state) {
69
+ state.patterns = state.patterns.filter(p => p.label !== label);
70
+ }
71
+ }
72
+ matchLine(watcherId, line, stream) {
73
+ const state = this.watchers.get(watcherId);
74
+ if (!state)
75
+ return;
76
+ const toRemove = [];
77
+ for (let i = 0; i < state.patterns.length; i++) {
78
+ const pattern = state.patterns[i];
79
+ const m = line.match(pattern.regex);
80
+ if (m) {
81
+ const match = {
82
+ label: pattern.label,
83
+ line,
84
+ groups: m.slice(1),
85
+ timestamp: Date.now(),
86
+ stream,
87
+ };
88
+ state.history.push(match);
89
+ if (state.history.length > state.maxHistory) {
90
+ state.history.shift();
91
+ }
92
+ state.onMatch(match);
93
+ this.emit('match', match);
94
+ if (pattern.once) {
95
+ toRemove.push(i);
96
+ }
97
+ }
98
+ }
99
+ // Remove once-patterns in reverse order
100
+ for (let i = toRemove.length - 1; i >= 0; i--) {
101
+ state.patterns.splice(toRemove[i], 1);
102
+ }
103
+ }
104
+ }
105
+ exports.ProcessWatcher = ProcessWatcher;
106
+ //# sourceMappingURL=watch.js.map
package/dist/index.d.ts CHANGED
@@ -85,4 +85,10 @@ export { sanitizeInput, detectInjection, securityHeaders, corsMiddleware, APIKey
85
85
  export type { SecurityHeadersConfig, CORSConfig, APIKeyEntry } from './core/security';
86
86
  export { createLoggingPlugin, createAnalyticsPlugin, createRateLimitPlugin } from './plugins';
87
87
  export type { PluginManifest } from './plugins';
88
+ export { FeishuChannel } from './channels/feishu';
89
+ export type { FeishuChannelConfig } from './channels/feishu';
90
+ export { DiscordChannel } from './channels/discord';
91
+ export type { DiscordChannelConfig } from './channels/discord';
92
+ export { ProcessWatcher } from './core/watch';
93
+ export type { WatchPattern, WatchMatch, WatchOptions } from './core/watch';
88
94
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EmailChannel = exports.compose = exports.AgentPipeline = exports.Orchestrator = exports.getActiveSessions = exports.createAuthMiddleware = exports.installAgent = exports.publishAgent = exports.deployToHermes = exports.KnowledgeBase = exports.addMessages = exports.detectLocale = exports.getLocale = exports.setLocale = exports.t = exports.LazyLoader = exports.RequestBatcher = exports.ConnectionPool = exports.VersionManager = exports.WebhookChannel = exports.VoiceChannel = exports.HITLManager = exports.AgentRegistry = exports.WorkflowEngine = exports.Analytics = exports.Sandbox = exports.PluginManager = exports.createMCPTool = exports.MCPToolRegistry = exports.Room = exports.SUPPORTED_PROVIDERS = exports.createProvider = exports.MRGConfigReader = exports.ValueTracker = exports.TrustManager = exports.DeepBrainMemoryStore = exports.InMemoryStore = exports.SkillRegistry = exports.BaseSkill = exports.WebSocketChannel = exports.TelegramChannel = exports.WebChannel = exports.BaseChannel = exports.OADSchema = exports.validateOAD = exports.loadOAD = exports.Logger = exports.truncateOutput = exports.AgentRuntime = exports.BaseAgent = void 0;
4
- exports.createRateLimitPlugin = exports.createAnalyticsPlugin = exports.createLoggingPlugin = exports.inputValidation = exports.APIKeyManager = exports.corsMiddleware = exports.securityHeaders = exports.detectInjection = exports.sanitizeInput = exports.formatErrorForUser = exports.wrapError = exports.TimeoutError = exports.SecurityError = exports.RateLimitError = exports.PluginError = exports.ChannelError = exports.ConfigError = exports.ValidationError = exports.ProviderError = exports.OPCError = exports.createTeacherConfig = exports.createDataAnalystConfig = exports.getSupportedLocales = exports.LLMCache = exports.RateLimiter = exports.AnalyticsEngine = exports.formatReport = exports.loadTestCases = exports.runTests = exports.DocumentSkill = exports.SchedulerSkill = exports.WebhookTriggerSkill = exports.HttpSkill = exports.TextAnalysisTool = exports.JsonTransformTool = exports.DateTimeTool = exports.CalculatorTool = exports.WeChatChannel = exports.SlackChannel = void 0;
4
+ exports.ProcessWatcher = exports.DiscordChannel = exports.FeishuChannel = exports.createRateLimitPlugin = exports.createAnalyticsPlugin = exports.createLoggingPlugin = exports.inputValidation = exports.APIKeyManager = exports.corsMiddleware = exports.securityHeaders = exports.detectInjection = exports.sanitizeInput = exports.formatErrorForUser = exports.wrapError = exports.TimeoutError = exports.SecurityError = exports.RateLimitError = exports.PluginError = exports.ChannelError = exports.ConfigError = exports.ValidationError = exports.ProviderError = exports.OPCError = exports.createTeacherConfig = exports.createDataAnalystConfig = exports.getSupportedLocales = exports.LLMCache = exports.RateLimiter = exports.AnalyticsEngine = exports.formatReport = exports.loadTestCases = exports.runTests = exports.DocumentSkill = exports.SchedulerSkill = exports.WebhookTriggerSkill = exports.HttpSkill = exports.TextAnalysisTool = exports.JsonTransformTool = exports.DateTimeTool = exports.CalculatorTool = exports.WeChatChannel = exports.SlackChannel = void 0;
5
5
  // OPC Agent — Open Agent Framework
6
6
  var agent_1 = require("./core/agent");
7
7
  Object.defineProperty(exports, "BaseAgent", { enumerable: true, get: function () { return agent_1.BaseAgent; } });
@@ -156,4 +156,11 @@ var plugins_2 = require("./plugins");
156
156
  Object.defineProperty(exports, "createLoggingPlugin", { enumerable: true, get: function () { return plugins_2.createLoggingPlugin; } });
157
157
  Object.defineProperty(exports, "createAnalyticsPlugin", { enumerable: true, get: function () { return plugins_2.createAnalyticsPlugin; } });
158
158
  Object.defineProperty(exports, "createRateLimitPlugin", { enumerable: true, get: function () { return plugins_2.createRateLimitPlugin; } });
159
+ // v1.1.0 modules
160
+ var feishu_1 = require("./channels/feishu");
161
+ Object.defineProperty(exports, "FeishuChannel", { enumerable: true, get: function () { return feishu_1.FeishuChannel; } });
162
+ var discord_1 = require("./channels/discord");
163
+ Object.defineProperty(exports, "DiscordChannel", { enumerable: true, get: function () { return discord_1.DiscordChannel; } });
164
+ var watch_1 = require("./core/watch");
165
+ Object.defineProperty(exports, "ProcessWatcher", { enumerable: true, get: function () { return watch_1.ProcessWatcher; } });
159
166
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opc-agent",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Open Agent Framework — Build, test, and run AI Agents for business workstations",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -0,0 +1,192 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ /**
5
+ * Discord Channel — v1.1.0
6
+ *
7
+ * Supports:
8
+ * - Discord Bot via Gateway (WebSocket) or HTTP interactions
9
+ * - Slash commands, message content intent
10
+ * - Thread-based conversations
11
+ * - Reactions, embeds
12
+ *
13
+ * Env vars:
14
+ * DISCORD_BOT_TOKEN — bot token
15
+ * DISCORD_APPLICATION_ID — application ID for slash commands
16
+ */
17
+
18
+ export interface DiscordChannelConfig {
19
+ /** Bot token */
20
+ botToken?: string;
21
+ /** Application ID */
22
+ applicationId?: string;
23
+ /** Guild IDs to register slash commands (empty = global) */
24
+ guildIds?: string[];
25
+ /** Whether to use threads for conversations */
26
+ useThreads?: boolean;
27
+ }
28
+
29
+ export class DiscordChannel extends BaseChannel {
30
+ readonly type = 'discord';
31
+ private config: DiscordChannelConfig;
32
+ private ws: import('ws').WebSocket | null = null;
33
+ private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
34
+ private sequenceNumber: number | null = null;
35
+ private sessionId: string | null = null;
36
+ private resumeUrl: string | null = null;
37
+
38
+ constructor(config: DiscordChannelConfig = {}) {
39
+ super();
40
+ this.config = {
41
+ botToken: config.botToken ?? process.env.DISCORD_BOT_TOKEN ?? '',
42
+ applicationId: config.applicationId ?? process.env.DISCORD_APPLICATION_ID ?? '',
43
+ guildIds: config.guildIds ?? [],
44
+ useThreads: config.useThreads ?? true,
45
+ };
46
+ }
47
+
48
+ async start(): Promise<void> {
49
+ if (!this.config.botToken) {
50
+ console.warn('[DiscordChannel] No bot token. Set DISCORD_BOT_TOKEN.');
51
+ return;
52
+ }
53
+
54
+ // Get gateway URL
55
+ const gatewayResp = await fetch('https://discord.com/api/v10/gateway/bot', {
56
+ headers: { Authorization: `Bot ${this.config.botToken}` },
57
+ });
58
+ const gatewayData = await gatewayResp.json() as { url: string };
59
+ const wsUrl = `${gatewayData.url}?v=10&encoding=json`;
60
+
61
+ const { WebSocket } = await import('ws');
62
+ this.ws = new WebSocket(wsUrl);
63
+
64
+ this.ws.on('message', async (data: Buffer) => {
65
+ const payload = JSON.parse(data.toString());
66
+ this.sequenceNumber = payload.s ?? this.sequenceNumber;
67
+
68
+ switch (payload.op) {
69
+ case 10: // Hello
70
+ this.startHeartbeat(payload.d.heartbeat_interval);
71
+ this.identify();
72
+ break;
73
+ case 11: // Heartbeat ACK
74
+ break;
75
+ case 0: // Dispatch
76
+ if (payload.t === 'READY') {
77
+ this.sessionId = payload.d.session_id;
78
+ this.resumeUrl = payload.d.resume_gateway_url;
79
+ console.log(`[DiscordChannel] Connected as ${payload.d.user.username}`);
80
+ } else if (payload.t === 'MESSAGE_CREATE') {
81
+ await this.handleMessage(payload.d);
82
+ }
83
+ break;
84
+ }
85
+ });
86
+
87
+ this.ws.on('close', (code: number) => {
88
+ console.log(`[DiscordChannel] WebSocket closed: ${code}`);
89
+ this.stopHeartbeat();
90
+ // Auto-reconnect after 5s for resumable codes
91
+ if (code !== 4004 && code !== 4014) {
92
+ setTimeout(() => this.start(), 5000);
93
+ }
94
+ });
95
+
96
+ this.ws.on('error', (err: Error) => {
97
+ console.error('[DiscordChannel] WebSocket error:', err.message);
98
+ });
99
+ }
100
+
101
+ async stop(): Promise<void> {
102
+ this.stopHeartbeat();
103
+ if (this.ws) {
104
+ this.ws.close(1000);
105
+ this.ws = null;
106
+ }
107
+ }
108
+
109
+ private identify(): void {
110
+ this.ws?.send(JSON.stringify({
111
+ op: 2,
112
+ d: {
113
+ token: this.config.botToken,
114
+ intents: (1 << 9) | (1 << 15), // GUILD_MESSAGES | MESSAGE_CONTENT
115
+ properties: {
116
+ os: process.platform,
117
+ browser: 'opc-agent',
118
+ device: 'opc-agent',
119
+ },
120
+ },
121
+ }));
122
+ }
123
+
124
+ private startHeartbeat(intervalMs: number): void {
125
+ this.stopHeartbeat();
126
+ // Send first heartbeat with jitter
127
+ setTimeout(() => {
128
+ this.sendHeartbeat();
129
+ this.heartbeatInterval = setInterval(() => this.sendHeartbeat(), intervalMs);
130
+ }, intervalMs * Math.random());
131
+ }
132
+
133
+ private stopHeartbeat(): void {
134
+ if (this.heartbeatInterval) {
135
+ clearInterval(this.heartbeatInterval);
136
+ this.heartbeatInterval = null;
137
+ }
138
+ }
139
+
140
+ private sendHeartbeat(): void {
141
+ this.ws?.send(JSON.stringify({ op: 1, d: this.sequenceNumber }));
142
+ }
143
+
144
+ private async handleMessage(d: Record<string, unknown>): Promise<void> {
145
+ // Ignore bot messages
146
+ const author = d.author as Record<string, unknown>;
147
+ if (author?.bot) return;
148
+ if (!d.content || !this.handler) return;
149
+
150
+ const msg: Message = {
151
+ id: `discord_${d.id}`,
152
+ role: 'user',
153
+ content: d.content as string,
154
+ timestamp: new Date(d.timestamp as string).getTime(),
155
+ metadata: {
156
+ sessionId: `discord_${d.channel_id}`,
157
+ chatId: d.channel_id as string,
158
+ userId: author.id as string,
159
+ platform: 'discord',
160
+ guildId: d.guild_id as string | undefined,
161
+ threadId: (d as Record<string, unknown>).thread?.toString(),
162
+ },
163
+ };
164
+
165
+ const response = await this.handler(msg);
166
+ await this.sendMessage(d.channel_id as string, response.content);
167
+ }
168
+
169
+ async sendMessage(channelId: string, content: string): Promise<void> {
170
+ // Discord max message length is 2000
171
+ const chunks = this.splitMessage(content, 2000);
172
+ for (const chunk of chunks) {
173
+ await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
174
+ method: 'POST',
175
+ headers: {
176
+ 'Content-Type': 'application/json',
177
+ Authorization: `Bot ${this.config.botToken}`,
178
+ },
179
+ body: JSON.stringify({ content: chunk }),
180
+ });
181
+ }
182
+ }
183
+
184
+ private splitMessage(text: string, maxLen: number): string[] {
185
+ if (text.length <= maxLen) return [text];
186
+ const parts: string[] = [];
187
+ for (let i = 0; i < text.length; i += maxLen) {
188
+ parts.push(text.slice(i, i + maxLen));
189
+ }
190
+ return parts;
191
+ }
192
+ }
@@ -0,0 +1,236 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ /**
5
+ * Feishu / Lark Channel — v1.1.0
6
+ *
7
+ * Supports:
8
+ * - Event Subscription (webhook) mode for receiving messages
9
+ * - Bot send via Feishu Open API
10
+ * - URL verification challenge
11
+ * - Message card (interactive) responses
12
+ * - Group chat & P2P messaging
13
+ *
14
+ * Env vars:
15
+ * FEISHU_APP_ID, FEISHU_APP_SECRET — app credentials
16
+ * FEISHU_VERIFICATION_TOKEN — event subscription verification
17
+ * FEISHU_ENCRYPT_KEY — (optional) event encryption key
18
+ */
19
+
20
+ export interface FeishuChannelConfig {
21
+ /** Feishu App ID */
22
+ appId?: string;
23
+ /** Feishu App Secret */
24
+ appSecret?: string;
25
+ /** Verification token for event subscription */
26
+ verificationToken?: string;
27
+ /** Encrypt key (optional, for encrypted events) */
28
+ encryptKey?: string;
29
+ /** Webhook server port (default: 3002) */
30
+ port?: number;
31
+ /** API base URL (use 'https://open.larksuite.com' for Lark international) */
32
+ apiBase?: string;
33
+ }
34
+
35
+ interface FeishuTokenCache {
36
+ token: string;
37
+ expiresAt: number;
38
+ }
39
+
40
+ export class FeishuChannel extends BaseChannel {
41
+ readonly type = 'feishu';
42
+ private config: Required<Pick<FeishuChannelConfig, 'port' | 'apiBase'>> & FeishuChannelConfig;
43
+ private server: import('http').Server | null = null;
44
+ private tokenCache: FeishuTokenCache | null = null;
45
+ private processedEvents = new Set<string>();
46
+
47
+ constructor(config: FeishuChannelConfig = {}) {
48
+ super();
49
+ this.config = {
50
+ appId: config.appId ?? process.env.FEISHU_APP_ID ?? '',
51
+ appSecret: config.appSecret ?? process.env.FEISHU_APP_SECRET ?? '',
52
+ verificationToken: config.verificationToken ?? process.env.FEISHU_VERIFICATION_TOKEN ?? '',
53
+ encryptKey: config.encryptKey ?? process.env.FEISHU_ENCRYPT_KEY,
54
+ port: config.port ?? 3002,
55
+ apiBase: config.apiBase ?? 'https://open.feishu.cn',
56
+ };
57
+ }
58
+
59
+ async start(): Promise<void> {
60
+ if (!this.config.appId || !this.config.appSecret) {
61
+ console.warn('[FeishuChannel] Missing appId/appSecret. Set FEISHU_APP_ID and FEISHU_APP_SECRET.');
62
+ return;
63
+ }
64
+
65
+ const express = (await import('express')).default;
66
+ const app = express();
67
+ app.use(express.json());
68
+
69
+ // Event subscription endpoint
70
+ app.post('/feishu/event', async (req, res) => {
71
+ try {
72
+ const body = req.body;
73
+
74
+ // URL verification challenge
75
+ if (body.type === 'url_verification') {
76
+ res.json({ challenge: body.challenge });
77
+ return;
78
+ }
79
+
80
+ // Deduplicate events
81
+ const eventId = body.header?.event_id;
82
+ if (eventId && this.processedEvents.has(eventId)) {
83
+ res.json({ ok: true });
84
+ return;
85
+ }
86
+ if (eventId) {
87
+ this.processedEvents.add(eventId);
88
+ // Prune old events (keep last 1000)
89
+ if (this.processedEvents.size > 1000) {
90
+ const arr = [...this.processedEvents];
91
+ this.processedEvents = new Set(arr.slice(-500));
92
+ }
93
+ }
94
+
95
+ // Verify token
96
+ if (this.config.verificationToken && body.header?.token !== this.config.verificationToken) {
97
+ res.status(403).json({ error: 'Invalid verification token' });
98
+ return;
99
+ }
100
+
101
+ // Handle im.message.receive_v1
102
+ const event = body.event;
103
+ if (body.header?.event_type === 'im.message.receive_v1' && this.handler) {
104
+ const msgBody = event?.message;
105
+ if (!msgBody) { res.json({ ok: true }); return; }
106
+
107
+ // Only handle text messages for now
108
+ const msgType = msgBody.message_type;
109
+ let content = '';
110
+ if (msgType === 'text') {
111
+ try {
112
+ const parsed = JSON.parse(msgBody.content);
113
+ content = parsed.text ?? '';
114
+ } catch {
115
+ content = msgBody.content ?? '';
116
+ }
117
+ } else {
118
+ // Acknowledge non-text silently
119
+ res.json({ ok: true });
120
+ return;
121
+ }
122
+
123
+ // Strip @bot mentions
124
+ content = content.replace(/@_user_\d+/g, '').trim();
125
+ if (!content) { res.json({ ok: true }); return; }
126
+
127
+ const chatId = msgBody.chat_id;
128
+ const senderId = event.sender?.sender_id?.open_id ?? 'unknown';
129
+
130
+ const msg: Message = {
131
+ id: `feishu_${msgBody.message_id}`,
132
+ role: 'user',
133
+ content,
134
+ timestamp: parseInt(msgBody.create_time, 10) || Date.now(),
135
+ metadata: {
136
+ sessionId: `feishu_${chatId}`,
137
+ chatId,
138
+ userId: senderId,
139
+ platform: 'feishu',
140
+ messageId: msgBody.message_id,
141
+ chatType: msgBody.chat_type, // 'p2p' or 'group'
142
+ },
143
+ };
144
+
145
+ const response = await this.handler(msg);
146
+ await this.sendTextMessage(chatId, response.content);
147
+ }
148
+
149
+ res.json({ ok: true });
150
+ } catch (err) {
151
+ console.error('[FeishuChannel] Error handling event:', err);
152
+ res.status(500).json({ error: 'Internal error' });
153
+ }
154
+ });
155
+
156
+ app.get('/health', (_req, res) => {
157
+ res.json({ status: 'ok', channel: 'feishu' });
158
+ });
159
+
160
+ this.server = app.listen(this.config.port, () => {
161
+ console.log(`[FeishuChannel] Listening on port ${this.config.port}`);
162
+ });
163
+ }
164
+
165
+ async stop(): Promise<void> {
166
+ if (this.server) {
167
+ this.server.close();
168
+ this.server = null;
169
+ }
170
+ }
171
+
172
+ /** Get tenant access token (cached) */
173
+ private async getAccessToken(): Promise<string> {
174
+ if (this.tokenCache && Date.now() < this.tokenCache.expiresAt) {
175
+ return this.tokenCache.token;
176
+ }
177
+
178
+ const resp = await fetch(`${this.config.apiBase}/open-apis/auth/v3/tenant_access_token/internal`, {
179
+ method: 'POST',
180
+ headers: { 'Content-Type': 'application/json' },
181
+ body: JSON.stringify({
182
+ app_id: this.config.appId,
183
+ app_secret: this.config.appSecret,
184
+ }),
185
+ });
186
+
187
+ const data = await resp.json() as { tenant_access_token: string; expire: number; code: number };
188
+ if (data.code !== 0) {
189
+ throw new Error(`[FeishuChannel] Failed to get access token: ${JSON.stringify(data)}`);
190
+ }
191
+
192
+ this.tokenCache = {
193
+ token: data.tenant_access_token,
194
+ expiresAt: Date.now() + (data.expire - 60) * 1000, // refresh 60s early
195
+ };
196
+ return this.tokenCache.token;
197
+ }
198
+
199
+ /** Send a text message to a chat */
200
+ async sendTextMessage(chatId: string, text: string): Promise<void> {
201
+ const token = await this.getAccessToken();
202
+ const resp = await fetch(`${this.config.apiBase}/open-apis/im/v1/messages?receive_id_type=chat_id`, {
203
+ method: 'POST',
204
+ headers: {
205
+ 'Content-Type': 'application/json',
206
+ 'Authorization': `Bearer ${token}`,
207
+ },
208
+ body: JSON.stringify({
209
+ receive_id: chatId,
210
+ msg_type: 'text',
211
+ content: JSON.stringify({ text }),
212
+ }),
213
+ });
214
+
215
+ if (!resp.ok) {
216
+ console.error('[FeishuChannel] Failed to send message:', await resp.text());
217
+ }
218
+ }
219
+
220
+ /** Send an interactive card message */
221
+ async sendCardMessage(chatId: string, card: Record<string, unknown>): Promise<void> {
222
+ const token = await this.getAccessToken();
223
+ await fetch(`${this.config.apiBase}/open-apis/im/v1/messages?receive_id_type=chat_id`, {
224
+ method: 'POST',
225
+ headers: {
226
+ 'Content-Type': 'application/json',
227
+ 'Authorization': `Bearer ${token}`,
228
+ },
229
+ body: JSON.stringify({
230
+ receive_id: chatId,
231
+ msg_type: 'interactive',
232
+ content: JSON.stringify(card),
233
+ }),
234
+ });
235
+ }
236
+ }
@@ -0,0 +1,178 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ /**
4
+ * ProcessWatcher — Background process output monitoring with pattern matching.
5
+ *
6
+ * Inspired by Hermes Agent's watch_patterns feature.
7
+ * Set patterns to watch for in background process output and get callbacks
8
+ * when they match — no polling needed.
9
+ *
10
+ * Usage:
11
+ * const watcher = new ProcessWatcher();
12
+ * watcher.watch(childProcess.stdout, {
13
+ * patterns: [
14
+ * { regex: /listening on port (\d+)/, label: 'server-ready' },
15
+ * { regex: /error|Error|ERROR/, label: 'error-detected' },
16
+ * { regex: /build completed/, label: 'build-done', once: true },
17
+ * ],
18
+ * onMatch: (match) => console.log(`[${match.label}] ${match.line}`),
19
+ * });
20
+ */
21
+
22
+ export interface WatchPattern {
23
+ /** Regex to match against each line of output */
24
+ regex: RegExp;
25
+ /** Human-readable label for this pattern */
26
+ label: string;
27
+ /** If true, auto-remove after first match */
28
+ once?: boolean;
29
+ }
30
+
31
+ export interface WatchMatch {
32
+ /** Pattern label */
33
+ label: string;
34
+ /** The full line that matched */
35
+ line: string;
36
+ /** Regex match groups */
37
+ groups: string[];
38
+ /** Timestamp of match */
39
+ timestamp: number;
40
+ /** Stream source */
41
+ stream: 'stdout' | 'stderr';
42
+ }
43
+
44
+ export interface WatchOptions {
45
+ /** Patterns to match */
46
+ patterns: WatchPattern[];
47
+ /** Callback on match */
48
+ onMatch: (match: WatchMatch) => void;
49
+ /** Optional: max matches to keep in history (default: 100) */
50
+ maxHistory?: number;
51
+ }
52
+
53
+ export class ProcessWatcher extends EventEmitter {
54
+ private watchers = new Map<string, {
55
+ patterns: WatchPattern[];
56
+ onMatch: (match: WatchMatch) => void;
57
+ history: WatchMatch[];
58
+ maxHistory: number;
59
+ }>();
60
+
61
+ private watcherIdCounter = 0;
62
+
63
+ /**
64
+ * Start watching a readable stream for patterns.
65
+ * Returns a watcher ID that can be used to stop watching.
66
+ */
67
+ watch(
68
+ stream: NodeJS.ReadableStream,
69
+ options: WatchOptions,
70
+ streamName: 'stdout' | 'stderr' = 'stdout',
71
+ ): string {
72
+ const id = `watcher_${++this.watcherIdCounter}`;
73
+ const state = {
74
+ patterns: [...options.patterns],
75
+ onMatch: options.onMatch,
76
+ history: [] as WatchMatch[],
77
+ maxHistory: options.maxHistory ?? 100,
78
+ };
79
+ this.watchers.set(id, state);
80
+
81
+ let buffer = '';
82
+
83
+ const onData = (chunk: Buffer | string) => {
84
+ buffer += chunk.toString();
85
+ const lines = buffer.split('\n');
86
+ buffer = lines.pop() ?? ''; // Keep incomplete line in buffer
87
+
88
+ for (const line of lines) {
89
+ this.matchLine(id, line, streamName);
90
+ }
91
+ };
92
+
93
+ stream.on('data', onData);
94
+ stream.on('end', () => {
95
+ // Process remaining buffer
96
+ if (buffer) this.matchLine(id, buffer, streamName);
97
+ this.watchers.delete(id);
98
+ this.emit('watcher:end', id);
99
+ });
100
+
101
+ return id;
102
+ }
103
+
104
+ /**
105
+ * Watch both stdout and stderr of a ChildProcess.
106
+ */
107
+ watchProcess(
108
+ proc: { stdout?: NodeJS.ReadableStream | null; stderr?: NodeJS.ReadableStream | null },
109
+ options: WatchOptions,
110
+ ): string[] {
111
+ const ids: string[] = [];
112
+ if (proc.stdout) ids.push(this.watch(proc.stdout, options, 'stdout'));
113
+ if (proc.stderr) ids.push(this.watch(proc.stderr, options, 'stderr'));
114
+ return ids;
115
+ }
116
+
117
+ /** Stop a specific watcher */
118
+ unwatch(id: string): void {
119
+ this.watchers.delete(id);
120
+ }
121
+
122
+ /** Get match history for a watcher */
123
+ getHistory(id: string): WatchMatch[] {
124
+ return this.watchers.get(id)?.history ?? [];
125
+ }
126
+
127
+ /** Add a pattern to an existing watcher */
128
+ addPattern(id: string, pattern: WatchPattern): void {
129
+ const state = this.watchers.get(id);
130
+ if (state) state.patterns.push(pattern);
131
+ }
132
+
133
+ /** Remove a pattern by label from a watcher */
134
+ removePattern(id: string, label: string): void {
135
+ const state = this.watchers.get(id);
136
+ if (state) {
137
+ state.patterns = state.patterns.filter(p => p.label !== label);
138
+ }
139
+ }
140
+
141
+ private matchLine(watcherId: string, line: string, stream: 'stdout' | 'stderr'): void {
142
+ const state = this.watchers.get(watcherId);
143
+ if (!state) return;
144
+
145
+ const toRemove: number[] = [];
146
+
147
+ for (let i = 0; i < state.patterns.length; i++) {
148
+ const pattern = state.patterns[i];
149
+ const m = line.match(pattern.regex);
150
+ if (m) {
151
+ const match: WatchMatch = {
152
+ label: pattern.label,
153
+ line,
154
+ groups: m.slice(1),
155
+ timestamp: Date.now(),
156
+ stream,
157
+ };
158
+
159
+ state.history.push(match);
160
+ if (state.history.length > state.maxHistory) {
161
+ state.history.shift();
162
+ }
163
+
164
+ state.onMatch(match);
165
+ this.emit('match', match);
166
+
167
+ if (pattern.once) {
168
+ toRemove.push(i);
169
+ }
170
+ }
171
+ }
172
+
173
+ // Remove once-patterns in reverse order
174
+ for (let i = toRemove.length - 1; i >= 0; i--) {
175
+ state.patterns.splice(toRemove[i], 1);
176
+ }
177
+ }
178
+ }
package/src/index.ts CHANGED
@@ -100,3 +100,11 @@ export { sanitizeInput, detectInjection, securityHeaders, corsMiddleware, APIKey
100
100
  export type { SecurityHeadersConfig, CORSConfig, APIKeyEntry } from './core/security';
101
101
  export { createLoggingPlugin, createAnalyticsPlugin, createRateLimitPlugin } from './plugins';
102
102
  export type { PluginManifest } from './plugins';
103
+
104
+ // v1.1.0 modules
105
+ export { FeishuChannel } from './channels/feishu';
106
+ export type { FeishuChannelConfig } from './channels/feishu';
107
+ export { DiscordChannel } from './channels/discord';
108
+ export type { DiscordChannelConfig } from './channels/discord';
109
+ export { ProcessWatcher } from './core/watch';
110
+ export type { WatchPattern, WatchMatch, WatchOptions } from './core/watch';