opc-agent 0.5.1 → 0.7.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.
@@ -0,0 +1,100 @@
1
+ import { BaseSkill } from './base';
2
+ import type { AgentContext, Message, SkillResult } from '../core/types';
3
+ import { KnowledgeBase } from '../core/knowledge';
4
+
5
+ export interface DocumentChunk {
6
+ content: string;
7
+ metadata: {
8
+ filename: string;
9
+ mimeType: string;
10
+ chunkIndex: number;
11
+ totalChunks: number;
12
+ };
13
+ }
14
+
15
+ export class DocumentSkill extends BaseSkill {
16
+ name = 'document';
17
+ description = 'Process uploaded documents (PDF, TXT, MD, DOCX). Chunks content and adds to knowledge base.';
18
+ private knowledgeBase: KnowledgeBase;
19
+
20
+ constructor(kbPath: string = '.') {
21
+ super();
22
+ this.knowledgeBase = new KnowledgeBase(kbPath);
23
+ }
24
+
25
+ async execute(context: AgentContext, message: Message): Promise<SkillResult> {
26
+ // Check if message has document attachment metadata
27
+ const meta = message.metadata;
28
+ if (!meta?.document) return this.noMatch();
29
+
30
+ const { content, filename, mimeType } = meta.document as {
31
+ content: string; filename: string; mimeType: string;
32
+ };
33
+
34
+ try {
35
+ const text = this.extractText(content, mimeType ?? this.guessMime(filename));
36
+ const chunks = this.chunk(text, 1000, 100);
37
+
38
+ const result = await this.knowledgeBase.addText(
39
+ chunks.map(c => c.content).join('\n\n---\n\n'),
40
+ filename
41
+ );
42
+
43
+ return this.match(
44
+ `📄 Processed "${filename}": ${chunks.length} chunks, ${text.length} chars → added to knowledge base (${result.chunks} KB entries)`
45
+ );
46
+ } catch (err) {
47
+ return this.match(`Document processing error: ${err instanceof Error ? err.message : String(err)}`);
48
+ }
49
+ }
50
+
51
+ extractText(content: string, mimeType: string): string {
52
+ // For plain text formats, content is already text
53
+ if (mimeType.includes('text/') || mimeType.includes('markdown')) {
54
+ return content;
55
+ }
56
+ // For other formats, assume base64-encoded or pre-extracted text
57
+ // In a real implementation, you'd use pdf-parse, mammoth, etc.
58
+ return content;
59
+ }
60
+
61
+ chunk(text: string, size: number = 1000, overlap: number = 100): DocumentChunk[] {
62
+ const chunks: DocumentChunk[] = [];
63
+ let start = 0;
64
+ while (start < text.length) {
65
+ const end = Math.min(start + size, text.length);
66
+ chunks.push({
67
+ content: text.slice(start, end),
68
+ metadata: {
69
+ filename: '',
70
+ mimeType: '',
71
+ chunkIndex: chunks.length,
72
+ totalChunks: 0, // filled after
73
+ },
74
+ });
75
+ start = end - overlap;
76
+ if (start >= text.length) break;
77
+ }
78
+ // Fill totalChunks
79
+ for (const c of chunks) c.metadata.totalChunks = chunks.length;
80
+ return chunks;
81
+ }
82
+
83
+ private guessMime(filename: string): string {
84
+ const ext = filename.split('.').pop()?.toLowerCase();
85
+ switch (ext) {
86
+ case 'pdf': return 'application/pdf';
87
+ case 'txt': return 'text/plain';
88
+ case 'md': return 'text/markdown';
89
+ case 'docx': return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
90
+ default: return 'text/plain';
91
+ }
92
+ }
93
+
94
+ /** Process raw text content directly (for API uploads) */
95
+ async processText(content: string, filename: string): Promise<{ chunks: number; chars: number }> {
96
+ const chunks = this.chunk(content);
97
+ const result = await this.knowledgeBase.addText(content, filename);
98
+ return { chunks: chunks.length, chars: content.length };
99
+ }
100
+ }
@@ -0,0 +1,35 @@
1
+ import { BaseSkill } from './base';
2
+ import type { AgentContext, Message, SkillResult } from '../core/types';
3
+
4
+ export class HttpSkill extends BaseSkill {
5
+ name = 'http';
6
+ description = 'Make HTTP requests to external APIs. Usage: http GET|POST|PUT|DELETE <url> [body]';
7
+
8
+ async execute(context: AgentContext, message: Message): Promise<SkillResult> {
9
+ const text = message.content.trim();
10
+ const match = text.match(/^http\s+(GET|POST|PUT|PATCH|DELETE)\s+(\S+)(?:\s+(.+))?$/is);
11
+ if (!match) return this.noMatch();
12
+
13
+ const [, method, url, bodyStr] = match;
14
+
15
+ try {
16
+ const opts: RequestInit = {
17
+ method: method.toUpperCase(),
18
+ headers: { 'Content-Type': 'application/json', 'User-Agent': 'OPC-Agent/0.7.0' },
19
+ };
20
+
21
+ if (bodyStr && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
22
+ opts.body = bodyStr;
23
+ }
24
+
25
+ const res = await fetch(url, opts);
26
+ const contentType = res.headers.get('content-type') ?? '';
27
+ const body = contentType.includes('json') ? JSON.stringify(await res.json(), null, 2) : await res.text();
28
+
29
+ const truncated = body.length > 4000 ? body.slice(0, 4000) + '\n...[truncated]' : body;
30
+ return this.match(`HTTP ${res.status} ${res.statusText}\n\n${truncated}`);
31
+ } catch (err) {
32
+ return this.match(`HTTP Error: ${err instanceof Error ? err.message : String(err)}`);
33
+ }
34
+ }
35
+ }
@@ -0,0 +1,80 @@
1
+ import { BaseSkill } from './base';
2
+ import type { AgentContext, Message, SkillResult } from '../core/types';
3
+
4
+ export interface ScheduledTask {
5
+ id: string;
6
+ name: string;
7
+ cronExpr: string;
8
+ action: string;
9
+ enabled: boolean;
10
+ lastRun?: number;
11
+ nextRun?: number;
12
+ }
13
+
14
+ export class SchedulerSkill extends BaseSkill {
15
+ name = 'scheduler';
16
+ description = 'Schedule recurring tasks. Usage: schedule list | schedule add <name> <cron> <action> | schedule remove <id>';
17
+ private tasks: Map<string, ScheduledTask> = new Map();
18
+ private timers: Map<string, NodeJS.Timeout> = new Map();
19
+
20
+ async execute(context: AgentContext, message: Message): Promise<SkillResult> {
21
+ const text = message.content.trim();
22
+
23
+ if (/^schedule\s+list$/i.test(text)) {
24
+ if (this.tasks.size === 0) return this.match('No scheduled tasks.');
25
+ const lines = Array.from(this.tasks.values()).map(t =>
26
+ `• ${t.name} (${t.id}) — ${t.cronExpr} — ${t.enabled ? '✅' : '❌'} — Last: ${t.lastRun ? new Date(t.lastRun).toISOString() : 'never'}`
27
+ );
28
+ return this.match(`Scheduled tasks:\n${lines.join('\n')}`);
29
+ }
30
+
31
+ const addMatch = text.match(/^schedule\s+add\s+(\S+)\s+(".*?"|\S+)\s+(.+)$/i);
32
+ if (addMatch) {
33
+ const [, name, cronExpr, action] = addMatch;
34
+ const id = `task_${Date.now().toString(36)}`;
35
+ const task: ScheduledTask = {
36
+ id, name, cronExpr: cronExpr.replace(/"/g, ''), action, enabled: true,
37
+ };
38
+ this.tasks.set(id, task);
39
+ // Simple interval-based scheduling (parse cron for interval in minutes)
40
+ const intervalMs = this.parseCronToInterval(task.cronExpr);
41
+ if (intervalMs > 0) {
42
+ const timer = setInterval(() => {
43
+ task.lastRun = Date.now();
44
+ }, intervalMs);
45
+ this.timers.set(id, timer);
46
+ }
47
+ return this.match(`Task scheduled: ${name} (${id}) — ${task.cronExpr} → "${action}"`);
48
+ }
49
+
50
+ const rmMatch = text.match(/^schedule\s+remove\s+(\S+)$/i);
51
+ if (rmMatch) {
52
+ const id = rmMatch[1];
53
+ const timer = this.timers.get(id);
54
+ if (timer) clearInterval(timer);
55
+ this.timers.delete(id);
56
+ const removed = this.tasks.delete(id);
57
+ return this.match(removed ? `Task ${id} removed.` : `Task ${id} not found.`);
58
+ }
59
+
60
+ return this.noMatch();
61
+ }
62
+
63
+ private parseCronToInterval(expr: string): number {
64
+ // Simple: support "every Xm" or "every Xh" or basic intervals
65
+ const m = expr.match(/every\s+(\d+)\s*(m|min|h|hr|s|sec)/i);
66
+ if (m) {
67
+ const val = parseInt(m[1]);
68
+ const unit = m[2].toLowerCase();
69
+ if (unit.startsWith('h')) return val * 3600_000;
70
+ if (unit.startsWith('m')) return val * 60_000;
71
+ if (unit.startsWith('s')) return val * 1000;
72
+ }
73
+ return 0; // Unknown cron format, no auto-schedule
74
+ }
75
+
76
+ destroy(): void {
77
+ for (const timer of this.timers.values()) clearInterval(timer);
78
+ this.timers.clear();
79
+ }
80
+ }
@@ -0,0 +1,59 @@
1
+ import { BaseSkill } from './base';
2
+ import type { AgentContext, Message, SkillResult } from '../core/types';
3
+
4
+ export interface WebhookTarget {
5
+ name: string;
6
+ url: string;
7
+ method?: string;
8
+ headers?: Record<string, string>;
9
+ secret?: string;
10
+ }
11
+
12
+ export class WebhookTriggerSkill extends BaseSkill {
13
+ name = 'webhook-trigger';
14
+ description = 'Trigger external webhooks. Usage: webhook <name> [payload JSON]';
15
+ private targets: Map<string, WebhookTarget> = new Map();
16
+
17
+ registerTarget(target: WebhookTarget): void {
18
+ this.targets.set(target.name, target);
19
+ }
20
+
21
+ async execute(context: AgentContext, message: Message): Promise<SkillResult> {
22
+ const match = message.content.trim().match(/^webhook\s+(\S+)(?:\s+(.+))?$/is);
23
+ if (!match) return this.noMatch();
24
+
25
+ const [, name, payloadStr] = match;
26
+ const target = this.targets.get(name);
27
+ if (!target) {
28
+ const available = Array.from(this.targets.keys()).join(', ') || 'none';
29
+ return this.match(`Unknown webhook "${name}". Available: ${available}`);
30
+ }
31
+
32
+ try {
33
+ const headers: Record<string, string> = {
34
+ 'Content-Type': 'application/json',
35
+ 'User-Agent': 'OPC-Agent/0.7.0',
36
+ ...target.headers,
37
+ };
38
+ if (target.secret) {
39
+ headers['X-Webhook-Secret'] = target.secret;
40
+ }
41
+
42
+ const body = payloadStr ?? JSON.stringify({
43
+ agent: context.agentName,
44
+ timestamp: Date.now(),
45
+ trigger: 'manual',
46
+ });
47
+
48
+ const res = await fetch(target.url, {
49
+ method: target.method ?? 'POST',
50
+ headers,
51
+ body,
52
+ });
53
+
54
+ return this.match(`Webhook "${name}" triggered → ${res.status} ${res.statusText}`);
55
+ } catch (err) {
56
+ return this.match(`Webhook error: ${err instanceof Error ? err.message : String(err)}`);
57
+ }
58
+ }
59
+ }
@@ -0,0 +1,15 @@
1
+ FROM node:22-alpine AS base
2
+ WORKDIR /app
3
+
4
+ # Install dependencies
5
+ COPY package.json package-lock.json* ./
6
+ RUN npm ci --production 2>/dev/null || npm install --production
7
+
8
+ # Copy agent files
9
+ COPY oad.yaml ./
10
+ COPY .env* ./
11
+ COPY prompts/ ./prompts/ 2>/dev/null || true
12
+
13
+ EXPOSE 3000
14
+
15
+ CMD ["npx", "opc", "run"]
@@ -0,0 +1,21 @@
1
+ version: '3.8'
2
+
3
+ services:
4
+ agent:
5
+ build: .
6
+ ports:
7
+ - "3000:3000"
8
+ env_file:
9
+ - .env
10
+ volumes:
11
+ - ./oad.yaml:/app/oad.yaml:ro
12
+ - agent-data:/app/data
13
+ restart: unless-stopped
14
+ healthcheck:
15
+ test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/health"]
16
+ interval: 30s
17
+ timeout: 5s
18
+ retries: 3
19
+
20
+ volumes:
21
+ agent-data:
@@ -0,0 +1,76 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { createAuthMiddleware, getActiveSessions } from '../src/core/auth';
3
+ import { HttpSkill } from '../src/skills/http';
4
+ import { WebhookTriggerSkill } from '../src/skills/webhook-trigger';
5
+ import { SchedulerSkill } from '../src/skills/scheduler';
6
+ import type { AgentContext, Message } from '../src/core/types';
7
+
8
+ const mockContext: AgentContext = {
9
+ agentName: 'test',
10
+ sessionId: 'test-session',
11
+ messages: [],
12
+ memory: { get: async () => null, set: async () => {}, getConversation: async () => [], addMessage: async () => {}, clear: async () => {} },
13
+ metadata: {},
14
+ };
15
+
16
+ function msg(content: string): Message {
17
+ return { id: '1', role: 'user', content, timestamp: Date.now() };
18
+ }
19
+
20
+ describe('Auth', () => {
21
+ it('should create middleware', () => {
22
+ const mw = createAuthMiddleware({ apiKeys: ['test-key'] });
23
+ expect(typeof mw).toBe('function');
24
+ });
25
+
26
+ it('should track sessions', () => {
27
+ const sessions = getActiveSessions();
28
+ expect(Array.isArray(sessions)).toBe(true);
29
+ });
30
+ });
31
+
32
+ describe('HttpSkill', () => {
33
+ it('should not match non-http messages', async () => {
34
+ const skill = new HttpSkill();
35
+ const result = await skill.execute(mockContext, msg('hello'));
36
+ expect(result.handled).toBe(false);
37
+ });
38
+ });
39
+
40
+ describe('WebhookTriggerSkill', () => {
41
+ it('should report unknown webhook', async () => {
42
+ const skill = new WebhookTriggerSkill();
43
+ const result = await skill.execute(mockContext, msg('webhook test'));
44
+ expect(result.handled).toBe(true);
45
+ expect(result.response).toContain('Unknown webhook');
46
+ });
47
+
48
+ it('should register targets', () => {
49
+ const skill = new WebhookTriggerSkill();
50
+ skill.registerTarget({ name: 'slack', url: 'https://hooks.slack.com/test' });
51
+ expect(skill).toBeDefined();
52
+ });
53
+ });
54
+
55
+ describe('SchedulerSkill', () => {
56
+ it('should list empty tasks', async () => {
57
+ const skill = new SchedulerSkill();
58
+ const result = await skill.execute(mockContext, msg('schedule list'));
59
+ expect(result.handled).toBe(true);
60
+ expect(result.response).toContain('No scheduled tasks');
61
+ });
62
+
63
+ it('should add a task', async () => {
64
+ const skill = new SchedulerSkill();
65
+ const result = await skill.execute(mockContext, msg('schedule add backup "every 5m" run backup'));
66
+ expect(result.handled).toBe(true);
67
+ expect(result.response).toContain('Task scheduled');
68
+ skill.destroy();
69
+ });
70
+
71
+ it('should not match unrelated messages', async () => {
72
+ const skill = new SchedulerSkill();
73
+ const result = await skill.execute(mockContext, msg('hello'));
74
+ expect(result.handled).toBe(false);
75
+ });
76
+ });