opc-agent 0.7.0 → 0.9.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 (69) 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/wechat.d.ts +62 -0
  6. package/dist/channels/wechat.js +104 -0
  7. package/dist/cli.js +45 -17
  8. package/dist/core/analytics-engine.d.ts +51 -0
  9. package/dist/core/analytics-engine.js +186 -0
  10. package/dist/core/cache.d.ts +47 -0
  11. package/dist/core/cache.js +156 -0
  12. package/dist/core/compose.d.ts +35 -0
  13. package/dist/core/compose.js +49 -0
  14. package/dist/core/orchestrator.d.ts +68 -0
  15. package/dist/core/orchestrator.js +145 -0
  16. package/dist/core/rate-limiter.d.ts +47 -0
  17. package/dist/core/rate-limiter.js +92 -0
  18. package/dist/i18n/index.d.ts +6 -1
  19. package/dist/i18n/index.js +86 -0
  20. package/dist/index.d.ts +24 -0
  21. package/dist/index.js +39 -1
  22. package/dist/templates/data-analyst.d.ts +53 -0
  23. package/dist/templates/data-analyst.js +70 -0
  24. package/dist/templates/teacher.d.ts +58 -0
  25. package/dist/templates/teacher.js +78 -0
  26. package/dist/testing/index.d.ts +37 -0
  27. package/dist/testing/index.js +176 -0
  28. package/dist/tools/calculator.d.ts +7 -0
  29. package/dist/tools/calculator.js +70 -0
  30. package/dist/tools/datetime.d.ts +7 -0
  31. package/dist/tools/datetime.js +159 -0
  32. package/dist/tools/json-transform.d.ts +7 -0
  33. package/dist/tools/json-transform.js +184 -0
  34. package/dist/tools/text-analysis.d.ts +8 -0
  35. package/dist/tools/text-analysis.js +113 -0
  36. package/docs/.vitepress/config.ts +92 -0
  37. package/docs/api/cli.md +48 -0
  38. package/docs/api/sdk.md +80 -0
  39. package/docs/guide/configuration.md +79 -0
  40. package/docs/guide/deployment.md +42 -0
  41. package/docs/guide/testing.md +84 -0
  42. package/docs/index.md +27 -0
  43. package/docs/zh/api/oad-schema.md +3 -0
  44. package/docs/zh/guide/concepts.md +28 -0
  45. package/docs/zh/guide/configuration.md +39 -0
  46. package/docs/zh/guide/deployment.md +3 -0
  47. package/docs/zh/guide/getting-started.md +58 -0
  48. package/docs/zh/guide/templates.md +22 -0
  49. package/docs/zh/guide/testing.md +18 -0
  50. package/docs/zh/index.md +27 -0
  51. package/package.json +7 -3
  52. package/src/channels/email.ts +177 -0
  53. package/src/channels/slack.ts +160 -0
  54. package/src/channels/wechat.ts +149 -0
  55. package/src/cli.ts +45 -19
  56. package/src/core/analytics-engine.ts +186 -0
  57. package/src/core/cache.ts +141 -0
  58. package/src/core/compose.ts +77 -0
  59. package/src/core/orchestrator.ts +215 -0
  60. package/src/core/rate-limiter.ts +128 -0
  61. package/src/i18n/index.ts +87 -1
  62. package/src/index.ts +28 -0
  63. package/src/templates/data-analyst.ts +70 -0
  64. package/src/templates/teacher.ts +79 -0
  65. package/src/testing/index.ts +181 -0
  66. package/src/tools/calculator.ts +73 -0
  67. package/src/tools/datetime.ts +149 -0
  68. package/src/tools/json-transform.ts +187 -0
  69. package/src/tools/text-analysis.ts +116 -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
@@ -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
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WeChatChannel = void 0;
4
+ const index_1 = require("./index");
5
+ class WeChatChannel extends index_1.BaseChannel {
6
+ type = 'wechat';
7
+ config;
8
+ accessToken = null;
9
+ tokenExpiry = 0;
10
+ constructor(config) {
11
+ super();
12
+ this.config = config;
13
+ }
14
+ async start() {
15
+ // TODO: Start HTTP server to receive WeChat push messages
16
+ // 1. Verify signature on GET requests
17
+ // 2. Parse XML messages on POST requests
18
+ // 3. Route to handler and reply with XML
19
+ }
20
+ async stop() {
21
+ // TODO: Stop HTTP server
22
+ }
23
+ /** Get or refresh access token */
24
+ async getAccessToken() {
25
+ if (this.accessToken && Date.now() < this.tokenExpiry) {
26
+ return this.accessToken;
27
+ }
28
+ // TODO: Implement token refresh
29
+ // const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.appId}&secret=${this.config.appSecret}`;
30
+ // const res = await fetch(url);
31
+ // const data = await res.json();
32
+ // this.accessToken = data.access_token;
33
+ // this.tokenExpiry = Date.now() + (data.expires_in - 300) * 1000;
34
+ return this.accessToken ?? '';
35
+ }
36
+ /** Handle incoming WeChat message */
37
+ async handleMessage(wxMsg) {
38
+ if (wxMsg.msgType === 'event') {
39
+ return this.handleEvent(wxMsg);
40
+ }
41
+ const message = this.wechatToMessage(wxMsg);
42
+ if (this.handler) {
43
+ const reply = await this.handler(message);
44
+ return reply.content;
45
+ }
46
+ return '';
47
+ }
48
+ /** Handle WeChat events (subscribe, scan, etc.) */
49
+ handleEvent(wxMsg) {
50
+ switch (wxMsg.event) {
51
+ case 'subscribe':
52
+ return 'Welcome! How can I help you?';
53
+ case 'SCAN':
54
+ return `QR code scanned: ${wxMsg.eventKey}`;
55
+ default:
56
+ return '';
57
+ }
58
+ }
59
+ /** Convert WeChat message to internal Message */
60
+ wechatToMessage(wxMsg) {
61
+ return {
62
+ id: wxMsg.msgId ?? `wx-${wxMsg.createTime}`,
63
+ role: 'user',
64
+ content: wxMsg.content ?? '',
65
+ timestamp: wxMsg.createTime * 1000,
66
+ metadata: {
67
+ channel: 'wechat',
68
+ fromUser: wxMsg.fromUserName,
69
+ toUser: wxMsg.toUserName,
70
+ msgType: wxMsg.msgType,
71
+ },
72
+ };
73
+ }
74
+ /** Send template message */
75
+ async sendTemplateMessage(data) {
76
+ // TODO: Implement
77
+ // const token = await this.getAccessToken();
78
+ // const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;
79
+ // const res = await fetch(url, {
80
+ // method: 'POST',
81
+ // body: JSON.stringify({
82
+ // touser: data.toUser,
83
+ // template_id: data.templateId,
84
+ // url: data.url,
85
+ // data: data.data,
86
+ // }),
87
+ // });
88
+ void data;
89
+ return true;
90
+ }
91
+ /** Generate QR code for login (stub) */
92
+ async generateLoginQR() {
93
+ // TODO: Implement with WeChat QR code API
94
+ // const token = await this.getAccessToken();
95
+ // POST to https://api.weixin.qq.com/cgi-bin/qrcode/create
96
+ return {
97
+ ticket: 'stub-ticket',
98
+ url: 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=stub-ticket',
99
+ expireSeconds: 300,
100
+ };
101
+ }
102
+ }
103
+ exports.WeChatChannel = WeChatChannel;
104
+ //# sourceMappingURL=wechat.js.map
package/dist/cli.js CHANGED
@@ -50,7 +50,11 @@ const content_writer_1 = require("./templates/content-writer");
50
50
  const legal_assistant_1 = require("./templates/legal-assistant");
51
51
  const financial_advisor_1 = require("./templates/financial-advisor");
52
52
  const executive_assistant_1 = require("./templates/executive-assistant");
53
+ const data_analyst_1 = require("./templates/data-analyst");
54
+ const teacher_1 = require("./templates/teacher");
53
55
  const analytics_1 = require("./analytics");
56
+ const analytics_engine_1 = require("./core/analytics-engine");
57
+ const testing_1 = require("./testing");
54
58
  const openclaw_1 = require("./deploy/openclaw");
55
59
  const hermes_1 = require("./deploy/hermes");
56
60
  const workflow_1 = require("./core/workflow");
@@ -90,6 +94,8 @@ const TEMPLATES = {
90
94
  'legal-assistant': { label: 'Legal Assistant - contract review + compliance + legal research', factory: legal_assistant_1.createLegalAssistantConfig },
91
95
  'financial-advisor': { label: 'Financial Advisor - budget analysis + expense tracking + planning', factory: financial_advisor_1.createFinancialAdvisorConfig },
92
96
  'executive-assistant': { label: 'Executive Assistant - calendar + email drafting + meeting prep', factory: executive_assistant_1.createExecutiveAssistantConfig },
97
+ 'data-analyst': { label: 'Data Analyst - data querying + visualization + insights', factory: data_analyst_1.createDataAnalystConfig },
98
+ 'teacher': { label: 'Teacher - lesson planning + quizzes + concept explanation', factory: teacher_1.createTeacherConfig },
93
99
  };
94
100
  async function promptUser(question, defaultValue) {
95
101
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -113,7 +119,7 @@ async function select(question, options) {
113
119
  program
114
120
  .name('opc')
115
121
  .description('OPC Agent - Open Agent Framework for business workstations')
116
- .version('0.6.0');
122
+ .version('0.9.0');
117
123
  // ── Init command ─────────────────────────────────────────────
118
124
  program
119
125
  .command('init')
@@ -396,25 +402,47 @@ program
396
402
  // ── Test command ─────────────────────────────────────────────
397
403
  program
398
404
  .command('test')
399
- .description('Run agent in sandbox mode')
405
+ .description('Run agent tests defined in OAD or tests.yaml')
400
406
  .option('-f, --file <file>', 'OAD file', 'oad.yaml')
407
+ .option('--json', 'Output as JSON')
401
408
  .action(async (opts) => {
402
409
  loadDotEnv();
403
- console.log(`\n${icon.gear} Running agent in sandbox mode...`);
404
- const runtime = new runtime_1.AgentRuntime();
405
- await runtime.loadConfig(opts.file);
406
- const agent = await runtime.initialize();
407
- console.log(`${icon.success} Agent "${color.bold(agent.name)}" initialized in sandbox.`);
408
- console.log(` State: ${agent.state}`);
409
- console.log(` Sending test message...`);
410
- const response = await agent.handleMessage({
411
- id: 'test_1',
412
- role: 'user',
413
- content: 'Hello! What can you help me with?',
414
- timestamp: Date.now(),
415
- });
416
- console.log(` Response: ${response.content.slice(0, 200)}`);
417
- console.log(`${icon.success} Sandbox test passed.\n`);
410
+ console.log(`\n${icon.gear} Running agent tests...\n`);
411
+ try {
412
+ const report = await (0, testing_1.runTests)(opts.file);
413
+ if (opts.json) {
414
+ console.log(JSON.stringify(report, null, 2));
415
+ }
416
+ else {
417
+ console.log((0, testing_1.formatReport)(report));
418
+ }
419
+ process.exit(report.failed > 0 ? 1 : 0);
420
+ }
421
+ catch (err) {
422
+ console.error(`${icon.error} Test failed:`, err instanceof Error ? err.message : err);
423
+ process.exit(1);
424
+ }
425
+ });
426
+ // ── Analytics command ────────────────────────────────────────
427
+ program
428
+ .command('analytics')
429
+ .description('Show agent analytics and usage stats')
430
+ .option('--json', 'Output as JSON')
431
+ .option('--clear', 'Clear analytics data')
432
+ .action(async (opts) => {
433
+ const engine = new analytics_engine_1.AnalyticsEngine('.');
434
+ if (opts.clear) {
435
+ engine.clear();
436
+ console.log(`${icon.success} Analytics data cleared.`);
437
+ return;
438
+ }
439
+ const stats = engine.getStats();
440
+ if (opts.json) {
441
+ console.log(JSON.stringify(stats, null, 2));
442
+ }
443
+ else {
444
+ console.log(analytics_engine_1.AnalyticsEngine.formatStats(stats));
445
+ }
418
446
  });
419
447
  // ── Dev command ──────────────────────────────────────────────
420
448
  program
@@ -0,0 +1,51 @@
1
+ export interface AnalyticsEvent {
2
+ type: 'message' | 'llm_call' | 'tool_use' | 'error';
3
+ timestamp: number;
4
+ data: Record<string, any>;
5
+ }
6
+ export interface AnalyticsStats {
7
+ totalMessages: number;
8
+ totalLLMCalls: number;
9
+ totalToolUses: number;
10
+ totalErrors: number;
11
+ avgResponseTimeMs: number;
12
+ totalTokens: {
13
+ input: number;
14
+ output: number;
15
+ total: number;
16
+ };
17
+ topSkills: {
18
+ name: string;
19
+ count: number;
20
+ }[];
21
+ topErrors: {
22
+ message: string;
23
+ count: number;
24
+ }[];
25
+ messagesPerDay: Record<string, number>;
26
+ period: {
27
+ from: number;
28
+ to: number;
29
+ };
30
+ }
31
+ export declare class AnalyticsEngine {
32
+ private dataDir;
33
+ private eventsFile;
34
+ private events;
35
+ constructor(dataDir?: string);
36
+ private load;
37
+ private save;
38
+ track(type: AnalyticsEvent['type'], data: Record<string, any>): void;
39
+ trackMessage(userId: string, responseTimeMs: number, tokensIn: number, tokensOut: number): void;
40
+ trackLLMCall(provider: string, model: string, tokensIn: number, tokensOut: number, latencyMs: number): void;
41
+ trackToolUse(toolName: string, success: boolean, latencyMs: number): void;
42
+ trackError(error: string, context?: string): void;
43
+ getStats(fromTs?: number, toTs?: number): AnalyticsStats;
44
+ getRecentEvents(limit?: number): AnalyticsEvent[];
45
+ clear(): void;
46
+ /**
47
+ * Format stats for CLI display.
48
+ */
49
+ static formatStats(stats: AnalyticsStats): string;
50
+ }
51
+ //# sourceMappingURL=analytics-engine.d.ts.map