opc-agent 0.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.
Files changed (67) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +179 -0
  3. package/README.zh-CN.md +126 -0
  4. package/dist/channels/index.d.ts +10 -0
  5. package/dist/channels/index.js +11 -0
  6. package/dist/channels/web.d.ts +12 -0
  7. package/dist/channels/web.js +81 -0
  8. package/dist/cli.d.ts +3 -0
  9. package/dist/cli.js +146 -0
  10. package/dist/core/agent.d.ts +28 -0
  11. package/dist/core/agent.js +100 -0
  12. package/dist/core/config.d.ts +4 -0
  13. package/dist/core/config.js +50 -0
  14. package/dist/core/runtime.d.ts +14 -0
  15. package/dist/core/runtime.js +54 -0
  16. package/dist/core/types.d.ts +58 -0
  17. package/dist/core/types.js +3 -0
  18. package/dist/dtv/data.d.ts +18 -0
  19. package/dist/dtv/data.js +25 -0
  20. package/dist/dtv/trust.d.ts +19 -0
  21. package/dist/dtv/trust.js +40 -0
  22. package/dist/dtv/value.d.ts +23 -0
  23. package/dist/dtv/value.js +38 -0
  24. package/dist/index.d.ts +16 -0
  25. package/dist/index.js +33 -0
  26. package/dist/memory/index.d.ts +11 -0
  27. package/dist/memory/index.js +33 -0
  28. package/dist/providers/index.d.ts +12 -0
  29. package/dist/providers/index.js +68 -0
  30. package/dist/schema/oad.d.ts +553 -0
  31. package/dist/schema/oad.js +61 -0
  32. package/dist/skills/base.d.ts +9 -0
  33. package/dist/skills/base.js +13 -0
  34. package/dist/skills/index.d.ts +10 -0
  35. package/dist/skills/index.js +25 -0
  36. package/dist/templates/customer-service.d.ts +56 -0
  37. package/dist/templates/customer-service.js +75 -0
  38. package/docs/api/oad-schema.md +64 -0
  39. package/docs/guide/concepts.md +51 -0
  40. package/docs/guide/getting-started.md +44 -0
  41. package/docs/guide/templates.md +28 -0
  42. package/package.json +37 -0
  43. package/src/channels/index.ts +15 -0
  44. package/src/channels/web.ts +85 -0
  45. package/src/cli.ts +131 -0
  46. package/src/core/agent.ts +116 -0
  47. package/src/core/config.ts +14 -0
  48. package/src/core/runtime.ts +57 -0
  49. package/src/core/types.ts +68 -0
  50. package/src/dtv/data.ts +29 -0
  51. package/src/dtv/trust.ts +43 -0
  52. package/src/dtv/value.ts +47 -0
  53. package/src/index.ts +16 -0
  54. package/src/memory/index.ts +34 -0
  55. package/src/providers/index.ts +44 -0
  56. package/src/schema/oad.ts +76 -0
  57. package/src/skills/base.ts +16 -0
  58. package/src/skills/index.ts +27 -0
  59. package/src/templates/customer-service.ts +80 -0
  60. package/templates/customer-service/README.md +22 -0
  61. package/templates/customer-service/oad.yaml +36 -0
  62. package/tests/agent.test.ts +72 -0
  63. package/tests/channel.test.ts +39 -0
  64. package/tests/oad.test.ts +68 -0
  65. package/tests/runtime.test.ts +42 -0
  66. package/tsconfig.json +19 -0
  67. package/vitest.config.ts +9 -0
@@ -0,0 +1,116 @@
1
+ import { EventEmitter } from 'events';
2
+ import type { AgentState, IAgent, IChannel, ISkill, Message, MemoryStore, AgentContext } from './types';
3
+ import { InMemoryStore } from '../memory';
4
+ import { createProvider, type LLMProvider } from '../providers';
5
+
6
+ export class BaseAgent extends EventEmitter implements IAgent {
7
+ readonly name: string;
8
+ private _state: AgentState = 'init';
9
+ private skills: Map<string, ISkill> = new Map();
10
+ private channels: IChannel[] = [];
11
+ private memory: MemoryStore;
12
+ private provider: LLMProvider;
13
+ private systemPrompt: string;
14
+
15
+ constructor(options: {
16
+ name: string;
17
+ systemPrompt?: string;
18
+ provider?: string;
19
+ model?: string;
20
+ memory?: MemoryStore;
21
+ }) {
22
+ super();
23
+ this.name = options.name;
24
+ this.systemPrompt = options.systemPrompt ?? 'You are a helpful AI agent.';
25
+ this.memory = options.memory ?? new InMemoryStore();
26
+ this.provider = createProvider(options.provider ?? 'deepseek', options.model ?? 'deepseek-chat');
27
+ }
28
+
29
+ get state(): AgentState {
30
+ return this._state;
31
+ }
32
+
33
+ private transition(to: AgentState): void {
34
+ const from = this._state;
35
+ this._state = to;
36
+ this.emit('state:change', from, to);
37
+ }
38
+
39
+ async init(): Promise<void> {
40
+ this.transition('ready');
41
+ }
42
+
43
+ async start(): Promise<void> {
44
+ if (this._state !== 'ready') {
45
+ throw new Error(`Cannot start agent in state: ${this._state}`);
46
+ }
47
+ for (const channel of this.channels) {
48
+ channel.onMessage((msg) => this.handleMessage(msg));
49
+ await channel.start();
50
+ }
51
+ this.transition('running');
52
+ }
53
+
54
+ async stop(): Promise<void> {
55
+ for (const channel of this.channels) {
56
+ await channel.stop();
57
+ }
58
+ this.transition('stopped');
59
+ }
60
+
61
+ registerSkill(skill: ISkill): void {
62
+ this.skills.set(skill.name, skill);
63
+ }
64
+
65
+ bindChannel(channel: IChannel): void {
66
+ this.channels.push(channel);
67
+ }
68
+
69
+ async handleMessage(message: Message): Promise<Message> {
70
+ this.emit('message:in', message);
71
+
72
+ const sessionId = (message.metadata?.sessionId as string) ?? 'default';
73
+ await this.memory.addMessage(sessionId, message);
74
+
75
+ const context: AgentContext = {
76
+ agentName: this.name,
77
+ sessionId,
78
+ messages: await this.memory.getConversation(sessionId),
79
+ memory: this.memory,
80
+ metadata: {},
81
+ };
82
+
83
+ // Try skills first
84
+ for (const [name, skill] of this.skills) {
85
+ try {
86
+ const result = await skill.execute(context, message);
87
+ this.emit('skill:execute', name, result);
88
+ if (result.handled && result.response) {
89
+ const response = this.createResponse(result.response, message);
90
+ await this.memory.addMessage(sessionId, response);
91
+ this.emit('message:out', response);
92
+ return response;
93
+ }
94
+ } catch (err) {
95
+ this.emit('error', err instanceof Error ? err : new Error(String(err)));
96
+ }
97
+ }
98
+
99
+ // Fall back to LLM
100
+ const llmResponse = await this.provider.chat(context.messages, this.systemPrompt);
101
+ const response = this.createResponse(llmResponse, message);
102
+ await this.memory.addMessage(sessionId, response);
103
+ this.emit('message:out', response);
104
+ return response;
105
+ }
106
+
107
+ private createResponse(content: string, inReplyTo: Message): Message {
108
+ return {
109
+ id: `msg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
110
+ role: 'assistant',
111
+ content,
112
+ timestamp: Date.now(),
113
+ metadata: { inReplyTo: inReplyTo.id },
114
+ };
115
+ }
116
+ }
@@ -0,0 +1,14 @@
1
+ import * as fs from 'fs';
2
+ import * as yaml from 'js-yaml';
3
+ import { OADSchema, type OADDocument } from '../schema/oad';
4
+
5
+ export function loadOAD(filePath: string): OADDocument {
6
+ const raw = fs.readFileSync(filePath, 'utf-8');
7
+ const ext = filePath.split('.').pop()?.toLowerCase();
8
+ const data = (ext === 'yaml' || ext === 'yml') ? yaml.load(raw) : JSON.parse(raw);
9
+ return OADSchema.parse(data);
10
+ }
11
+
12
+ export function validateOAD(data: unknown): OADDocument {
13
+ return OADSchema.parse(data);
14
+ }
@@ -0,0 +1,57 @@
1
+ import { BaseAgent } from './agent';
2
+ import { loadOAD } from './config';
3
+ import { WebChannel } from '../channels/web';
4
+ import type { OADDocument } from '../schema/oad';
5
+ import type { ISkill } from './types';
6
+
7
+ export class AgentRuntime {
8
+ private agent: BaseAgent | null = null;
9
+ private config: OADDocument | null = null;
10
+
11
+ async loadConfig(filePath: string): Promise<OADDocument> {
12
+ this.config = loadOAD(filePath);
13
+ return this.config;
14
+ }
15
+
16
+ async initialize(config?: OADDocument): Promise<BaseAgent> {
17
+ const cfg = config ?? this.config;
18
+ if (!cfg) throw new Error('No config loaded. Call loadConfig() first.');
19
+
20
+ this.agent = new BaseAgent({
21
+ name: cfg.metadata.name,
22
+ systemPrompt: cfg.spec.systemPrompt,
23
+ provider: cfg.spec.provider?.default,
24
+ model: cfg.spec.model,
25
+ });
26
+
27
+ // Bind channels
28
+ for (const ch of cfg.spec.channels) {
29
+ if (ch.type === 'web') {
30
+ const port = ch.port ?? 3000;
31
+ this.agent.bindChannel(new WebChannel(port));
32
+ }
33
+ }
34
+
35
+ await this.agent.init();
36
+ return this.agent;
37
+ }
38
+
39
+ async start(): Promise<void> {
40
+ if (!this.agent) throw new Error('Agent not initialized.');
41
+ await this.agent.start();
42
+ }
43
+
44
+ async stop(): Promise<void> {
45
+ if (!this.agent) return;
46
+ await this.agent.stop();
47
+ }
48
+
49
+ registerSkill(skill: ISkill): void {
50
+ if (!this.agent) throw new Error('Agent not initialized.');
51
+ this.agent.registerSkill(skill);
52
+ }
53
+
54
+ getAgent(): BaseAgent | null {
55
+ return this.agent;
56
+ }
57
+ }
@@ -0,0 +1,68 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ // ─── Core Types ──────────────────────────────────────────────
4
+
5
+ export type AgentState = 'init' | 'ready' | 'running' | 'stopped' | 'error';
6
+
7
+ export interface Message {
8
+ id: string;
9
+ role: 'user' | 'assistant' | 'system';
10
+ content: string;
11
+ timestamp: number;
12
+ metadata?: Record<string, unknown>;
13
+ }
14
+
15
+ export interface AgentContext {
16
+ agentName: string;
17
+ sessionId: string;
18
+ messages: Message[];
19
+ memory: MemoryStore;
20
+ metadata: Record<string, unknown>;
21
+ }
22
+
23
+ export interface SkillResult {
24
+ handled: boolean;
25
+ response?: string;
26
+ confidence: number;
27
+ metadata?: Record<string, unknown>;
28
+ }
29
+
30
+ export interface ISkill {
31
+ name: string;
32
+ description: string;
33
+ execute(context: AgentContext, message: Message): Promise<SkillResult>;
34
+ }
35
+
36
+ export interface IChannel {
37
+ type: string;
38
+ start(): Promise<void>;
39
+ stop(): Promise<void>;
40
+ onMessage(handler: (message: Message) => Promise<Message>): void;
41
+ }
42
+
43
+ export interface MemoryStore {
44
+ get(key: string): Promise<unknown>;
45
+ set(key: string, value: unknown): Promise<void>;
46
+ getConversation(sessionId: string): Promise<Message[]>;
47
+ addMessage(sessionId: string, message: Message): Promise<void>;
48
+ clear(sessionId?: string): Promise<void>;
49
+ }
50
+
51
+ export interface AgentEvents {
52
+ 'state:change': (from: AgentState, to: AgentState) => void;
53
+ 'message:in': (message: Message) => void;
54
+ 'message:out': (message: Message) => void;
55
+ 'skill:execute': (skill: string, result: SkillResult) => void;
56
+ 'error': (error: Error) => void;
57
+ }
58
+
59
+ export interface IAgent extends EventEmitter {
60
+ readonly name: string;
61
+ readonly state: AgentState;
62
+ init(): Promise<void>;
63
+ start(): Promise<void>;
64
+ stop(): Promise<void>;
65
+ handleMessage(message: Message): Promise<Message>;
66
+ registerSkill(skill: ISkill): void;
67
+ bindChannel(channel: IChannel): void;
68
+ }
@@ -0,0 +1,29 @@
1
+ export interface DataSource {
2
+ readonly name: string;
3
+ readonly type: string;
4
+ read(key: string): Promise<unknown>;
5
+ }
6
+
7
+ /**
8
+ * MRGConfig reader — read-only data layer for agents.
9
+ * Agents can read business data but cannot modify source systems.
10
+ */
11
+ export class MRGConfigReader implements DataSource {
12
+ readonly name = 'mrg-config';
13
+ readonly type = 'config';
14
+ private data: Map<string, unknown>;
15
+
16
+ constructor(initial?: Record<string, unknown>) {
17
+ this.data = new Map(Object.entries(initial ?? {}));
18
+ }
19
+
20
+ async read(key: string): Promise<unknown> {
21
+ return this.data.get(key);
22
+ }
23
+
24
+ load(data: Record<string, unknown>): void {
25
+ for (const [k, v] of Object.entries(data)) {
26
+ this.data.set(k, v);
27
+ }
28
+ }
29
+ }
@@ -0,0 +1,43 @@
1
+ import type { TrustLevelType } from '../schema/oad';
2
+
3
+ /**
4
+ * Trust levels: sandbox → verified → certified → listed
5
+ *
6
+ * - sandbox: No network, no file system, limited capabilities
7
+ * - verified: Identity verified, basic capabilities
8
+ * - certified: Passed security audit, full capabilities
9
+ * - listed: Published in OPC marketplace
10
+ */
11
+ export class TrustManager {
12
+ private level: TrustLevelType;
13
+
14
+ constructor(level: TrustLevelType = 'sandbox') {
15
+ this.level = level;
16
+ }
17
+
18
+ getLevel(): TrustLevelType {
19
+ return this.level;
20
+ }
21
+
22
+ canAccessNetwork(): boolean {
23
+ return this.level !== 'sandbox';
24
+ }
25
+
26
+ canAccessFileSystem(): boolean {
27
+ return this.level === 'certified' || this.level === 'listed';
28
+ }
29
+
30
+ canPublish(): boolean {
31
+ return this.level === 'listed';
32
+ }
33
+
34
+ upgrade(to: TrustLevelType): void {
35
+ const order: TrustLevelType[] = ['sandbox', 'verified', 'certified', 'listed'];
36
+ const currentIdx = order.indexOf(this.level);
37
+ const targetIdx = order.indexOf(to);
38
+ if (targetIdx <= currentIdx) {
39
+ throw new Error(`Cannot downgrade trust from ${this.level} to ${to}`);
40
+ }
41
+ this.level = to;
42
+ }
43
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Value tracking — metrics and ROI for agent operations.
3
+ */
4
+ export interface ValueMetric {
5
+ name: string;
6
+ value: number;
7
+ unit: string;
8
+ timestamp: number;
9
+ }
10
+
11
+ export class ValueTracker {
12
+ private metrics: Map<string, ValueMetric[]> = new Map();
13
+ private trackedNames: Set<string>;
14
+
15
+ constructor(metricNames: string[] = []) {
16
+ this.trackedNames = new Set(metricNames);
17
+ }
18
+
19
+ record(name: string, value: number, unit: string = ''): void {
20
+ if (!this.metrics.has(name)) {
21
+ this.metrics.set(name, []);
22
+ }
23
+ this.metrics.get(name)!.push({ name, value, unit, timestamp: Date.now() });
24
+ }
25
+
26
+ getMetrics(name: string): ValueMetric[] {
27
+ return this.metrics.get(name) ?? [];
28
+ }
29
+
30
+ getAverage(name: string): number {
31
+ const m = this.getMetrics(name);
32
+ if (m.length === 0) return 0;
33
+ return m.reduce((sum, v) => sum + v.value, 0) / m.length;
34
+ }
35
+
36
+ getSummary(): Record<string, { count: number; average: number; last: number }> {
37
+ const result: Record<string, { count: number; average: number; last: number }> = {};
38
+ for (const [name, values] of this.metrics) {
39
+ result[name] = {
40
+ count: values.length,
41
+ average: this.getAverage(name),
42
+ last: values[values.length - 1]?.value ?? 0,
43
+ };
44
+ }
45
+ return result;
46
+ }
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ // OPC Agent — Open Agent Framework
2
+ export { BaseAgent } from './core/agent';
3
+ export { AgentRuntime } from './core/runtime';
4
+ export { loadOAD, validateOAD } from './core/config';
5
+ export { OADSchema } from './schema/oad';
6
+ export type { OADDocument, Metadata, Spec, DTVConfig, TrustLevelType } from './schema/oad';
7
+ export type { IAgent, IChannel, ISkill, Message, AgentContext, SkillResult, MemoryStore, AgentState } from './core/types';
8
+ export { BaseChannel } from './channels';
9
+ export { WebChannel } from './channels/web';
10
+ export { BaseSkill } from './skills/base';
11
+ export { SkillRegistry } from './skills';
12
+ export { InMemoryStore } from './memory';
13
+ export { TrustManager } from './dtv/trust';
14
+ export { ValueTracker } from './dtv/value';
15
+ export { MRGConfigReader } from './dtv/data';
16
+ export { createProvider, SUPPORTED_PROVIDERS } from './providers';
@@ -0,0 +1,34 @@
1
+ import type { Message, MemoryStore } from '../core/types';
2
+
3
+ export class InMemoryStore implements MemoryStore {
4
+ private store: Map<string, unknown> = new Map();
5
+ private conversations: Map<string, Message[]> = new Map();
6
+
7
+ async get(key: string): Promise<unknown> {
8
+ return this.store.get(key);
9
+ }
10
+
11
+ async set(key: string, value: unknown): Promise<void> {
12
+ this.store.set(key, value);
13
+ }
14
+
15
+ async getConversation(sessionId: string): Promise<Message[]> {
16
+ return this.conversations.get(sessionId) ?? [];
17
+ }
18
+
19
+ async addMessage(sessionId: string, message: Message): Promise<void> {
20
+ if (!this.conversations.has(sessionId)) {
21
+ this.conversations.set(sessionId, []);
22
+ }
23
+ this.conversations.get(sessionId)!.push(message);
24
+ }
25
+
26
+ async clear(sessionId?: string): Promise<void> {
27
+ if (sessionId) {
28
+ this.conversations.delete(sessionId);
29
+ } else {
30
+ this.store.clear();
31
+ this.conversations.clear();
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,44 @@
1
+ import type { Message } from '../core/types';
2
+
3
+ /**
4
+ * LLM Provider interface — abstracts different LLM backends.
5
+ * Uses agentkits when available, falls back to stub.
6
+ */
7
+ export interface LLMProvider {
8
+ name: string;
9
+ chat(messages: Message[], systemPrompt?: string): Promise<string>;
10
+ }
11
+
12
+ class StubProvider implements LLMProvider {
13
+ name: string;
14
+ private model: string;
15
+
16
+ constructor(name: string, model: string) {
17
+ this.name = name;
18
+ this.model = model;
19
+ }
20
+
21
+ async chat(messages: Message[], systemPrompt?: string): Promise<string> {
22
+ // Try agentkits dynamic import
23
+ try {
24
+ const ak = await import('agentkits');
25
+ const chat = ak.createChat({ provider: this.name as any, model: this.model });
26
+ const formatted = [
27
+ ...(systemPrompt ? [{ role: 'system' as const, content: systemPrompt }] : []),
28
+ ...messages.map((m) => ({ role: m.role, content: m.content })),
29
+ ];
30
+ const result = await (chat as any).send(formatted);
31
+ return typeof result === 'string' ? result : JSON.stringify(result);
32
+ } catch {
33
+ // Stub fallback when agentkits is not available
34
+ const lastMessage = messages[messages.length - 1];
35
+ return `[${this.name}/${this.model} stub] Received: "${lastMessage?.content ?? ''}"`;
36
+ }
37
+ }
38
+ }
39
+
40
+ export function createProvider(name: string = 'deepseek', model: string = 'deepseek-chat'): LLMProvider {
41
+ return new StubProvider(name, model);
42
+ }
43
+
44
+ export const SUPPORTED_PROVIDERS = ['openai', 'deepseek', 'qwen'] as const;
@@ -0,0 +1,76 @@
1
+ import { z } from 'zod';
2
+
3
+ // ─── OAD Schema v1 ───────────────────────────────────────────
4
+
5
+ export const SkillRefSchema = z.object({
6
+ name: z.string(),
7
+ description: z.string().optional(),
8
+ config: z.record(z.unknown()).optional(),
9
+ });
10
+
11
+ export const ChannelSchema = z.object({
12
+ type: z.enum(['web', 'websocket', 'cli']),
13
+ port: z.number().optional(),
14
+ config: z.record(z.unknown()).optional(),
15
+ });
16
+
17
+ export const MemorySchema = z.object({
18
+ shortTerm: z.boolean().default(true),
19
+ longTerm: z.boolean().default(false),
20
+ provider: z.string().optional(),
21
+ });
22
+
23
+ export const TrustLevel = z.enum(['sandbox', 'verified', 'certified', 'listed']);
24
+
25
+ export const DTVSchema = z.object({
26
+ trust: z.object({
27
+ level: TrustLevel.default('sandbox'),
28
+ }).optional(),
29
+ value: z.object({
30
+ metrics: z.array(z.string()).default([]),
31
+ }).optional(),
32
+ });
33
+
34
+ export const ProviderSchema = z.object({
35
+ default: z.string().default('deepseek'),
36
+ allowed: z.array(z.string()).default(['openai', 'deepseek', 'qwen']),
37
+ });
38
+
39
+ export const MarketplaceSchema = z.object({
40
+ certified: z.boolean().default(false),
41
+ category: z.string().optional(),
42
+ });
43
+
44
+ export const MetadataSchema = z.object({
45
+ name: z.string(),
46
+ version: z.string().default('1.0.0'),
47
+ description: z.string().optional(),
48
+ author: z.string().optional(),
49
+ license: z.string().default('Apache-2.0'),
50
+ marketplace: MarketplaceSchema.optional(),
51
+ });
52
+
53
+ export const SpecSchema = z.object({
54
+ provider: ProviderSchema.optional(),
55
+ model: z.string().default('deepseek-chat'),
56
+ systemPrompt: z.string().optional(),
57
+ skills: z.array(SkillRefSchema).default([]),
58
+ channels: z.array(ChannelSchema).default([]),
59
+ memory: MemorySchema.optional(),
60
+ dtv: DTVSchema.optional(),
61
+ });
62
+
63
+ export const OADSchema = z.object({
64
+ apiVersion: z.literal('opc/v1'),
65
+ kind: z.literal('Agent'),
66
+ metadata: MetadataSchema,
67
+ spec: SpecSchema,
68
+ });
69
+
70
+ export type OADDocument = z.infer<typeof OADSchema>;
71
+ export type SkillRef = z.infer<typeof SkillRefSchema>;
72
+ export type Channel = z.infer<typeof ChannelSchema>;
73
+ export type Metadata = z.infer<typeof MetadataSchema>;
74
+ export type Spec = z.infer<typeof SpecSchema>;
75
+ export type DTVConfig = z.infer<typeof DTVSchema>;
76
+ export type TrustLevelType = z.infer<typeof TrustLevel>;
@@ -0,0 +1,16 @@
1
+ import type { ISkill, AgentContext, Message, SkillResult } from '../core/types';
2
+
3
+ export abstract class BaseSkill implements ISkill {
4
+ abstract name: string;
5
+ abstract description: string;
6
+
7
+ abstract execute(context: AgentContext, message: Message): Promise<SkillResult>;
8
+
9
+ protected noMatch(): SkillResult {
10
+ return { handled: false, confidence: 0 };
11
+ }
12
+
13
+ protected match(response: string, confidence: number = 1.0): SkillResult {
14
+ return { handled: true, response, confidence };
15
+ }
16
+ }
@@ -0,0 +1,27 @@
1
+ import type { ISkill, AgentContext, Message, SkillResult } from '../core/types';
2
+
3
+ export type { ISkill } from '../core/types';
4
+
5
+ export class SkillRegistry {
6
+ private skills: Map<string, ISkill> = new Map();
7
+
8
+ register(skill: ISkill): void {
9
+ this.skills.set(skill.name, skill);
10
+ }
11
+
12
+ get(name: string): ISkill | undefined {
13
+ return this.skills.get(name);
14
+ }
15
+
16
+ list(): ISkill[] {
17
+ return Array.from(this.skills.values());
18
+ }
19
+
20
+ async executeAll(context: AgentContext, message: Message): Promise<SkillResult | null> {
21
+ for (const skill of this.skills.values()) {
22
+ const result = await skill.execute(context, message);
23
+ if (result.handled) return result;
24
+ }
25
+ return null;
26
+ }
27
+ }
@@ -0,0 +1,80 @@
1
+ import { BaseSkill } from '../skills/base';
2
+ import type { AgentContext, Message, SkillResult } from '../core/types';
3
+
4
+ const DEFAULT_FAQ: Record<string, string> = {
5
+ 'hours': 'Our business hours are Monday-Friday, 9am-6pm.',
6
+ 'return': 'You can return items within 30 days of purchase.',
7
+ 'shipping': 'Standard shipping takes 3-5 business days.',
8
+ 'contact': 'You can reach us at support@example.com.',
9
+ };
10
+
11
+ export class FAQSkill extends BaseSkill {
12
+ name = 'faq-lookup';
13
+ description = 'Look up FAQ answers';
14
+ private faq: Record<string, string>;
15
+
16
+ constructor(faq?: Record<string, string>) {
17
+ super();
18
+ this.faq = faq ?? DEFAULT_FAQ;
19
+ }
20
+
21
+ async execute(_context: AgentContext, message: Message): Promise<SkillResult> {
22
+ const lower = message.content.toLowerCase();
23
+ for (const [key, answer] of Object.entries(this.faq)) {
24
+ if (lower.includes(key)) {
25
+ return this.match(answer, 0.9);
26
+ }
27
+ }
28
+ return this.noMatch();
29
+ }
30
+ }
31
+
32
+ export class HandoffSkill extends BaseSkill {
33
+ name = 'human-handoff';
34
+ description = 'Hand off to a human agent when confidence is low';
35
+ private keywords = ['speak to human', 'talk to agent', 'real person', 'human agent'];
36
+
37
+ async execute(_context: AgentContext, message: Message): Promise<SkillResult> {
38
+ const lower = message.content.toLowerCase();
39
+ if (this.keywords.some((kw) => lower.includes(kw))) {
40
+ return this.match(
41
+ 'I understand you\'d like to speak with a human agent. Let me connect you now. Please hold.',
42
+ 1.0
43
+ );
44
+ }
45
+ return this.noMatch();
46
+ }
47
+ }
48
+
49
+ export const CUSTOMER_SERVICE_SYSTEM_PROMPT = `You are a friendly and professional customer service agent.
50
+ You help customers with their questions about products, orders, shipping, and returns.
51
+ Be concise, helpful, and empathetic. If you're unsure, offer to connect them with a human agent.`;
52
+
53
+ export function createCustomerServiceConfig() {
54
+ return {
55
+ apiVersion: 'opc/v1' as const,
56
+ kind: 'Agent' as const,
57
+ metadata: {
58
+ name: 'customer-service',
59
+ version: '1.0.0',
60
+ description: 'Customer service agent with FAQ and human handoff',
61
+ author: 'OPC Agent',
62
+ license: 'Apache-2.0',
63
+ },
64
+ spec: {
65
+ provider: { default: 'deepseek', allowed: ['openai', 'deepseek', 'qwen'] },
66
+ model: 'deepseek-chat',
67
+ systemPrompt: CUSTOMER_SERVICE_SYSTEM_PROMPT,
68
+ skills: [
69
+ { name: 'faq-lookup', description: 'Look up FAQ answers' },
70
+ { name: 'human-handoff', description: 'Hand off to human agent' },
71
+ ],
72
+ channels: [{ type: 'web' as const, port: 3000 }],
73
+ memory: { shortTerm: true, longTerm: false },
74
+ dtv: {
75
+ trust: { level: 'sandbox' as const },
76
+ value: { metrics: ['response_time', 'satisfaction_score'] },
77
+ },
78
+ },
79
+ };
80
+ }