opc-agent 0.9.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 +7 -0
- package/README.md +145 -144
- package/dist/channels/discord.d.ts +44 -0
- package/dist/channels/discord.js +189 -0
- package/dist/channels/feishu.d.ts +47 -0
- package/dist/channels/feishu.js +221 -0
- package/dist/channels/web.js +118 -39
- package/dist/cli.js +109 -1
- package/dist/core/errors.d.ts +68 -0
- package/dist/core/errors.js +149 -0
- package/dist/core/security.d.ts +48 -0
- package/dist/core/security.js +146 -0
- package/dist/core/watch.d.ts +73 -0
- package/dist/core/watch.js +106 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +32 -1
- package/dist/plugins/index.d.ts +24 -3
- package/dist/plugins/index.js +109 -4
- package/dist/schema/oad.d.ts +54 -0
- package/dist/schema/oad.js +6 -1
- package/package.json +1 -1
- package/src/channels/discord.ts +192 -0
- package/src/channels/feishu.ts +236 -0
- package/src/channels/web.ts +118 -39
- package/src/cli.ts +108 -1
- package/src/core/errors.ts +148 -0
- package/src/core/security.ts +171 -0
- package/src/core/watch.ts +178 -0
- package/src/index.ts +15 -0
- package/src/plugins/index.ts +128 -7
- package/src/schema/oad.ts +6 -0
- package/tests/errors.test.ts +83 -0
- package/tests/security.test.ts +60 -0
|
@@ -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
|
+
}
|
package/src/channels/web.ts
CHANGED
|
@@ -62,52 +62,127 @@ const CHAT_HTML = `<!DOCTYPE html>
|
|
|
62
62
|
<html lang="en">
|
|
63
63
|
<head>
|
|
64
64
|
<meta charset="UTF-8">
|
|
65
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
65
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
|
66
66
|
<title>OPC Agent</title>
|
|
67
67
|
<style>
|
|
68
|
+
:root{--bg:#0a0a0f;--surface:#12121a;--border:#1e1e2e;--text:#e0e0e0;--text-dim:#888;--accent:#818cf8;--accent-hover:#6366f1;--user-bg:#2563eb;--user-hover:#1d4ed8;--error-bg:#7f1d1d;--error-text:#fca5a5;--success:#22c55e;--radius:12px}
|
|
68
69
|
*{margin:0;padding:0;box-sizing:border-box}
|
|
69
|
-
body{background
|
|
70
|
-
header{background
|
|
71
|
-
header
|
|
72
|
-
header .
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
.
|
|
76
|
-
.
|
|
77
|
-
.
|
|
78
|
-
.
|
|
70
|
+
body{background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',sans-serif;height:100vh;height:100dvh;display:flex;flex-direction:column;overflow:hidden}
|
|
71
|
+
header{background:var(--surface);padding:14px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;flex-shrink:0;backdrop-filter:blur(12px)}
|
|
72
|
+
header .avatar{width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,var(--accent),#6366f1);display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
|
|
73
|
+
header .info{flex:1;min-width:0}
|
|
74
|
+
header h1{font-size:16px;font-weight:600;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
75
|
+
header .status{font-size:12px;color:var(--success);display:flex;align-items:center;gap:4px}
|
|
76
|
+
header .status .dot{width:6px;height:6px;border-radius:50%;background:var(--success);animation:pulse 2s infinite}
|
|
77
|
+
nav.header-nav{display:flex;gap:4px}
|
|
78
|
+
nav.header-nav a{color:var(--text-dim);text-decoration:none;font-size:12px;padding:4px 10px;border-radius:6px;transition:all .2s}
|
|
79
|
+
nav.header-nav a:hover{color:#fff;background:rgba(255,255,255,.06)}
|
|
80
|
+
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
|
|
81
|
+
@keyframes fadeIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
|
|
82
|
+
@keyframes slideIn{from{opacity:0;transform:scale(.96)}to{opacity:1;transform:scale(1)}}
|
|
83
|
+
#messages{flex:1;overflow-y:auto;padding:20px;display:flex;flex-direction:column;gap:12px;scroll-behavior:smooth}
|
|
84
|
+
#messages::-webkit-scrollbar{width:4px}
|
|
85
|
+
#messages::-webkit-scrollbar-track{background:transparent}
|
|
86
|
+
#messages::-webkit-scrollbar-thumb{background:var(--border);border-radius:4px}
|
|
87
|
+
.msg-wrap{display:flex;flex-direction:column;animation:fadeIn .3s ease-out}
|
|
88
|
+
.msg-wrap.user{align-items:flex-end}
|
|
89
|
+
.msg-wrap.assistant{align-items:flex-start}
|
|
90
|
+
.msg{max-width:min(720px,85%);padding:10px 14px;border-radius:var(--radius);line-height:1.7;font-size:14px;word-break:break-word;position:relative;transition:all .2s}
|
|
91
|
+
.msg.user{background:var(--user-bg);color:#fff;border-bottom-right-radius:4px}
|
|
92
|
+
.msg.assistant{background:var(--surface);color:var(--text);border:1px solid var(--border);border-bottom-left-radius:4px}
|
|
93
|
+
.msg.error{background:var(--error-bg);color:var(--error-text);border:1px solid rgba(239,68,68,.3)}
|
|
94
|
+
.msg pre{background:rgba(0,0,0,.4);padding:12px;border-radius:8px;overflow-x:auto;margin:8px 0;font-size:13px;font-family:'JetBrains Mono','Fira Code','Cascadia Code',monospace;line-height:1.5}
|
|
95
|
+
.msg code{font-family:'JetBrains Mono','Fira Code','Cascadia Code',monospace;font-size:13px;background:rgba(0,0,0,.3);padding:1px 5px;border-radius:4px}
|
|
96
|
+
.msg pre code{background:none;padding:0}
|
|
97
|
+
.msg .cursor{display:inline-block;width:2px;height:14px;background:var(--accent);animation:blink .6s infinite;vertical-align:text-bottom;margin-left:2px}
|
|
79
98
|
@keyframes blink{0%,100%{opacity:1}50%{opacity:0}}
|
|
80
|
-
.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
99
|
+
.typing{display:flex;gap:4px;padding:12px 16px;align-items:center}
|
|
100
|
+
.typing span{width:6px;height:6px;border-radius:50%;background:var(--text-dim);animation:typingDot 1.4s infinite}
|
|
101
|
+
.typing span:nth-child(2){animation-delay:.2s}
|
|
102
|
+
.typing span:nth-child(3){animation-delay:.4s}
|
|
103
|
+
@keyframes typingDot{0%,60%,100%{opacity:.3;transform:scale(.8)}30%{opacity:1;transform:scale(1)}}
|
|
104
|
+
.reactions{display:flex;gap:4px;margin-top:4px}
|
|
105
|
+
.reactions button{background:rgba(255,255,255,.06);border:1px solid transparent;border-radius:16px;padding:2px 8px;font-size:13px;cursor:pointer;transition:all .15s;color:var(--text-dim)}
|
|
106
|
+
.reactions button:hover{background:rgba(255,255,255,.12);border-color:var(--border)}
|
|
107
|
+
.reactions button.active{background:rgba(99,102,241,.2);border-color:var(--accent);color:var(--accent)}
|
|
108
|
+
.msg-time{font-size:11px;color:var(--text-dim);margin-top:2px;opacity:0;transition:opacity .2s}
|
|
109
|
+
.msg-wrap:hover .msg-time{opacity:1}
|
|
110
|
+
.attachment{display:flex;align-items:center;gap:8px;background:rgba(0,0,0,.3);padding:8px 12px;border-radius:8px;margin-top:6px;font-size:13px}
|
|
111
|
+
.attachment .icon{font-size:18px}
|
|
112
|
+
#input-area{background:var(--surface);padding:12px 20px 16px;border-top:1px solid var(--border);display:flex;gap:10px;align-items:flex-end;flex-shrink:0}
|
|
113
|
+
#input{flex:1;background:var(--bg);border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px;color:#fff;font-size:14px;outline:none;resize:none;max-height:150px;min-height:42px;font-family:inherit;line-height:1.5;transition:border-color .2s}
|
|
114
|
+
#input:focus{border-color:var(--accent)}
|
|
115
|
+
#input::placeholder{color:var(--text-dim)}
|
|
116
|
+
#send{background:var(--user-bg);color:#fff;border:none;border-radius:var(--radius);width:42px;height:42px;font-size:18px;cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center;flex-shrink:0}
|
|
117
|
+
#send:hover{background:var(--user-hover);transform:scale(1.05)}
|
|
118
|
+
#send:disabled{background:#334155;cursor:not-allowed;transform:none}
|
|
119
|
+
.empty-state{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;color:var(--text-dim);gap:12px;padding:40px;text-align:center}
|
|
120
|
+
.empty-state .logo{font-size:48px;opacity:.6}
|
|
121
|
+
.empty-state h2{color:var(--text);font-size:20px;font-weight:500}
|
|
122
|
+
.empty-state p{font-size:14px;max-width:400px;line-height:1.6}
|
|
123
|
+
@media(max-width:640px){
|
|
124
|
+
header{padding:10px 14px}
|
|
125
|
+
#messages{padding:12px}
|
|
126
|
+
#input-area{padding:10px 14px 14px}
|
|
127
|
+
.msg{max-width:90%;font-size:14px}
|
|
128
|
+
nav.header-nav{display:none}
|
|
129
|
+
}
|
|
87
130
|
</style>
|
|
88
131
|
</head>
|
|
89
132
|
<body>
|
|
90
|
-
<header
|
|
91
|
-
<div id="
|
|
133
|
+
<header>
|
|
134
|
+
<div class="avatar" id="avatar">🤖</div>
|
|
135
|
+
<div class="info"><h1 id="title">OPC Agent</h1><div class="status"><span class="dot"></span>Online</div></div>
|
|
136
|
+
<nav class="header-nav"><a href="/dashboard">Dashboard</a><a href="/templates">Templates</a></nav>
|
|
137
|
+
</header>
|
|
138
|
+
<div id="messages">
|
|
139
|
+
<div class="empty-state" id="empty"><div class="logo">💬</div><h2>Start a conversation</h2><p>Type a message below to chat with your AI agent.</p></div>
|
|
140
|
+
</div>
|
|
92
141
|
<div id="input-area">
|
|
93
|
-
<textarea id="input" rows="1" placeholder="Type a message
|
|
94
|
-
<button id="send"
|
|
142
|
+
<textarea id="input" rows="1" placeholder="Type a message…" autocomplete="off"></textarea>
|
|
143
|
+
<button id="send" aria-label="Send">↑</button>
|
|
95
144
|
</div>
|
|
96
145
|
<script>
|
|
97
|
-
const msgs=document.getElementById('messages'),input=document.getElementById('input'),btn=document.getElementById('send');
|
|
146
|
+
const msgs=document.getElementById('messages'),input=document.getElementById('input'),btn=document.getElementById('send'),empty=document.getElementById('empty');
|
|
98
147
|
let sessionId=crypto.randomUUID(),sending=false;
|
|
99
148
|
|
|
100
|
-
function
|
|
149
|
+
function esc(s){const d=document.createElement('div');d.textContent=s;return d.innerHTML}
|
|
150
|
+
function fmtTime(){return new Date().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})}
|
|
151
|
+
function renderMd(text){
|
|
152
|
+
let h=esc(text);
|
|
153
|
+
h=h.replace(/\`\`\`(\\w*)\\n([\\s\\S]*?)\`\`\`/g,'<pre><code>$2</code></pre>');
|
|
154
|
+
h=h.replace(/\`([^\`]+)\`/g,'<code>$1</code>');
|
|
155
|
+
h=h.replace(/\\*\\*(.+?)\\*\\*/g,'<strong>$1</strong>');
|
|
156
|
+
h=h.replace(/\\n/g,'<br>');
|
|
157
|
+
return h;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function addMsg(role,text,opts){
|
|
161
|
+
if(empty)empty.remove();
|
|
162
|
+
const wrap=document.createElement('div');
|
|
163
|
+
wrap.className='msg-wrap '+role;
|
|
101
164
|
const d=document.createElement('div');
|
|
102
165
|
d.className='msg '+role;
|
|
103
|
-
d.textContent=text;
|
|
104
|
-
|
|
166
|
+
if(opts?.html)d.innerHTML=text;else if(role==='assistant'&&text)d.innerHTML=renderMd(text);else d.textContent=text;
|
|
167
|
+
wrap.appendChild(d);
|
|
168
|
+
const time=document.createElement('div');
|
|
169
|
+
time.className='msg-time';
|
|
170
|
+
time.textContent=fmtTime();
|
|
171
|
+
wrap.appendChild(time);
|
|
172
|
+
if(role==='assistant'&&text){
|
|
173
|
+
const rx=document.createElement('div');rx.className='reactions';
|
|
174
|
+
rx.innerHTML='<button data-r="👍" onclick="react(this)">👍</button><button data-r="👎" onclick="react(this)">👎</button>';
|
|
175
|
+
wrap.appendChild(rx);
|
|
176
|
+
}
|
|
177
|
+
msgs.appendChild(wrap);
|
|
105
178
|
msgs.scrollTop=msgs.scrollHeight;
|
|
106
179
|
return d;
|
|
107
180
|
}
|
|
108
181
|
|
|
182
|
+
window.react=function(el){el.classList.toggle('active')};
|
|
183
|
+
|
|
109
184
|
input.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send()}});
|
|
110
|
-
input.addEventListener('input',()=>{input.style.height='auto';input.style.height=Math.min(input.scrollHeight,
|
|
185
|
+
input.addEventListener('input',()=>{input.style.height='auto';input.style.height=Math.min(input.scrollHeight,150)+'px'});
|
|
111
186
|
btn.addEventListener('click',send);
|
|
112
187
|
|
|
113
188
|
async function send(){
|
|
@@ -116,8 +191,13 @@ async function send(){
|
|
|
116
191
|
sending=true;btn.disabled=true;
|
|
117
192
|
input.value='';input.style.height='auto';
|
|
118
193
|
addMsg('user',text);
|
|
119
|
-
const
|
|
120
|
-
|
|
194
|
+
const wrap=document.createElement('div');wrap.className='msg-wrap assistant';
|
|
195
|
+
const d=document.createElement('div');d.className='msg assistant';
|
|
196
|
+
d.innerHTML='<div class="typing"><span></span><span></span><span></span></div>';
|
|
197
|
+
wrap.appendChild(d);
|
|
198
|
+
const time=document.createElement('div');time.className='msg-time';time.textContent=fmtTime();
|
|
199
|
+
wrap.appendChild(time);
|
|
200
|
+
msgs.appendChild(wrap);msgs.scrollTop=msgs.scrollHeight;
|
|
121
201
|
try{
|
|
122
202
|
const res=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({message:text,sessionId})});
|
|
123
203
|
if(!res.ok)throw new Error('HTTP '+res.status);
|
|
@@ -130,21 +210,20 @@ async function send(){
|
|
|
130
210
|
const lines=chunk.split('\\n');
|
|
131
211
|
for(const line of lines){
|
|
132
212
|
if(!line.startsWith('data: '))continue;
|
|
133
|
-
const
|
|
134
|
-
if(
|
|
135
|
-
try{const j=JSON.parse(d);if(j.content)full+=j.content;if(j.error)full='Error: '+j.error;}catch{}
|
|
213
|
+
const dd=line.slice(6);if(dd==='[DONE]')continue;
|
|
214
|
+
try{const j=JSON.parse(dd);if(j.content)full+=j.content;if(j.error)full='Error: '+j.error;}catch{}
|
|
136
215
|
}
|
|
137
|
-
|
|
216
|
+
d.innerHTML=renderMd(full)+'<span class="cursor"></span>';
|
|
138
217
|
msgs.scrollTop=msgs.scrollHeight;
|
|
139
218
|
}
|
|
140
|
-
if(!full)
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
219
|
+
if(!full){d.textContent='(empty response)';}else{d.innerHTML=renderMd(full);}
|
|
220
|
+
const rx=document.createElement('div');rx.className='reactions';
|
|
221
|
+
rx.innerHTML='<button data-r="👍" onclick="react(this)">👍</button><button data-r="👎" onclick="react(this)">👎</button>';
|
|
222
|
+
wrap.appendChild(rx);
|
|
223
|
+
}catch(e){d.className='msg error';d.textContent='Error: '+e.message;}
|
|
144
224
|
sending=false;btn.disabled=false;input.focus();
|
|
145
225
|
}
|
|
146
226
|
|
|
147
|
-
// Fetch agent info
|
|
148
227
|
fetch('/api/info').then(r=>r.json()).then(d=>{if(d.name)document.getElementById('title').textContent=d.name}).catch(()=>{});
|
|
149
228
|
</script>
|
|
150
229
|
</body>
|
|
@@ -379,7 +458,7 @@ export class WebChannel extends BaseChannel {
|
|
|
379
458
|
timestamp: Date.now(),
|
|
380
459
|
uptime: uptimeMs,
|
|
381
460
|
uptimeHuman: `${Math.floor(uptimeMs / 3600000)}h ${Math.floor((uptimeMs % 3600000) / 60000)}m`,
|
|
382
|
-
version: '0.
|
|
461
|
+
version: '1.0.0',
|
|
383
462
|
agent: this.agentName,
|
|
384
463
|
stats: {
|
|
385
464
|
sessions: this.stats.sessions,
|
package/src/cli.ts
CHANGED
|
@@ -29,6 +29,8 @@ import { createProvider } from './providers';
|
|
|
29
29
|
import { KnowledgeBase } from './core/knowledge';
|
|
30
30
|
import { publishAgent, installAgent } from './marketplace';
|
|
31
31
|
|
|
32
|
+
import { PluginManager, createLoggingPlugin, createAnalyticsPlugin, createRateLimitPlugin } from './plugins';
|
|
33
|
+
|
|
32
34
|
const program = new Command();
|
|
33
35
|
|
|
34
36
|
const color = {
|
|
@@ -92,7 +94,7 @@ async function select(question: string, options: { value: string; label: string
|
|
|
92
94
|
program
|
|
93
95
|
.name('opc')
|
|
94
96
|
.description('OPC Agent - Open Agent Framework for business workstations')
|
|
95
|
-
.version('0.
|
|
97
|
+
.version('1.0.0');
|
|
96
98
|
|
|
97
99
|
// ── Init command ─────────────────────────────────────────────
|
|
98
100
|
|
|
@@ -800,4 +802,109 @@ program
|
|
|
800
802
|
}
|
|
801
803
|
});
|
|
802
804
|
|
|
805
|
+
// 🔌 Plugin commands ────────────────────────────────────────
|
|
806
|
+
|
|
807
|
+
const pluginCmd = program.command('plugin').description('Manage plugins');
|
|
808
|
+
pluginCmd.command('list')
|
|
809
|
+
.description('List available built-in plugins')
|
|
810
|
+
.action(() => {
|
|
811
|
+
const builtIn = [
|
|
812
|
+
{ name: 'logging', description: 'Logs all messages and responses' },
|
|
813
|
+
{ name: 'analytics', description: 'Tracks message counts and error rates' },
|
|
814
|
+
{ name: 'rate-limit', description: 'Per-user rate limiting' },
|
|
815
|
+
];
|
|
816
|
+
console.log(`\n${icon.gear} ${color.bold('Available Plugins')}\n`);
|
|
817
|
+
for (const p of builtIn) {
|
|
818
|
+
console.log(` ${color.cyan(p.name.padEnd(16))} ${p.description}`);
|
|
819
|
+
}
|
|
820
|
+
console.log(`\n Add to oad.yaml: ${color.dim('plugins: [{ name: "logging" }]')}\n`);
|
|
821
|
+
});
|
|
822
|
+
|
|
823
|
+
pluginCmd.command('add')
|
|
824
|
+
.argument('<name>', 'Plugin name')
|
|
825
|
+
.option('-f, --file <file>', 'OAD file', 'oad.yaml')
|
|
826
|
+
.description('Add a plugin to your agent configuration')
|
|
827
|
+
.action((name: string, opts: { file: string }) => {
|
|
828
|
+
const validPlugins = ['logging', 'analytics', 'rate-limit'];
|
|
829
|
+
if (!validPlugins.includes(name)) {
|
|
830
|
+
console.error(`${icon.error} Unknown plugin: ${color.bold(name)}. Available: ${validPlugins.join(', ')}`);
|
|
831
|
+
process.exit(1);
|
|
832
|
+
}
|
|
833
|
+
try {
|
|
834
|
+
const raw = fs.readFileSync(opts.file, 'utf-8');
|
|
835
|
+
const config = yaml.load(raw) as any;
|
|
836
|
+
if (!config.spec.plugins) config.spec.plugins = [];
|
|
837
|
+
if (config.spec.plugins.some((p: any) => p.name === name)) {
|
|
838
|
+
console.log(`${icon.info} Plugin "${name}" already in config.`);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
config.spec.plugins.push({ name });
|
|
842
|
+
fs.writeFileSync(opts.file, yaml.dump(config, { lineWidth: 120 }));
|
|
843
|
+
console.log(`${icon.success} Added plugin "${color.cyan(name)}" to ${opts.file}`);
|
|
844
|
+
} catch (err) {
|
|
845
|
+
console.error(`${icon.error} Failed:`, err instanceof Error ? err.message : err);
|
|
846
|
+
process.exit(1);
|
|
847
|
+
}
|
|
848
|
+
});
|
|
849
|
+
|
|
850
|
+
// 🔄 Migrate command ────────────────────────────────────────
|
|
851
|
+
|
|
852
|
+
program
|
|
853
|
+
.command('migrate')
|
|
854
|
+
.description('Migrate OAD to latest schema version')
|
|
855
|
+
.option('-f, --file <file>', 'OAD file', 'oad.yaml')
|
|
856
|
+
.option('--dry-run', 'Show changes without writing')
|
|
857
|
+
.action(async (opts: { file: string; dryRun?: boolean }) => {
|
|
858
|
+
try {
|
|
859
|
+
const raw = fs.readFileSync(opts.file, 'utf-8');
|
|
860
|
+
const config = yaml.load(raw) as any;
|
|
861
|
+
let changed = false;
|
|
862
|
+
|
|
863
|
+
// Migration: add apiVersion if missing
|
|
864
|
+
if (!config.apiVersion) { config.apiVersion = 'opc/v1'; changed = true; }
|
|
865
|
+
// Migration: add kind if missing
|
|
866
|
+
if (!config.kind) { config.kind = 'Agent'; changed = true; }
|
|
867
|
+
// Migration: ensure metadata.version
|
|
868
|
+
if (!config.metadata?.version) {
|
|
869
|
+
if (!config.metadata) config.metadata = {};
|
|
870
|
+
config.metadata.version = '1.0.0';
|
|
871
|
+
changed = true;
|
|
872
|
+
}
|
|
873
|
+
// Migration: ensure spec.channels is array
|
|
874
|
+
if (config.spec?.channels && !Array.isArray(config.spec.channels)) {
|
|
875
|
+
config.spec.channels = [config.spec.channels];
|
|
876
|
+
changed = true;
|
|
877
|
+
}
|
|
878
|
+
// Migration: ensure spec.skills is array
|
|
879
|
+
if (config.spec?.skills && !Array.isArray(config.spec.skills)) {
|
|
880
|
+
config.spec.skills = [config.spec.skills];
|
|
881
|
+
changed = true;
|
|
882
|
+
}
|
|
883
|
+
// Migration: old model format
|
|
884
|
+
if (config.spec?.llm?.model && !config.spec?.model) {
|
|
885
|
+
config.spec.model = config.spec.llm.model;
|
|
886
|
+
delete config.spec.llm;
|
|
887
|
+
changed = true;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
if (!changed) {
|
|
891
|
+
console.log(`${icon.success} OAD is already up to date.`);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
if (opts.dryRun) {
|
|
896
|
+
console.log(`\n${icon.info} Would migrate:\n`);
|
|
897
|
+
console.log(yaml.dump(config, { lineWidth: 120 }));
|
|
898
|
+
} else {
|
|
899
|
+
// Backup
|
|
900
|
+
fs.writeFileSync(opts.file + '.bak', raw);
|
|
901
|
+
fs.writeFileSync(opts.file, yaml.dump(config, { lineWidth: 120 }));
|
|
902
|
+
console.log(`${icon.success} Migrated ${color.bold(opts.file)} (backup: ${opts.file}.bak)`);
|
|
903
|
+
}
|
|
904
|
+
} catch (err) {
|
|
905
|
+
console.error(`${icon.error} Migration failed:`, err instanceof Error ? err.message : err);
|
|
906
|
+
process.exit(1);
|
|
907
|
+
}
|
|
908
|
+
});
|
|
909
|
+
|
|
803
910
|
program.parse();
|