opc-agent 4.1.0 → 4.1.2

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 (258) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +20 -20
  2. package/.github/ISSUE_TEMPLATE/feature_request.md +14 -14
  3. package/.github/PULL_REQUEST_TEMPLATE.md +13 -13
  4. package/CHANGELOG.md +48 -48
  5. package/CONTRIBUTING.md +36 -36
  6. package/README.zh-CN.md +497 -497
  7. package/USABILITY-ISSUES.md +73 -0
  8. package/dist/channels/web.js +8 -2
  9. package/dist/channels/wechat.js +6 -6
  10. package/dist/cli.js +200 -85
  11. package/dist/core/runtime.js +37 -15
  12. package/dist/deploy/index.js +56 -56
  13. package/dist/doctor.d.ts +1 -0
  14. package/dist/doctor.js +105 -10
  15. package/dist/memory/deepbrain.d.ts +1 -1
  16. package/dist/memory/deepbrain.js +95 -4
  17. package/dist/scheduler/cron-engine.js +3 -36
  18. package/dist/studio/server.js +30 -1
  19. package/dist/studio-ui/index.html +230 -10
  20. package/dist/ui/components.js +105 -105
  21. package/examples/README.md +22 -22
  22. package/examples/basic-agent.ts +90 -90
  23. package/examples/brain-integration.ts +71 -71
  24. package/examples/multi-channel.ts +74 -74
  25. package/fix-sidebar.mjs +188 -188
  26. package/install.ps1 +154 -154
  27. package/install.sh +164 -164
  28. package/package.json +1 -1
  29. package/scripts/install.ps1 +31 -31
  30. package/scripts/install.sh +40 -40
  31. package/serve-studio.js +13 -13
  32. package/serve-test.js +25 -25
  33. package/src/channels/dingtalk.ts +46 -46
  34. package/src/channels/email.ts +351 -351
  35. package/src/channels/feishu.ts +349 -349
  36. package/src/channels/googlechat.ts +42 -42
  37. package/src/channels/imessage.ts +31 -31
  38. package/src/channels/irc.ts +82 -82
  39. package/src/channels/line.ts +32 -32
  40. package/src/channels/matrix.ts +33 -33
  41. package/src/channels/mattermost.ts +57 -57
  42. package/src/channels/msteams.ts +32 -32
  43. package/src/channels/nostr.ts +32 -32
  44. package/src/channels/qq.ts +33 -33
  45. package/src/channels/signal.ts +32 -32
  46. package/src/channels/sms.ts +33 -33
  47. package/src/channels/telegram.ts +616 -616
  48. package/src/channels/twitch.ts +65 -65
  49. package/src/channels/voice-call.ts +100 -100
  50. package/src/channels/web.ts +8 -2
  51. package/src/channels/websocket.ts +399 -399
  52. package/src/channels/wechat.ts +329 -329
  53. package/src/channels/whatsapp.ts +32 -32
  54. package/src/cli/chat.ts +99 -99
  55. package/src/cli/setup.ts +314 -314
  56. package/src/cli.ts +195 -92
  57. package/src/core/agent.ts +476 -476
  58. package/src/core/api-server.ts +277 -277
  59. package/src/core/audio.ts +98 -98
  60. package/src/core/collaboration.ts +275 -275
  61. package/src/core/context-discovery.ts +85 -85
  62. package/src/core/context-refs.ts +140 -140
  63. package/src/core/gateway.ts +106 -106
  64. package/src/core/heartbeat.ts +51 -51
  65. package/src/core/hooks.ts +105 -105
  66. package/src/core/ide-bridge.ts +133 -133
  67. package/src/core/node-network.ts +86 -86
  68. package/src/core/profiles.ts +122 -122
  69. package/src/core/runtime.ts +25 -0
  70. package/src/core/scheduler.ts +187 -187
  71. package/src/core/session-manager.ts +137 -137
  72. package/src/core/subagent.ts +98 -98
  73. package/src/core/vision.ts +180 -180
  74. package/src/core/workflow-graph.ts +365 -365
  75. package/src/daemon.ts +96 -96
  76. package/src/deploy/index.ts +255 -255
  77. package/src/doctor.ts +98 -11
  78. package/src/eval/index.ts +211 -211
  79. package/src/eval/suites/basic.json +16 -16
  80. package/src/eval/suites/memory.json +12 -12
  81. package/src/eval/suites/safety.json +14 -14
  82. package/src/hub/brain-seed.ts +54 -54
  83. package/src/hub/client.ts +60 -60
  84. package/src/mcp/servers/calculator-mcp.ts +65 -65
  85. package/src/mcp/servers/crypto-mcp.ts +73 -73
  86. package/src/mcp/servers/database-mcp.ts +72 -72
  87. package/src/mcp/servers/datetime-mcp.ts +69 -69
  88. package/src/mcp/servers/filesystem.ts +66 -66
  89. package/src/mcp/servers/github-mcp.ts +58 -58
  90. package/src/mcp/servers/index.ts +63 -63
  91. package/src/mcp/servers/json-mcp.ts +102 -102
  92. package/src/mcp/servers/memory-mcp.ts +56 -56
  93. package/src/mcp/servers/regex-mcp.ts +53 -53
  94. package/src/mcp/servers/web-mcp.ts +49 -49
  95. package/src/memory/context-compressor.ts +189 -189
  96. package/src/memory/deepbrain.ts +99 -5
  97. package/src/memory/seed-loader.ts +212 -212
  98. package/src/memory/user-profiler.ts +215 -215
  99. package/src/plugins/content-filter.ts +23 -23
  100. package/src/plugins/logger.ts +18 -18
  101. package/src/plugins/rate-limiter.ts +38 -38
  102. package/src/protocols/a2a/client.ts +132 -132
  103. package/src/protocols/a2a/index.ts +8 -8
  104. package/src/protocols/a2a/server.ts +333 -333
  105. package/src/protocols/a2a/types.ts +88 -88
  106. package/src/protocols/a2a/utils.ts +50 -50
  107. package/src/protocols/agui/client.ts +83 -83
  108. package/src/protocols/agui/index.ts +4 -4
  109. package/src/protocols/agui/server.ts +218 -218
  110. package/src/protocols/agui/types.ts +153 -153
  111. package/src/protocols/index.ts +2 -2
  112. package/src/protocols/mcp/agent-tools.ts +134 -134
  113. package/src/protocols/mcp/index.ts +8 -8
  114. package/src/protocols/mcp/server.ts +262 -262
  115. package/src/protocols/mcp/types.ts +69 -69
  116. package/src/providers/index.ts +632 -632
  117. package/src/publish/index.ts +376 -376
  118. package/src/scheduler/cron-engine.ts +191 -191
  119. package/src/scheduler/index.ts +2 -2
  120. package/src/schema/oad.ts +217 -217
  121. package/src/security/approval.ts +131 -131
  122. package/src/security/approvals.ts +143 -143
  123. package/src/security/elevated.ts +105 -105
  124. package/src/security/guardrails.ts +248 -248
  125. package/src/security/index.ts +9 -9
  126. package/src/security/keys.ts +87 -87
  127. package/src/security/secrets.ts +129 -129
  128. package/src/skills/builtin/index.ts +408 -408
  129. package/src/skills/marketplace.ts +113 -113
  130. package/src/skills/types.ts +42 -42
  131. package/src/studio/server.ts +31 -1
  132. package/src/studio/templates-data.ts +178 -178
  133. package/src/studio-ui/index.html +230 -10
  134. package/src/telemetry/index.ts +324 -324
  135. package/src/tools/builtin/browser.ts +299 -299
  136. package/src/tools/builtin/datetime.ts +41 -41
  137. package/src/tools/builtin/file.ts +107 -107
  138. package/src/tools/builtin/home-assistant.ts +116 -116
  139. package/src/tools/builtin/rl-tools.ts +243 -243
  140. package/src/tools/builtin/shell.ts +43 -43
  141. package/src/tools/builtin/vision.ts +64 -64
  142. package/src/tools/builtin/web-search.ts +126 -126
  143. package/src/tools/builtin/web.ts +35 -35
  144. package/src/tools/document-processor.ts +213 -213
  145. package/src/tools/image-generator.ts +150 -150
  146. package/src/tools/integrations/calendar.ts +73 -73
  147. package/src/tools/integrations/code-exec.ts +39 -39
  148. package/src/tools/integrations/csv-analyzer.ts +92 -92
  149. package/src/tools/integrations/database.ts +44 -44
  150. package/src/tools/integrations/email-send.ts +76 -76
  151. package/src/tools/integrations/git-tool.ts +42 -42
  152. package/src/tools/integrations/github-tool.ts +76 -76
  153. package/src/tools/integrations/image-gen.ts +56 -56
  154. package/src/tools/integrations/index.ts +92 -92
  155. package/src/tools/integrations/jira.ts +83 -83
  156. package/src/tools/integrations/notion.ts +71 -71
  157. package/src/tools/integrations/npm-tool.ts +48 -48
  158. package/src/tools/integrations/pdf-reader.ts +58 -58
  159. package/src/tools/integrations/slack.ts +65 -65
  160. package/src/tools/integrations/summarizer.ts +49 -49
  161. package/src/tools/integrations/translator.ts +48 -48
  162. package/src/tools/integrations/trello.ts +60 -60
  163. package/src/tools/integrations/vector-search.ts +42 -42
  164. package/src/tools/integrations/web-scraper.ts +47 -47
  165. package/src/tools/integrations/web-search.ts +58 -58
  166. package/src/tools/integrations/webhook.ts +38 -38
  167. package/src/tools/mcp-client.ts +131 -131
  168. package/src/tools/web-scraper.ts +179 -179
  169. package/src/tools/web-search.ts +180 -180
  170. package/src/ui/components.ts +127 -127
  171. package/srv-out.txt +1 -1
  172. package/templates/ecommerce-assistant/README.md +45 -45
  173. package/templates/ecommerce-assistant/oad.yaml +47 -47
  174. package/templates/tech-support/README.md +43 -43
  175. package/templates/tech-support/oad.yaml +45 -45
  176. package/test-agent/Dockerfile +9 -9
  177. package/test-agent/README.md +50 -50
  178. package/test-agent/agent.yaml +23 -23
  179. package/test-agent/docker-compose.yml +11 -11
  180. package/test-agent/oad.yaml +31 -31
  181. package/test-agent/package-lock.json +1492 -1492
  182. package/test-agent/package.json +17 -17
  183. package/test-agent/src/index.ts +24 -24
  184. package/test-agent/src/skills/echo.ts +15 -15
  185. package/test-agent/tsconfig.json +24 -24
  186. package/test-full.js +43 -43
  187. package/test-sidebar.js +22 -22
  188. package/test-studio3.js +75 -75
  189. package/test-studio4.js +41 -41
  190. package/tests/a2a-protocol.test.ts +285 -285
  191. package/tests/agui-protocol.test.ts +246 -246
  192. package/tests/api-server.test.ts +148 -148
  193. package/tests/approvals.test.ts +89 -89
  194. package/tests/audio.test.ts +40 -40
  195. package/tests/brain-seed-extended.test.ts +490 -490
  196. package/tests/brain-seed.test.ts +239 -239
  197. package/tests/browser.test.ts +179 -179
  198. package/tests/channels/discord.test.ts +79 -79
  199. package/tests/channels/email.test.ts +148 -148
  200. package/tests/channels/feishu.test.ts +123 -123
  201. package/tests/channels/telegram.test.ts +129 -129
  202. package/tests/channels/websocket.test.ts +53 -53
  203. package/tests/channels/wechat.test.ts +170 -170
  204. package/tests/channels-extra.test.ts +45 -45
  205. package/tests/chat-cli.test.ts +160 -160
  206. package/tests/cli.test.ts +46 -46
  207. package/tests/context-compressor.test.ts +172 -172
  208. package/tests/context-refs.test.ts +121 -121
  209. package/tests/cron-engine.test.ts +101 -101
  210. package/tests/daemon.test.ts +135 -135
  211. package/tests/deepbrain-wire.test.ts +234 -234
  212. package/tests/deploy-and-dag.test.ts +196 -196
  213. package/tests/doctor.test.ts +38 -38
  214. package/tests/document-processor.test.ts +69 -69
  215. package/tests/e2e-nocode.test.ts +442 -442
  216. package/tests/elevated.test.ts +69 -69
  217. package/tests/eval.test.ts +173 -173
  218. package/tests/gateway.test.ts +63 -63
  219. package/tests/guardrails.test.ts +177 -177
  220. package/tests/home-assistant.test.ts +40 -40
  221. package/tests/hooks.test.ts +79 -79
  222. package/tests/ide-bridge.test.ts +38 -38
  223. package/tests/image-generator.test.ts +84 -84
  224. package/tests/init-role.test.ts +124 -124
  225. package/tests/integrations.test.ts +249 -249
  226. package/tests/mcp-client.test.ts +92 -92
  227. package/tests/mcp-server.test.ts +178 -178
  228. package/tests/mcp-servers.test.ts +260 -260
  229. package/tests/node-network.test.ts +74 -74
  230. package/tests/plugin-a2a-enhanced.test.ts +230 -230
  231. package/tests/profiles.test.ts +61 -61
  232. package/tests/publish.test.ts +231 -231
  233. package/tests/rl-tools.test.ts +93 -93
  234. package/tests/sandbox-manager.test.ts +46 -46
  235. package/tests/scheduler.test.ts +200 -200
  236. package/tests/secrets.test.ts +107 -107
  237. package/tests/security-enhanced.test.ts +233 -233
  238. package/tests/settings-api.test.ts +148 -148
  239. package/tests/setup.test.ts +73 -73
  240. package/tests/subagent.test.ts +193 -193
  241. package/tests/telegram-discord.test.ts +60 -60
  242. package/tests/telemetry.test.ts +186 -186
  243. package/tests/user-profiler.test.ts +169 -169
  244. package/tests/v090-features.test.ts +254 -254
  245. package/tests/vision.test.ts +61 -61
  246. package/tests/voice-call.test.ts +47 -47
  247. package/tests/voice-enhanced.test.ts +169 -169
  248. package/tests/voice-interaction.test.ts +38 -38
  249. package/tests/web-search.test.ts +155 -155
  250. package/tests/workflow-graph.test.ts +279 -279
  251. package/tutorial/customer-service-agent/README.md +612 -612
  252. package/tutorial/customer-service-agent/SOUL.md +26 -26
  253. package/tutorial/customer-service-agent/agent.yaml +63 -63
  254. package/tutorial/customer-service-agent/package.json +19 -19
  255. package/tutorial/customer-service-agent/src/index.ts +69 -69
  256. package/tutorial/customer-service-agent/src/skills/faq.ts +27 -27
  257. package/tutorial/customer-service-agent/src/skills/ticket.ts +22 -22
  258. package/tutorial/customer-service-agent/tsconfig.json +14 -14
@@ -1,612 +1,612 @@
1
- # Build a Customer Service Agent with OPC Agent
2
-
3
- A step-by-step guide covering **every** major feature of OPC Agent — from project setup to production deployment.
4
-
5
- > 🌐 中英双语注释 | Bilingual comments throughout
6
-
7
- ## Table of Contents
8
-
9
- 1. [Project Setup](#chapter-1-project-setup)
10
- 2. [Agent Configuration (OAD)](#chapter-2-agent-configuration)
11
- 3. [Skills](#chapter-3-skills)
12
- 4. [Memory with DeepBrain](#chapter-4-memory-with-deepbrain)
13
- 5. [Channels (Web, Telegram, Discord)](#chapter-5-channels)
14
- 6. [Workflow Engine](#chapter-6-workflow-engine)
15
- 7. [Built-in Tools](#chapter-7-built-in-tools)
16
- 8. [Sub-Agents](#chapter-8-sub-agents)
17
- 9. [Plugin System](#chapter-9-plugin-system)
18
- 10. [Scheduled Jobs (Cron)](#chapter-10-scheduled-jobs)
19
- 11. [Security](#chapter-11-security)
20
- 12. [Packaging & Publishing](#chapter-12-packaging--publishing)
21
- 13. [Monitoring & Analytics](#chapter-13-monitoring--analytics)
22
-
23
- ---
24
-
25
- ## Chapter 1: Project Setup
26
-
27
- ### Prerequisites
28
-
29
- - Node.js >= 18
30
- - npm or yarn
31
- - (Optional) Ollama for local LLM inference
32
-
33
- ### Install & Initialize
34
-
35
- ```bash
36
- # 安装 OPC Agent CLI / Install the CLI globally
37
- npm install -g opc-agent
38
-
39
- # 检查环境 / Verify your environment
40
- opc doctor
41
-
42
- # 创建项目 / Scaffold a new agent project
43
- opc init customer-service
44
- cd customer-service
45
- npm install
46
- ```
47
-
48
- `opc doctor` checks for Node version, required dependencies, and optional integrations (Ollama, Docker, etc.).
49
-
50
- ### Project Structure
51
-
52
- After initialization, you'll have:
53
-
54
- ```
55
- customer-service/
56
- ├── agent.yaml # Agent configuration (OAD spec)
57
- ├── SOUL.md # Agent personality & behavior guide
58
- ├── package.json # Node.js dependencies
59
- ├── tsconfig.json # TypeScript config
60
- └── src/
61
- ├── index.ts # Entry point
62
- └── skills/ # Custom skills
63
- ├── faq.ts
64
- └── ticket.ts
65
- ```
66
-
67
- ---
68
-
69
- ## Chapter 2: Agent Configuration
70
-
71
- The `agent.yaml` file is the heart of your agent — it follows the **OAD (Open Agent Definition)** spec.
72
-
73
- ```yaml
74
- apiVersion: opc/v1
75
- kind: Agent
76
- metadata:
77
- name: customer-service
78
- version: 1.0.0
79
- description: 智能客服 Agent — Smart Customer Service Agent
80
- author: your-name
81
- license: MIT
82
-
83
- spec:
84
- # LLM 配置 / LLM Configuration
85
- model: qwen2.5
86
- provider:
87
- default: ollama
88
-
89
- # 系统提示词 / System Prompt
90
- systemPrompt: |
91
- 你是一个专业的客服助手,代表我们的电商平台为客户提供帮助。
92
- You are a professional customer service assistant.
93
-
94
- 规则 / Rules:
95
- - 用中文回答,必要时使用英文术语
96
- - 始终保持礼貌和耐心
97
- - 如果不确定,创建工单转人工
98
- - 不要编造信息
99
-
100
- # 频道配置 / Channel Configuration
101
- channels:
102
- - type: web
103
- port: 3000
104
-
105
- # 记忆系统 / Memory System
106
- memory:
107
- shortTerm: true
108
-
109
- # 技能列表 / Skills
110
- skills:
111
- - name: faq
112
- - name: ticket
113
-
114
- # 调度任务 / Scheduled Jobs
115
- scheduler:
116
- jobs:
117
- - name: daily-report
118
- schedule: "0 9 * * *"
119
- task: "Generate daily customer service report"
120
-
121
- # 安全配置 / Security
122
- security:
123
- approval: dangerous
124
- sandbox:
125
- maxFileSize: 10485760
126
- ```
127
-
128
- ### Key Sections Explained
129
-
130
- | Section | Purpose |
131
- |---------|---------|
132
- | `metadata` | Agent identity — name, version, description |
133
- | `spec.model` | Which LLM to use |
134
- | `spec.provider` | LLM provider (ollama, openai, etc.) |
135
- | `spec.systemPrompt` | Base personality and rules |
136
- | `spec.channels` | How users interact with the agent |
137
- | `spec.memory` | Conversation memory settings |
138
- | `spec.skills` | Registered skill modules |
139
- | `spec.scheduler` | Cron-based scheduled tasks |
140
- | `spec.security` | Permission and sandbox settings |
141
-
142
- ---
143
-
144
- ## Chapter 3: Skills
145
-
146
- Skills are modular capabilities your agent can invoke. Each skill has a name, description, trigger patterns, and an `execute` method.
147
-
148
- ### FAQ Skill — `src/skills/faq.ts`
149
-
150
- ```typescript
151
- import { BaseSkill } from 'opc-agent';
152
-
153
- // FAQ 查询技能 / FAQ Lookup Skill
154
- export class FAQSkill extends BaseSkill {
155
- name = 'faq';
156
- description = 'Look up frequently asked questions';
157
- triggers = [/常见问题|FAQ|怎么退款|退货|配送|支付/i];
158
-
159
- async execute(input: string): Promise<string> {
160
- // 常见问题知识库 / FAQ Knowledge Base
161
- const faqs: Record<string, string> = {
162
- '退款': '退款将在3-5个工作日内到账。如超时未到账,请联系银行确认。',
163
- '退货': '请在收到商品7天内申请退货。商品需保持原包装,未使用。',
164
- '配送': '标准配送3-5天,加急配送1-2天。偏远地区可能延迟1-2天。',
165
- '支付': '支持支付宝、微信支付、银行卡(Visa/Mastercard/银联)。',
166
- };
167
-
168
- for (const [key, answer] of Object.entries(faqs)) {
169
- if (input.includes(key)) return answer;
170
- }
171
-
172
- return '请问您想了解什么?我们有以下常见问题:退款、退货、配送、支付';
173
- }
174
- }
175
- ```
176
-
177
- ### Ticket Skill — `src/skills/ticket.ts`
178
-
179
- ```typescript
180
- import { BaseSkill } from 'opc-agent';
181
-
182
- // 工单创建技能 / Support Ticket Skill
183
- export class TicketSkill extends BaseSkill {
184
- name = 'ticket';
185
- description = 'Create a support ticket for human follow-up';
186
- triggers = [/创建工单|提交问题|人工客服|投诉/i];
187
-
188
- async execute(input: string): Promise<string> {
189
- // 生成唯一工单号 / Generate unique ticket ID
190
- const ticketId = `TK-${Date.now().toString(36).toUpperCase()}`;
191
-
192
- // 实际项目中这里会写入数据库
193
- // In production, this would write to a database
194
- console.log(`[Ticket Created] ${ticketId}: ${input}`);
195
-
196
- return `已创建工单 ${ticketId},客服团队将在2小时内联系您。\nTicket ${ticketId} created. Our team will contact you within 2 hours.`;
197
- }
198
- }
199
- ```
200
-
201
- ### Registering Skills
202
-
203
- Skills listed in `agent.yaml` under `spec.skills` are auto-discovered from `src/skills/`. The agent matches incoming messages against `triggers` and routes to the appropriate skill.
204
-
205
- ---
206
-
207
- ## Chapter 4: Memory with DeepBrain
208
-
209
- OPC Agent integrates with **DeepBrain** for persistent memory — enabling your agent to learn from past conversations.
210
-
211
- ```typescript
212
- // src/index.ts
213
- import { Agent } from 'opc-agent';
214
- import { Brain } from 'deepbrain';
215
-
216
- // 初始化 DeepBrain / Initialize DeepBrain
217
- const brain = new Brain({
218
- database: './data/customer-brain.db',
219
- embedding_provider: 'ollama',
220
- });
221
- await brain.connect();
222
-
223
- const agent = new Agent('./agent.yaml');
224
-
225
- // 存储对话用于学习 / Store conversations for learning
226
- agent.on('message', async (msg, response) => {
227
- await brain.put(
228
- `conv-${msg.id}`,
229
- `Q: ${msg.content}\nA: ${response.content}`
230
- );
231
- });
232
-
233
- // 语义搜索历史对话 / Semantic search past conversations
234
- agent.on('beforeReply', async (ctx) => {
235
- const relevant = await brain.query(ctx.message, { limit: 3 });
236
- if (relevant.length > 0) {
237
- ctx.additionalContext = relevant.map(r => r.content).join('\n');
238
- }
239
- });
240
-
241
- await agent.start();
242
- ```
243
-
244
- ### What DeepBrain Provides
245
-
246
- - **Semantic search** — Find relevant past conversations by meaning, not just keywords
247
- - **Persistent storage** — SQLite-based, survives restarts
248
- - **Embedding support** — Works with Ollama, OpenAI, or Gemini embeddings
249
-
250
- ---
251
-
252
- ## Chapter 5: Channels
253
-
254
- Channels define how users interact with your agent. OPC Agent supports multiple simultaneous channels.
255
-
256
- ### Web (Built-in)
257
-
258
- ```yaml
259
- spec:
260
- channels:
261
- - type: web
262
- port: 3000
263
- ```
264
-
265
- Launches a web chat UI at `http://localhost:3000`.
266
-
267
- ### Telegram
268
-
269
- ```yaml
270
- spec:
271
- channels:
272
- - type: web
273
- port: 3000
274
- - type: telegram
275
- token: ${TELEGRAM_BOT_TOKEN}
276
- mode: polling
277
- ```
278
-
279
- Set the environment variable `TELEGRAM_BOT_TOKEN` from [@BotFather](https://t.me/BotFather).
280
-
281
- ### Discord
282
-
283
- ```yaml
284
- spec:
285
- channels:
286
- - type: discord
287
- token: ${DISCORD_BOT_TOKEN}
288
- guildId: "your-server-id"
289
- ```
290
-
291
- ### Multi-Channel
292
-
293
- All channels share the same agent logic, skills, and memory. A message from Telegram triggers the same FAQ skill as one from the web UI.
294
-
295
- ---
296
-
297
- ## Chapter 6: Workflow Engine
298
-
299
- For multi-step interactions, use the **Workflow Engine** to define conversation flows with branching logic.
300
-
301
- ```typescript
302
- import { WorkflowBuilder } from 'opc-agent';
303
-
304
- // 客户引导流程 / Customer Onboarding Workflow
305
- const onboarding = new WorkflowBuilder()
306
- .start('greet')
307
- .addAction('greet', async (ctx) => {
308
- return '欢迎!请问您是新客户还是老客户?\nWelcome! Are you a new or returning customer?';
309
- }, { next: 'check-type' })
310
- .addCondition('check-type',
311
- (ctx) => ctx.variables.get('isNewCustomer'),
312
- 'new-flow', // true 分支 / true branch
313
- 'existing-flow' // false 分支 / false branch
314
- )
315
- .addAction('new-flow', async (ctx) => {
316
- return '让我帮您注册账号。请提供您的邮箱地址。';
317
- }, { next: 'collect-email' })
318
- .addAction('collect-email', async (ctx) => {
319
- const email = ctx.message;
320
- ctx.variables.set('email', email);
321
- return `注册成功!欢迎加入,${email}`;
322
- }, { next: 'done' })
323
- .addAction('existing-flow', async (ctx) => {
324
- return '欢迎回来!有什么可以帮您?';
325
- }, { next: 'done' })
326
- .addAction('done', async () => 'Onboarding complete')
327
- .build();
328
-
329
- // 注册工作流 / Register the workflow
330
- agent.registerWorkflow('onboarding', onboarding);
331
- ```
332
-
333
- ### Workflow Features
334
-
335
- - **Branching** — Conditional paths based on user input or variables
336
- - **State management** — `ctx.variables` persists across steps
337
- - **Composable** — Workflows can trigger other workflows
338
-
339
- ---
340
-
341
- ## Chapter 7: Built-in Tools
342
-
343
- OPC Agent comes with built-in tools that your agent can use autonomously.
344
-
345
- ```typescript
346
- import { getBuiltinTools } from 'opc-agent';
347
-
348
- // 加载内置工具 / Load built-in tools
349
- const tools = getBuiltinTools('./workspace');
350
- ```
351
-
352
- ### Available Tools
353
-
354
- | Tool | Description |
355
- |------|-------------|
356
- | `readFile` | Read file contents |
357
- | `writeFile` | Write/create files |
358
- | `fetchUrl` | HTTP requests to external APIs |
359
- | `runCommand` | Execute shell commands (sandboxed) |
360
- | `getTime` | Current date/time |
361
- | `listFiles` | Directory listing |
362
-
363
- ### Example: Agent Uses Tools
364
-
365
- ```typescript
366
- // Agent can autonomously decide to use tools
367
- // 例如查询订单状态时,agent 可以调用 API
368
- const agent = new Agent('./agent.yaml', { tools });
369
- ```
370
-
371
- The agent decides which tools to invoke based on the user's request and the tool descriptions.
372
-
373
- ---
374
-
375
- ## Chapter 8: Sub-Agents
376
-
377
- For complex tasks, spawn specialized sub-agents that work independently and report back.
378
-
379
- ```typescript
380
- import { SubAgentManager } from 'opc-agent';
381
-
382
- const manager = new SubAgentManager();
383
-
384
- // 委派研究任务给子 Agent / Delegate research to a sub-agent
385
- const result = await agent.spawnSubAgent({
386
- name: 'researcher',
387
- task: 'Find the return policy for order #12345',
388
- systemPrompt: 'You are a research specialist. Find accurate information.',
389
- model: 'qwen2.5',
390
- });
391
-
392
- console.log(result.output); // Sub-agent's findings
393
- ```
394
-
395
- ### Sub-Agent Use Cases
396
-
397
- - **Research** — Look up order details, policies, product info
398
- - **Translation** — Translate customer messages
399
- - **Analysis** — Analyze sentiment or categorize issues
400
- - **Escalation** — Prepare summaries for human agents
401
-
402
- ---
403
-
404
- ## Chapter 9: Plugin System
405
-
406
- Extend your agent with plugins for cross-cutting concerns.
407
-
408
- ```typescript
409
- import { loggerPlugin, rateLimiterPlugin } from 'opc-agent';
410
-
411
- const agent = new Agent('./agent.yaml', {
412
- plugins: [
413
- // 日志插件 / Logger — logs all messages
414
- loggerPlugin({ level: 'info', output: './logs/agent.log' }),
415
-
416
- // 限流插件 / Rate limiter — prevent abuse
417
- rateLimiterPlugin({ maxRequests: 60, windowMs: 60000 }),
418
- ],
419
- });
420
- ```
421
-
422
- ### Plugin Lifecycle Hooks
423
-
424
- Plugins can hook into:
425
- - `onMessage` — Before processing a message
426
- - `onReply` — Before sending a reply
427
- - `onError` — When an error occurs
428
- - `onStart` / `onStop` — Agent lifecycle
429
-
430
- ### Writing a Custom Plugin
431
-
432
- ```typescript
433
- import { Plugin } from 'opc-agent';
434
-
435
- // 自定义插件示例 / Custom plugin example
436
- export const metricsPlugin: Plugin = {
437
- name: 'metrics',
438
- onMessage: async (msg) => {
439
- console.log(`[${new Date().toISOString()}] Received: ${msg.content.slice(0, 50)}`);
440
- },
441
- onReply: async (msg, reply) => {
442
- console.log(`[${new Date().toISOString()}] Replied in ${reply.latencyMs}ms`);
443
- },
444
- };
445
- ```
446
-
447
- ---
448
-
449
- ## Chapter 10: Scheduled Jobs
450
-
451
- Run tasks on a schedule using cron syntax.
452
-
453
- ```yaml
454
- # agent.yaml
455
- spec:
456
- scheduler:
457
- jobs:
458
- - name: daily-report
459
- schedule: "0 9 * * *" # 每天早上9点 / Daily at 9 AM
460
- task: "Generate daily customer service report"
461
-
462
- - name: cleanup-old-tickets
463
- schedule: "0 2 * * 0" # 每周日凌晨2点 / Sunday 2 AM
464
- task: "Archive tickets older than 30 days"
465
-
466
- - name: health-check
467
- schedule: "*/15 * * * *" # 每15分钟 / Every 15 minutes
468
- task: "Check all channel connections are alive"
469
- ```
470
-
471
- ### Managing Jobs
472
-
473
- ```bash
474
- # 查看所有任务 / List all scheduled jobs
475
- opc jobs list
476
-
477
- # 手动触发 / Manually trigger a job
478
- opc jobs run daily-report
479
-
480
- # 查看历史 / View job history
481
- opc jobs history
482
- ```
483
-
484
- ---
485
-
486
- ## Chapter 11: Security
487
-
488
- OPC Agent provides multiple security layers.
489
-
490
- ```yaml
491
- spec:
492
- security:
493
- # 危险操作需要审批 / Dangerous actions require approval
494
- approval: dangerous
495
-
496
- # 沙箱限制 / Sandbox constraints
497
- sandbox:
498
- maxFileSize: 10485760 # 10MB max file size
499
- allowedCommands: # Whitelist commands
500
- - "curl"
501
- - "node"
502
- blockedPaths: # Protect sensitive paths
503
- - "/etc"
504
- - "~/.ssh"
505
- ```
506
-
507
- ### Security Features
508
-
509
- | Feature | Description |
510
- |---------|-------------|
511
- | **Approval mode** | `dangerous` ops need human approval |
512
- | **Sandbox** | File size limits, command whitelist |
513
- | **Path blocking** | Prevent access to sensitive directories |
514
- | **Rate limiting** | Via plugin (Chapter 9) |
515
- | **Token rotation** | Channel tokens via env vars, not hardcoded |
516
-
517
- ### Best Practices
518
-
519
- - Never hardcode API keys — use `${ENV_VAR}` syntax in `agent.yaml`
520
- - Enable `approval: dangerous` in production
521
- - Set `maxFileSize` to prevent resource exhaustion
522
- - Use `allowedCommands` to restrict what the agent can execute
523
-
524
- ---
525
-
526
- ## Chapter 12: Packaging & Publishing
527
-
528
- Share your agent with others via the OPC registry.
529
-
530
- ```bash
531
- # 预览打包内容 / Preview what will be packaged
532
- opc pack --list
533
-
534
- # 试运行发布 / Dry run — see what would happen
535
- opc publish --dry-run
536
-
537
- # 正式发布 / Publish to the registry
538
- opc publish
539
- ```
540
-
541
- ### What Gets Packaged
542
-
543
- - `agent.yaml` — Configuration
544
- - `SOUL.md` — Personality
545
- - `src/` — Skills and logic
546
- - `package.json` — Dependencies
547
-
548
- ### Versioning
549
-
550
- Follow semver in `metadata.version`. Bump before each publish:
551
-
552
- ```bash
553
- # Update version in agent.yaml
554
- # metadata:
555
- # version: 1.1.0
556
- opc publish
557
- ```
558
-
559
- ---
560
-
561
- ## Chapter 13: Monitoring & Analytics
562
-
563
- ### Running Your Agent
564
-
565
- ```bash
566
- # 开发模式 / Development — interactive CLI chat
567
- opc chat
568
-
569
- # 服务模式 / Server — starts web server + all channels
570
- opc run
571
-
572
- # 生产模式 / Production — runs as daemon
573
- opc start
574
-
575
- # 检查状态 / Check status
576
- opc status
577
-
578
- # 查看日志 / View logs
579
- opc logs --tail 100
580
-
581
- # 停止 / Stop
582
- opc stop
583
- ```
584
-
585
- ### Monitoring
586
-
587
- - **`opc status`** — Shows agent health, active channels, memory usage
588
- - **`opc jobs list`** — Cron job status and next run times
589
- - **Logs** — Structured JSON logs for integration with ELK, Grafana, etc.
590
- - **Metrics plugin** — Custom metrics (see Chapter 9)
591
-
592
- ### Production Checklist
593
-
594
- - [ ] Set `approval: dangerous` in security config
595
- - [ ] Configure all channel tokens via environment variables
596
- - [ ] Enable logging plugin with file output
597
- - [ ] Set up cron jobs for maintenance tasks
598
- - [ ] Test all skills with edge cases
599
- - [ ] Run `opc doctor` to verify environment
600
- - [ ] Use `opc start` (daemon mode) instead of `opc run`
601
-
602
- ---
603
-
604
- ## Next Steps
605
-
606
- - 📖 Read the [OPC Agent Documentation](https://github.com/Deepleaper/opc-agent)
607
- - 🧩 Explore community skills on the OPC registry
608
- - 🤝 Join the community on Discord/Telegram
609
-
610
- ---
611
-
612
- *Built with ❤️ using [OPC Agent](https://github.com/Deepleaper/opc-agent)*
1
+ # Build a Customer Service Agent with OPC Agent
2
+
3
+ A step-by-step guide covering **every** major feature of OPC Agent — from project setup to production deployment.
4
+
5
+ > 🌐 中英双语注释 | Bilingual comments throughout
6
+
7
+ ## Table of Contents
8
+
9
+ 1. [Project Setup](#chapter-1-project-setup)
10
+ 2. [Agent Configuration (OAD)](#chapter-2-agent-configuration)
11
+ 3. [Skills](#chapter-3-skills)
12
+ 4. [Memory with DeepBrain](#chapter-4-memory-with-deepbrain)
13
+ 5. [Channels (Web, Telegram, Discord)](#chapter-5-channels)
14
+ 6. [Workflow Engine](#chapter-6-workflow-engine)
15
+ 7. [Built-in Tools](#chapter-7-built-in-tools)
16
+ 8. [Sub-Agents](#chapter-8-sub-agents)
17
+ 9. [Plugin System](#chapter-9-plugin-system)
18
+ 10. [Scheduled Jobs (Cron)](#chapter-10-scheduled-jobs)
19
+ 11. [Security](#chapter-11-security)
20
+ 12. [Packaging & Publishing](#chapter-12-packaging--publishing)
21
+ 13. [Monitoring & Analytics](#chapter-13-monitoring--analytics)
22
+
23
+ ---
24
+
25
+ ## Chapter 1: Project Setup
26
+
27
+ ### Prerequisites
28
+
29
+ - Node.js >= 18
30
+ - npm or yarn
31
+ - (Optional) Ollama for local LLM inference
32
+
33
+ ### Install & Initialize
34
+
35
+ ```bash
36
+ # 安装 OPC Agent CLI / Install the CLI globally
37
+ npm install -g opc-agent
38
+
39
+ # 检查环境 / Verify your environment
40
+ opc doctor
41
+
42
+ # 创建项目 / Scaffold a new agent project
43
+ opc init customer-service
44
+ cd customer-service
45
+ npm install
46
+ ```
47
+
48
+ `opc doctor` checks for Node version, required dependencies, and optional integrations (Ollama, Docker, etc.).
49
+
50
+ ### Project Structure
51
+
52
+ After initialization, you'll have:
53
+
54
+ ```
55
+ customer-service/
56
+ ├── agent.yaml # Agent configuration (OAD spec)
57
+ ├── SOUL.md # Agent personality & behavior guide
58
+ ├── package.json # Node.js dependencies
59
+ ├── tsconfig.json # TypeScript config
60
+ └── src/
61
+ ├── index.ts # Entry point
62
+ └── skills/ # Custom skills
63
+ ├── faq.ts
64
+ └── ticket.ts
65
+ ```
66
+
67
+ ---
68
+
69
+ ## Chapter 2: Agent Configuration
70
+
71
+ The `agent.yaml` file is the heart of your agent — it follows the **OAD (Open Agent Definition)** spec.
72
+
73
+ ```yaml
74
+ apiVersion: opc/v1
75
+ kind: Agent
76
+ metadata:
77
+ name: customer-service
78
+ version: 1.0.0
79
+ description: 智能客服 Agent — Smart Customer Service Agent
80
+ author: your-name
81
+ license: MIT
82
+
83
+ spec:
84
+ # LLM 配置 / LLM Configuration
85
+ model: qwen2.5
86
+ provider:
87
+ default: ollama
88
+
89
+ # 系统提示词 / System Prompt
90
+ systemPrompt: |
91
+ 你是一个专业的客服助手,代表我们的电商平台为客户提供帮助。
92
+ You are a professional customer service assistant.
93
+
94
+ 规则 / Rules:
95
+ - 用中文回答,必要时使用英文术语
96
+ - 始终保持礼貌和耐心
97
+ - 如果不确定,创建工单转人工
98
+ - 不要编造信息
99
+
100
+ # 频道配置 / Channel Configuration
101
+ channels:
102
+ - type: web
103
+ port: 3000
104
+
105
+ # 记忆系统 / Memory System
106
+ memory:
107
+ shortTerm: true
108
+
109
+ # 技能列表 / Skills
110
+ skills:
111
+ - name: faq
112
+ - name: ticket
113
+
114
+ # 调度任务 / Scheduled Jobs
115
+ scheduler:
116
+ jobs:
117
+ - name: daily-report
118
+ schedule: "0 9 * * *"
119
+ task: "Generate daily customer service report"
120
+
121
+ # 安全配置 / Security
122
+ security:
123
+ approval: dangerous
124
+ sandbox:
125
+ maxFileSize: 10485760
126
+ ```
127
+
128
+ ### Key Sections Explained
129
+
130
+ | Section | Purpose |
131
+ |---------|---------|
132
+ | `metadata` | Agent identity — name, version, description |
133
+ | `spec.model` | Which LLM to use |
134
+ | `spec.provider` | LLM provider (ollama, openai, etc.) |
135
+ | `spec.systemPrompt` | Base personality and rules |
136
+ | `spec.channels` | How users interact with the agent |
137
+ | `spec.memory` | Conversation memory settings |
138
+ | `spec.skills` | Registered skill modules |
139
+ | `spec.scheduler` | Cron-based scheduled tasks |
140
+ | `spec.security` | Permission and sandbox settings |
141
+
142
+ ---
143
+
144
+ ## Chapter 3: Skills
145
+
146
+ Skills are modular capabilities your agent can invoke. Each skill has a name, description, trigger patterns, and an `execute` method.
147
+
148
+ ### FAQ Skill — `src/skills/faq.ts`
149
+
150
+ ```typescript
151
+ import { BaseSkill } from 'opc-agent';
152
+
153
+ // FAQ 查询技能 / FAQ Lookup Skill
154
+ export class FAQSkill extends BaseSkill {
155
+ name = 'faq';
156
+ description = 'Look up frequently asked questions';
157
+ triggers = [/常见问题|FAQ|怎么退款|退货|配送|支付/i];
158
+
159
+ async execute(input: string): Promise<string> {
160
+ // 常见问题知识库 / FAQ Knowledge Base
161
+ const faqs: Record<string, string> = {
162
+ '退款': '退款将在3-5个工作日内到账。如超时未到账,请联系银行确认。',
163
+ '退货': '请在收到商品7天内申请退货。商品需保持原包装,未使用。',
164
+ '配送': '标准配送3-5天,加急配送1-2天。偏远地区可能延迟1-2天。',
165
+ '支付': '支持支付宝、微信支付、银行卡(Visa/Mastercard/银联)。',
166
+ };
167
+
168
+ for (const [key, answer] of Object.entries(faqs)) {
169
+ if (input.includes(key)) return answer;
170
+ }
171
+
172
+ return '请问您想了解什么?我们有以下常见问题:退款、退货、配送、支付';
173
+ }
174
+ }
175
+ ```
176
+
177
+ ### Ticket Skill — `src/skills/ticket.ts`
178
+
179
+ ```typescript
180
+ import { BaseSkill } from 'opc-agent';
181
+
182
+ // 工单创建技能 / Support Ticket Skill
183
+ export class TicketSkill extends BaseSkill {
184
+ name = 'ticket';
185
+ description = 'Create a support ticket for human follow-up';
186
+ triggers = [/创建工单|提交问题|人工客服|投诉/i];
187
+
188
+ async execute(input: string): Promise<string> {
189
+ // 生成唯一工单号 / Generate unique ticket ID
190
+ const ticketId = `TK-${Date.now().toString(36).toUpperCase()}`;
191
+
192
+ // 实际项目中这里会写入数据库
193
+ // In production, this would write to a database
194
+ console.log(`[Ticket Created] ${ticketId}: ${input}`);
195
+
196
+ return `已创建工单 ${ticketId},客服团队将在2小时内联系您。\nTicket ${ticketId} created. Our team will contact you within 2 hours.`;
197
+ }
198
+ }
199
+ ```
200
+
201
+ ### Registering Skills
202
+
203
+ Skills listed in `agent.yaml` under `spec.skills` are auto-discovered from `src/skills/`. The agent matches incoming messages against `triggers` and routes to the appropriate skill.
204
+
205
+ ---
206
+
207
+ ## Chapter 4: Memory with DeepBrain
208
+
209
+ OPC Agent integrates with **DeepBrain** for persistent memory — enabling your agent to learn from past conversations.
210
+
211
+ ```typescript
212
+ // src/index.ts
213
+ import { Agent } from 'opc-agent';
214
+ import { Brain } from 'deepbrain';
215
+
216
+ // 初始化 DeepBrain / Initialize DeepBrain
217
+ const brain = new Brain({
218
+ database: './data/customer-brain.db',
219
+ embedding_provider: 'ollama',
220
+ });
221
+ await brain.connect();
222
+
223
+ const agent = new Agent('./agent.yaml');
224
+
225
+ // 存储对话用于学习 / Store conversations for learning
226
+ agent.on('message', async (msg, response) => {
227
+ await brain.put(
228
+ `conv-${msg.id}`,
229
+ `Q: ${msg.content}\nA: ${response.content}`
230
+ );
231
+ });
232
+
233
+ // 语义搜索历史对话 / Semantic search past conversations
234
+ agent.on('beforeReply', async (ctx) => {
235
+ const relevant = await brain.query(ctx.message, { limit: 3 });
236
+ if (relevant.length > 0) {
237
+ ctx.additionalContext = relevant.map(r => r.content).join('\n');
238
+ }
239
+ });
240
+
241
+ await agent.start();
242
+ ```
243
+
244
+ ### What DeepBrain Provides
245
+
246
+ - **Semantic search** — Find relevant past conversations by meaning, not just keywords
247
+ - **Persistent storage** — SQLite-based, survives restarts
248
+ - **Embedding support** — Works with Ollama, OpenAI, or Gemini embeddings
249
+
250
+ ---
251
+
252
+ ## Chapter 5: Channels
253
+
254
+ Channels define how users interact with your agent. OPC Agent supports multiple simultaneous channels.
255
+
256
+ ### Web (Built-in)
257
+
258
+ ```yaml
259
+ spec:
260
+ channels:
261
+ - type: web
262
+ port: 3000
263
+ ```
264
+
265
+ Launches a web chat UI at `http://localhost:3000`.
266
+
267
+ ### Telegram
268
+
269
+ ```yaml
270
+ spec:
271
+ channels:
272
+ - type: web
273
+ port: 3000
274
+ - type: telegram
275
+ token: ${TELEGRAM_BOT_TOKEN}
276
+ mode: polling
277
+ ```
278
+
279
+ Set the environment variable `TELEGRAM_BOT_TOKEN` from [@BotFather](https://t.me/BotFather).
280
+
281
+ ### Discord
282
+
283
+ ```yaml
284
+ spec:
285
+ channels:
286
+ - type: discord
287
+ token: ${DISCORD_BOT_TOKEN}
288
+ guildId: "your-server-id"
289
+ ```
290
+
291
+ ### Multi-Channel
292
+
293
+ All channels share the same agent logic, skills, and memory. A message from Telegram triggers the same FAQ skill as one from the web UI.
294
+
295
+ ---
296
+
297
+ ## Chapter 6: Workflow Engine
298
+
299
+ For multi-step interactions, use the **Workflow Engine** to define conversation flows with branching logic.
300
+
301
+ ```typescript
302
+ import { WorkflowBuilder } from 'opc-agent';
303
+
304
+ // 客户引导流程 / Customer Onboarding Workflow
305
+ const onboarding = new WorkflowBuilder()
306
+ .start('greet')
307
+ .addAction('greet', async (ctx) => {
308
+ return '欢迎!请问您是新客户还是老客户?\nWelcome! Are you a new or returning customer?';
309
+ }, { next: 'check-type' })
310
+ .addCondition('check-type',
311
+ (ctx) => ctx.variables.get('isNewCustomer'),
312
+ 'new-flow', // true 分支 / true branch
313
+ 'existing-flow' // false 分支 / false branch
314
+ )
315
+ .addAction('new-flow', async (ctx) => {
316
+ return '让我帮您注册账号。请提供您的邮箱地址。';
317
+ }, { next: 'collect-email' })
318
+ .addAction('collect-email', async (ctx) => {
319
+ const email = ctx.message;
320
+ ctx.variables.set('email', email);
321
+ return `注册成功!欢迎加入,${email}`;
322
+ }, { next: 'done' })
323
+ .addAction('existing-flow', async (ctx) => {
324
+ return '欢迎回来!有什么可以帮您?';
325
+ }, { next: 'done' })
326
+ .addAction('done', async () => 'Onboarding complete')
327
+ .build();
328
+
329
+ // 注册工作流 / Register the workflow
330
+ agent.registerWorkflow('onboarding', onboarding);
331
+ ```
332
+
333
+ ### Workflow Features
334
+
335
+ - **Branching** — Conditional paths based on user input or variables
336
+ - **State management** — `ctx.variables` persists across steps
337
+ - **Composable** — Workflows can trigger other workflows
338
+
339
+ ---
340
+
341
+ ## Chapter 7: Built-in Tools
342
+
343
+ OPC Agent comes with built-in tools that your agent can use autonomously.
344
+
345
+ ```typescript
346
+ import { getBuiltinTools } from 'opc-agent';
347
+
348
+ // 加载内置工具 / Load built-in tools
349
+ const tools = getBuiltinTools('./workspace');
350
+ ```
351
+
352
+ ### Available Tools
353
+
354
+ | Tool | Description |
355
+ |------|-------------|
356
+ | `readFile` | Read file contents |
357
+ | `writeFile` | Write/create files |
358
+ | `fetchUrl` | HTTP requests to external APIs |
359
+ | `runCommand` | Execute shell commands (sandboxed) |
360
+ | `getTime` | Current date/time |
361
+ | `listFiles` | Directory listing |
362
+
363
+ ### Example: Agent Uses Tools
364
+
365
+ ```typescript
366
+ // Agent can autonomously decide to use tools
367
+ // 例如查询订单状态时,agent 可以调用 API
368
+ const agent = new Agent('./agent.yaml', { tools });
369
+ ```
370
+
371
+ The agent decides which tools to invoke based on the user's request and the tool descriptions.
372
+
373
+ ---
374
+
375
+ ## Chapter 8: Sub-Agents
376
+
377
+ For complex tasks, spawn specialized sub-agents that work independently and report back.
378
+
379
+ ```typescript
380
+ import { SubAgentManager } from 'opc-agent';
381
+
382
+ const manager = new SubAgentManager();
383
+
384
+ // 委派研究任务给子 Agent / Delegate research to a sub-agent
385
+ const result = await agent.spawnSubAgent({
386
+ name: 'researcher',
387
+ task: 'Find the return policy for order #12345',
388
+ systemPrompt: 'You are a research specialist. Find accurate information.',
389
+ model: 'qwen2.5',
390
+ });
391
+
392
+ console.log(result.output); // Sub-agent's findings
393
+ ```
394
+
395
+ ### Sub-Agent Use Cases
396
+
397
+ - **Research** — Look up order details, policies, product info
398
+ - **Translation** — Translate customer messages
399
+ - **Analysis** — Analyze sentiment or categorize issues
400
+ - **Escalation** — Prepare summaries for human agents
401
+
402
+ ---
403
+
404
+ ## Chapter 9: Plugin System
405
+
406
+ Extend your agent with plugins for cross-cutting concerns.
407
+
408
+ ```typescript
409
+ import { loggerPlugin, rateLimiterPlugin } from 'opc-agent';
410
+
411
+ const agent = new Agent('./agent.yaml', {
412
+ plugins: [
413
+ // 日志插件 / Logger — logs all messages
414
+ loggerPlugin({ level: 'info', output: './logs/agent.log' }),
415
+
416
+ // 限流插件 / Rate limiter — prevent abuse
417
+ rateLimiterPlugin({ maxRequests: 60, windowMs: 60000 }),
418
+ ],
419
+ });
420
+ ```
421
+
422
+ ### Plugin Lifecycle Hooks
423
+
424
+ Plugins can hook into:
425
+ - `onMessage` — Before processing a message
426
+ - `onReply` — Before sending a reply
427
+ - `onError` — When an error occurs
428
+ - `onStart` / `onStop` — Agent lifecycle
429
+
430
+ ### Writing a Custom Plugin
431
+
432
+ ```typescript
433
+ import { Plugin } from 'opc-agent';
434
+
435
+ // 自定义插件示例 / Custom plugin example
436
+ export const metricsPlugin: Plugin = {
437
+ name: 'metrics',
438
+ onMessage: async (msg) => {
439
+ console.log(`[${new Date().toISOString()}] Received: ${msg.content.slice(0, 50)}`);
440
+ },
441
+ onReply: async (msg, reply) => {
442
+ console.log(`[${new Date().toISOString()}] Replied in ${reply.latencyMs}ms`);
443
+ },
444
+ };
445
+ ```
446
+
447
+ ---
448
+
449
+ ## Chapter 10: Scheduled Jobs
450
+
451
+ Run tasks on a schedule using cron syntax.
452
+
453
+ ```yaml
454
+ # agent.yaml
455
+ spec:
456
+ scheduler:
457
+ jobs:
458
+ - name: daily-report
459
+ schedule: "0 9 * * *" # 每天早上9点 / Daily at 9 AM
460
+ task: "Generate daily customer service report"
461
+
462
+ - name: cleanup-old-tickets
463
+ schedule: "0 2 * * 0" # 每周日凌晨2点 / Sunday 2 AM
464
+ task: "Archive tickets older than 30 days"
465
+
466
+ - name: health-check
467
+ schedule: "*/15 * * * *" # 每15分钟 / Every 15 minutes
468
+ task: "Check all channel connections are alive"
469
+ ```
470
+
471
+ ### Managing Jobs
472
+
473
+ ```bash
474
+ # 查看所有任务 / List all scheduled jobs
475
+ opc jobs list
476
+
477
+ # 手动触发 / Manually trigger a job
478
+ opc jobs run daily-report
479
+
480
+ # 查看历史 / View job history
481
+ opc jobs history
482
+ ```
483
+
484
+ ---
485
+
486
+ ## Chapter 11: Security
487
+
488
+ OPC Agent provides multiple security layers.
489
+
490
+ ```yaml
491
+ spec:
492
+ security:
493
+ # 危险操作需要审批 / Dangerous actions require approval
494
+ approval: dangerous
495
+
496
+ # 沙箱限制 / Sandbox constraints
497
+ sandbox:
498
+ maxFileSize: 10485760 # 10MB max file size
499
+ allowedCommands: # Whitelist commands
500
+ - "curl"
501
+ - "node"
502
+ blockedPaths: # Protect sensitive paths
503
+ - "/etc"
504
+ - "~/.ssh"
505
+ ```
506
+
507
+ ### Security Features
508
+
509
+ | Feature | Description |
510
+ |---------|-------------|
511
+ | **Approval mode** | `dangerous` ops need human approval |
512
+ | **Sandbox** | File size limits, command whitelist |
513
+ | **Path blocking** | Prevent access to sensitive directories |
514
+ | **Rate limiting** | Via plugin (Chapter 9) |
515
+ | **Token rotation** | Channel tokens via env vars, not hardcoded |
516
+
517
+ ### Best Practices
518
+
519
+ - Never hardcode API keys — use `${ENV_VAR}` syntax in `agent.yaml`
520
+ - Enable `approval: dangerous` in production
521
+ - Set `maxFileSize` to prevent resource exhaustion
522
+ - Use `allowedCommands` to restrict what the agent can execute
523
+
524
+ ---
525
+
526
+ ## Chapter 12: Packaging & Publishing
527
+
528
+ Share your agent with others via the OPC registry.
529
+
530
+ ```bash
531
+ # 预览打包内容 / Preview what will be packaged
532
+ opc pack --list
533
+
534
+ # 试运行发布 / Dry run — see what would happen
535
+ opc publish --dry-run
536
+
537
+ # 正式发布 / Publish to the registry
538
+ opc publish
539
+ ```
540
+
541
+ ### What Gets Packaged
542
+
543
+ - `agent.yaml` — Configuration
544
+ - `SOUL.md` — Personality
545
+ - `src/` — Skills and logic
546
+ - `package.json` — Dependencies
547
+
548
+ ### Versioning
549
+
550
+ Follow semver in `metadata.version`. Bump before each publish:
551
+
552
+ ```bash
553
+ # Update version in agent.yaml
554
+ # metadata:
555
+ # version: 1.1.0
556
+ opc publish
557
+ ```
558
+
559
+ ---
560
+
561
+ ## Chapter 13: Monitoring & Analytics
562
+
563
+ ### Running Your Agent
564
+
565
+ ```bash
566
+ # 开发模式 / Development — interactive CLI chat
567
+ opc chat
568
+
569
+ # 服务模式 / Server — starts web server + all channels
570
+ opc run
571
+
572
+ # 生产模式 / Production — runs as daemon
573
+ opc start
574
+
575
+ # 检查状态 / Check status
576
+ opc status
577
+
578
+ # 查看日志 / View logs
579
+ opc logs --tail 100
580
+
581
+ # 停止 / Stop
582
+ opc stop
583
+ ```
584
+
585
+ ### Monitoring
586
+
587
+ - **`opc status`** — Shows agent health, active channels, memory usage
588
+ - **`opc jobs list`** — Cron job status and next run times
589
+ - **Logs** — Structured JSON logs for integration with ELK, Grafana, etc.
590
+ - **Metrics plugin** — Custom metrics (see Chapter 9)
591
+
592
+ ### Production Checklist
593
+
594
+ - [ ] Set `approval: dangerous` in security config
595
+ - [ ] Configure all channel tokens via environment variables
596
+ - [ ] Enable logging plugin with file output
597
+ - [ ] Set up cron jobs for maintenance tasks
598
+ - [ ] Test all skills with edge cases
599
+ - [ ] Run `opc doctor` to verify environment
600
+ - [ ] Use `opc start` (daemon mode) instead of `opc run`
601
+
602
+ ---
603
+
604
+ ## Next Steps
605
+
606
+ - 📖 Read the [OPC Agent Documentation](https://github.com/Deepleaper/opc-agent)
607
+ - 🧩 Explore community skills on the OPC registry
608
+ - 🤝 Join the community on Discord/Telegram
609
+
610
+ ---
611
+
612
+ *Built with ❤️ using [OPC Agent](https://github.com/Deepleaper/opc-agent)*