opc-agent 4.1.1 → 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.
@@ -74,25 +74,39 @@ class AgentRuntime {
74
74
  evolveScheduler = null;
75
75
  async loadConfig(filePath) {
76
76
  const fs = require('fs');
77
+ const path = require('path');
78
+ // 如果指定文件不存在,尝试 fallback
77
79
  if (!fs.existsSync(filePath)) {
78
- // Auto-create a minimal oad.yaml with auto-detect provider
79
- const yaml = require('js-yaml');
80
- const defaultOAD = {
81
- apiVersion: 'opc/v1',
82
- kind: 'Agent',
83
- metadata: { name: 'my-agent', version: '1.0.0', description: 'OPC Agent' },
84
- spec: {
85
- model: 'auto',
86
- provider: { default: 'auto' },
87
- systemPrompt: 'You are a helpful AI assistant.',
88
- channels: [{ type: 'web', config: { port: 3000 } }],
89
- },
90
- };
91
- fs.writeFileSync(filePath, yaml.dump(defaultOAD, { lineWidth: 120 }));
92
- this.logger.info('Created default oad.yaml (no config file found)');
80
+ // 如果发现旧的 agent.yaml,提示迁移
81
+ if (filePath === 'oad.yaml' && fs.existsSync('agent.yaml')) {
82
+ this.logger.warn('⚠️ 发现 agent.yaml 但未找到 oad.yaml。建议运行 `opc migrate` 统一为 oad.yaml。');
83
+ this.logger.info('暂时使用 agent.yaml 加载配置...');
84
+ filePath = 'agent.yaml';
85
+ }
86
+ else {
87
+ // Auto-create a minimal oad.yaml with auto-detect provider
88
+ const yaml = require('js-yaml');
89
+ const defaultOAD = {
90
+ apiVersion: 'opc/v1',
91
+ kind: 'Agent',
92
+ metadata: { name: 'my-agent', version: '1.0.0', description: 'OPC Agent' },
93
+ spec: {
94
+ model: 'auto',
95
+ provider: { default: 'auto' },
96
+ systemPrompt: 'You are a helpful AI assistant.',
97
+ channels: [{ type: 'web', config: { port: 3000 } }],
98
+ },
99
+ };
100
+ fs.writeFileSync(filePath, yaml.dump(defaultOAD, { lineWidth: 120 }));
101
+ this.logger.info('Created default oad.yaml (no config file found)');
102
+ }
93
103
  }
94
104
  this.config = (0, config_1.loadOAD)(filePath);
95
105
  this.logger.info('Config loaded', { name: this.config.metadata.name });
106
+ // 如果同时存在 agent.yaml 和 oad.yaml,提示用户清理
107
+ if (fs.existsSync('agent.yaml') && fs.existsSync('oad.yaml')) {
108
+ this.logger.warn('⚠️ 同时存在 agent.yaml 和 oad.yaml。建议删除 agent.yaml,统一使用 oad.yaml。');
109
+ }
96
110
  return this.config;
97
111
  }
98
112
  setHistoryLimit(limit) {
@@ -128,6 +142,14 @@ class AgentRuntime {
128
142
  const cfg = config ?? this.config;
129
143
  if (!cfg)
130
144
  throw new Error('No config loaded. Call loadConfig() first.');
145
+ // 检查 API key 是否为占位符,启动时警告
146
+ const apiKey = process.env.OPC_LLM_API_KEY;
147
+ const cfgProvider = cfg.spec.provider?.default;
148
+ if (cfgProvider !== 'ollama' && cfgProvider !== 'auto') {
149
+ if (!apiKey || apiKey === 'your-api-key-here') {
150
+ this.logger.warn('⚠️ API Key 未配置或仍是占位符。请编辑 .env 文件设置 OPC_LLM_API_KEY。');
151
+ }
152
+ }
131
153
  let memory;
132
154
  const memCfg = cfg.spec.memory;
133
155
  if (memCfg && typeof memCfg.longTerm === 'object' && memCfg.longTerm.provider === 'deepbrain') {
package/dist/doctor.d.ts CHANGED
@@ -2,6 +2,7 @@ export interface CheckResult {
2
2
  ok: boolean;
3
3
  detail: string;
4
4
  fix?: string;
5
+ optional?: boolean;
5
6
  }
6
7
  export interface DoctorCheck {
7
8
  name: string;
package/dist/doctor.js CHANGED
@@ -38,6 +38,41 @@ exports.runDoctor = runDoctor;
38
38
  const child_process_1 = require("child_process");
39
39
  const fs_1 = require("fs");
40
40
  const net = __importStar(require("net"));
41
+ const yaml = __importStar(require("js-yaml"));
42
+ /** 读取 .env 文件并解析为 key-value */
43
+ function loadEnvFile() {
44
+ const envPath = '.env';
45
+ if (!(0, fs_1.existsSync)(envPath))
46
+ return {};
47
+ const result = {};
48
+ try {
49
+ const content = (0, fs_1.readFileSync)(envPath, 'utf-8');
50
+ for (const line of content.split('\n')) {
51
+ const trimmed = line.trim();
52
+ if (!trimmed || trimmed.startsWith('#'))
53
+ continue;
54
+ const eqIdx = trimmed.indexOf('=');
55
+ if (eqIdx === -1)
56
+ continue;
57
+ result[trimmed.slice(0, eqIdx).trim()] = trimmed.slice(eqIdx + 1).trim();
58
+ }
59
+ }
60
+ catch { /* ignore */ }
61
+ return result;
62
+ }
63
+ /** 从 oad.yaml 读取 provider 配置 */
64
+ function loadOadProvider() {
65
+ for (const f of ['oad.yaml', 'agent.yaml']) {
66
+ if ((0, fs_1.existsSync)(f)) {
67
+ try {
68
+ const cfg = yaml.load((0, fs_1.readFileSync)(f, 'utf-8'));
69
+ return cfg?.spec?.provider?.default;
70
+ }
71
+ catch { /* ignore */ }
72
+ }
73
+ }
74
+ return undefined;
75
+ }
41
76
  function getDoctorChecks() {
42
77
  return [
43
78
  {
@@ -64,6 +99,7 @@ function getDoctorChecks() {
64
99
  },
65
100
  },
66
101
  {
102
+ // Ollama 是可选的(只有选了 ollama provider 才需要)
67
103
  name: 'Ollama running',
68
104
  check: async () => {
69
105
  try {
@@ -75,15 +111,22 @@ function getDoctorChecks() {
75
111
  return { ok: true, detail: `${data.models?.length || 0} models available` };
76
112
  }
77
113
  catch {
78
- return { ok: false, detail: 'Not running', fix: 'Install Ollama: https://ollama.ai' };
114
+ return { ok: false, detail: 'Not running', fix: 'Install Ollama: https://ollama.ai (optional, only needed for local models)', optional: true };
79
115
  }
80
116
  },
81
117
  },
82
118
  {
83
- name: 'agent.yaml exists',
119
+ // 检查 oad.yaml 而不是 agent.yaml
120
+ name: 'oad.yaml exists',
84
121
  check: () => {
85
- const found = (0, fs_1.existsSync)('./agent.yaml');
86
- return { ok: found, detail: found ? 'Found' : 'Not found', fix: found ? undefined : 'Run `opc init` to create a project' };
122
+ const found = (0, fs_1.existsSync)('./oad.yaml');
123
+ if (found)
124
+ return { ok: true, detail: 'Found' };
125
+ // 检查是否有旧的 agent.yaml 需要迁移
126
+ if ((0, fs_1.existsSync)('./agent.yaml')) {
127
+ return { ok: false, detail: 'Not found (found agent.yaml)', fix: 'Run `opc migrate` to migrate agent.yaml → oad.yaml' };
128
+ }
129
+ return { ok: false, detail: 'Not found', fix: 'Run `opc init` to create a project' };
87
130
  },
88
131
  },
89
132
  {
@@ -94,6 +137,7 @@ function getDoctorChecks() {
94
137
  },
95
138
  },
96
139
  {
140
+ // TypeScript 是可选的
97
141
  name: 'TypeScript installed',
98
142
  check: () => {
99
143
  try {
@@ -101,7 +145,7 @@ function getDoctorChecks() {
101
145
  return { ok: true, detail: 'Available' };
102
146
  }
103
147
  catch {
104
- return { ok: false, detail: 'Not found', fix: 'npm install -D typescript' };
148
+ return { ok: false, detail: 'Not found', fix: 'npm install -D typescript (optional)', optional: true };
105
149
  }
106
150
  },
107
151
  },
@@ -112,6 +156,7 @@ function getDoctorChecks() {
112
156
  },
113
157
  },
114
158
  {
159
+ // DeepBrain 是可选的
115
160
  name: 'DeepBrain package',
116
161
  check: () => {
117
162
  try {
@@ -119,7 +164,7 @@ function getDoctorChecks() {
119
164
  return { ok: true, detail: 'Installed' };
120
165
  }
121
166
  catch {
122
- return { ok: false, detail: 'Not installed', fix: 'npm install deepbrain' };
167
+ return { ok: false, detail: 'Not installed', fix: 'npm install deepbrain (optional, for long-term memory)', optional: true };
123
168
  }
124
169
  },
125
170
  },
@@ -140,6 +185,53 @@ function getDoctorChecks() {
140
185
  });
141
186
  },
142
187
  },
188
+ {
189
+ // 检查 API key 是否配置(不是占位符)
190
+ name: 'API key configured',
191
+ check: () => {
192
+ const env = loadEnvFile();
193
+ const apiKey = env['OPC_LLM_API_KEY'] || '';
194
+ const oadProvider = loadOadProvider();
195
+ // Ollama 不需要 API key
196
+ if (oadProvider === 'ollama') {
197
+ return { ok: true, detail: 'Not required (Ollama provider)' };
198
+ }
199
+ if (!apiKey || apiKey === 'your-api-key-here') {
200
+ return { ok: false, detail: 'Not configured or still placeholder', fix: 'Edit .env and set OPC_LLM_API_KEY to your actual API key' };
201
+ }
202
+ return { ok: true, detail: 'Configured' };
203
+ },
204
+ },
205
+ {
206
+ // 检查 .env 和 oad.yaml 的 provider 是否匹配
207
+ name: 'Provider consistency',
208
+ check: () => {
209
+ const env = loadEnvFile();
210
+ const baseUrl = env['OPC_LLM_BASE_URL'] || '';
211
+ const oadProvider = loadOadProvider();
212
+ if (!oadProvider || !baseUrl) {
213
+ return { ok: true, detail: 'N/A (no config to compare)' };
214
+ }
215
+ // 检测 .env 的 base URL 暗示的 provider
216
+ let envProvider = 'unknown';
217
+ if (baseUrl.includes('openai.com'))
218
+ envProvider = 'openai';
219
+ else if (baseUrl.includes('deepseek.com'))
220
+ envProvider = 'deepseek';
221
+ else if (baseUrl.includes('localhost:11434'))
222
+ envProvider = 'ollama';
223
+ else if (baseUrl.includes('anthropic.com'))
224
+ envProvider = 'anthropic';
225
+ else if (baseUrl.includes('dashscope.aliyuncs.com'))
226
+ envProvider = 'qwen';
227
+ if (envProvider === 'unknown')
228
+ return { ok: true, detail: `Custom base URL (${oadProvider})` };
229
+ if (envProvider !== oadProvider && oadProvider !== 'auto') {
230
+ return { ok: false, detail: `Mismatch: .env → ${envProvider}, oad.yaml → ${oadProvider}`, fix: 'Update .env or oad.yaml to use the same provider' };
231
+ }
232
+ return { ok: true, detail: `Matched: ${oadProvider}` };
233
+ },
234
+ },
143
235
  ];
144
236
  }
145
237
  async function runDoctor() {
@@ -147,6 +239,7 @@ async function runDoctor() {
147
239
  const color = {
148
240
  green: (s) => `\x1b[32m${s}\x1b[0m`,
149
241
  red: (s) => `\x1b[31m${s}\x1b[0m`,
242
+ yellow: (s) => `\x1b[33m${s}\x1b[0m`,
150
243
  dim: (s) => `\x1b[2m${s}\x1b[0m`,
151
244
  bold: (s) => `\x1b[1m${s}\x1b[0m`,
152
245
  };
@@ -156,17 +249,19 @@ async function runDoctor() {
156
249
  for (const check of checks) {
157
250
  try {
158
251
  const result = await check.check();
159
- const icon = result.ok ? color.green('✅') : color.red('');
160
- const name = check.name.padEnd(22);
252
+ // optional 项失败显示 ⚠️ 而不是
253
+ const icon = result.ok ? color.green('✅') : (result.optional ? color.yellow('⚠️') : color.red('❌'));
254
+ const name = check.name.padEnd(24);
161
255
  console.log(` ${icon} ${name} ${result.detail}`);
162
256
  if (!result.ok && result.fix) {
163
257
  console.log(` → ${result.fix}`);
164
258
  }
165
- if (result.ok)
259
+ // optional 项即使失败也算 passed
260
+ if (result.ok || result.optional)
166
261
  passed++;
167
262
  }
168
263
  catch (err) {
169
- const name = check.name.padEnd(22);
264
+ const name = check.name.padEnd(24);
170
265
  console.log(` ${color.red('❌')} ${name} Error: ${err instanceof Error ? err.message : String(err)}`);
171
266
  }
172
267
  }
@@ -1,7 +1,7 @@
1
1
  import type { Message, MemoryStore } from '../core/types';
2
2
  /**
3
3
  * DeepBrain-backed memory store for long-term semantic memory.
4
- * Falls back to InMemoryStore if deepbrain package is not installed.
4
+ * Falls back to local JSON file storage (.opc/memory.json) if deepbrain package is not installed.
5
5
  */
6
6
  export interface DeepBrainClient {
7
7
  store(collection: string, id: string, content: string, metadata?: Record<string, unknown>): Promise<void>;
@@ -34,14 +34,105 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.DeepBrainMemoryStore = void 0;
37
- const index_1 = require("./index");
37
+ const fs_1 = require("fs");
38
+ const path_1 = require("path");
39
+ /**
40
+ * 本地 JSON 文件持久化存储,作为 DeepBrain 不可用时的 fallback。
41
+ * 数据保存在 .opc/memory.json,进程重启后记忆不会丢失。
42
+ */
43
+ class FileBackedStore {
44
+ store = new Map();
45
+ conversations = new Map();
46
+ filePath;
47
+ dirty = false;
48
+ saveTimer = null;
49
+ constructor(baseDir = '.') {
50
+ const opcDir = (0, path_1.join)((0, path_1.resolve)(baseDir), '.opc');
51
+ if (!(0, fs_1.existsSync)(opcDir))
52
+ (0, fs_1.mkdirSync)(opcDir, { recursive: true });
53
+ this.filePath = (0, path_1.join)(opcDir, 'memory.json');
54
+ this.loadFromFile();
55
+ }
56
+ loadFromFile() {
57
+ if (!(0, fs_1.existsSync)(this.filePath))
58
+ return;
59
+ try {
60
+ const data = JSON.parse((0, fs_1.readFileSync)(this.filePath, 'utf-8'));
61
+ if (data.store) {
62
+ for (const [k, v] of Object.entries(data.store)) {
63
+ this.store.set(k, v);
64
+ }
65
+ }
66
+ if (data.conversations) {
67
+ for (const [k, v] of Object.entries(data.conversations)) {
68
+ this.conversations.set(k, v);
69
+ }
70
+ }
71
+ }
72
+ catch { /* 文件损坏则忽略,从空开始 */ }
73
+ }
74
+ scheduleSave() {
75
+ this.dirty = true;
76
+ if (this.saveTimer)
77
+ return; // 已经有定时器在等了
78
+ // 延迟 1 秒批量写入,避免高频写磁盘
79
+ this.saveTimer = setTimeout(() => {
80
+ this.saveTimer = null;
81
+ if (this.dirty)
82
+ this.saveToFile();
83
+ }, 1000);
84
+ }
85
+ saveToFile() {
86
+ try {
87
+ const data = {
88
+ store: Object.fromEntries(this.store),
89
+ conversations: Object.fromEntries(this.conversations),
90
+ updatedAt: new Date().toISOString(),
91
+ };
92
+ (0, fs_1.writeFileSync)(this.filePath, JSON.stringify(data, null, 2));
93
+ this.dirty = false;
94
+ }
95
+ catch { /* 写入失败不影响运行 */ }
96
+ }
97
+ async get(key) {
98
+ return this.store.get(key);
99
+ }
100
+ async set(key, value) {
101
+ this.store.set(key, value);
102
+ this.scheduleSave();
103
+ }
104
+ async getConversation(sessionId) {
105
+ return this.conversations.get(sessionId) ?? [];
106
+ }
107
+ async addMessage(sessionId, message) {
108
+ if (!this.conversations.has(sessionId)) {
109
+ this.conversations.set(sessionId, []);
110
+ }
111
+ const conv = this.conversations.get(sessionId);
112
+ conv.push(message);
113
+ // 每个 session 最多保留 200 条消息,避免文件无限增长
114
+ if (conv.length > 200)
115
+ conv.splice(0, conv.length - 200);
116
+ this.scheduleSave();
117
+ }
118
+ async clear(sessionId) {
119
+ if (sessionId) {
120
+ this.conversations.delete(sessionId);
121
+ }
122
+ else {
123
+ this.store.clear();
124
+ this.conversations.clear();
125
+ }
126
+ this.scheduleSave();
127
+ }
128
+ }
38
129
  class DeepBrainMemoryStore {
39
130
  fallback;
40
131
  client = null;
41
132
  collection;
42
133
  ready;
43
134
  constructor(options = {}) {
44
- this.fallback = new index_1.InMemoryStore();
135
+ this.fallback = new FileBackedStore();
45
136
  this.collection = options.collection ?? 'agent-memory';
46
137
  this.ready = this.initClient(options.config);
47
138
  }
@@ -51,13 +142,13 @@ class DeepBrainMemoryStore {
51
142
  const deepbrain = await Promise.resolve().then(() => __importStar(require(/* webpackIgnore: true */ 'deepbrain')));
52
143
  this.client = deepbrain.createClient?.(config) ?? deepbrain.default?.createClient?.(config);
53
144
  if (!this.client) {
54
- console.warn('[DeepBrainMemory] Could not create client, using in-memory fallback');
145
+ console.warn('[DeepBrainMemory] Could not create client, using file-backed fallback (.opc/memory.json)');
55
146
  return false;
56
147
  }
57
148
  return true;
58
149
  }
59
150
  catch {
60
- console.warn('[DeepBrainMemory] deepbrain package not found, using in-memory fallback');
151
+ console.warn('[DeepBrainMemory] deepbrain package not found, using file-backed fallback (.opc/memory.json)');
61
152
  return false;
62
153
  }
63
154
  }
@@ -4,48 +4,15 @@
4
4
  * Manages scheduled tasks with cron expressions, persists to ~/.opc/schedules.json,
5
5
  * and auto-recovers on startup.
6
6
  */
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- var desc = Object.getOwnPropertyDescriptor(m, k);
10
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
- desc = { enumerable: true, get: function() { return m[k]; } };
12
- }
13
- Object.defineProperty(o, k2, desc);
14
- }) : (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- }));
18
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
- Object.defineProperty(o, "default", { enumerable: true, value: v });
20
- }) : function(o, v) {
21
- o["default"] = v;
22
- });
23
- var __importStar = (this && this.__importStar) || (function () {
24
- var ownKeys = function(o) {
25
- ownKeys = Object.getOwnPropertyNames || function (o) {
26
- var ar = [];
27
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
- return ar;
29
- };
30
- return ownKeys(o);
31
- };
32
- return function (mod) {
33
- if (mod && mod.__esModule) return mod;
34
- var result = {};
35
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
- __setModuleDefault(result, mod);
37
- return result;
38
- };
39
- })();
40
7
  Object.defineProperty(exports, "__esModule", { value: true });
41
8
  exports.CronEngine = void 0;
42
9
  exports.frequencyToCron = frequencyToCron;
43
10
  const fs_1 = require("fs");
44
11
  const path_1 = require("path");
45
- const os = __importStar(require("os"));
46
12
  const scheduler_1 = require("../core/scheduler");
47
- function getSchedulesPath() {
48
- const dir = (0, path_1.join)(os.homedir(), '.opc');
13
+ function getSchedulesPath(projectDir) {
14
+ // 使用项目本地路径而不是全局 ~/.opc/,避免新 agent 加载其他项目的任务
15
+ const dir = projectDir ? (0, path_1.join)(projectDir, '.opc') : (0, path_1.join)(process.cwd(), '.opc');
49
16
  if (!(0, fs_1.existsSync)(dir))
50
17
  (0, fs_1.mkdirSync)(dir, { recursive: true });
51
18
  return (0, path_1.join)(dir, 'schedules.json');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opc-agent",
3
- "version": "4.1.1",
3
+ "version": "4.1.2",
4
4
  "description": "Open Agent Framework — Build, test, and run AI Agents for business workstations",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -211,7 +211,7 @@ async function send(){
211
211
  for(const line of lines){
212
212
  if(!line.startsWith('data: '))continue;
213
213
  const dd=line.slice(6);if(dd==='[DONE]')continue;
214
- try{const j=JSON.parse(dd);if(j.content)full+=j.content;if(j.error)full='Error: '+j.error;}catch{}
214
+ try{const j=JSON.parse(dd);if(j.content)full+=j.content;if(j.error){if(j.error.includes('401')||j.error.toLowerCase().includes('api key')||j.error.toLowerCase().includes('unauthorized')){full='⚠️ 请先配置 API Key。编辑项目根目录的 .env 文件,设置 OPC_LLM_API_KEY。';}else{full='Error: '+j.error;}}}catch{}
215
215
  }
216
216
  d.innerHTML=renderMd(full)+'<span class="cursor"></span>';
217
217
  msgs.scrollTop=msgs.scrollHeight;
@@ -220,7 +220,13 @@ async function send(){
220
220
  const rx=document.createElement('div');rx.className='reactions';
221
221
  rx.innerHTML='<button data-r="👍" onclick="react(this)">👍</button><button data-r="👎" onclick="react(this)">👎</button>';
222
222
  wrap.appendChild(rx);
223
- }catch(e){d.className='msg error';d.textContent='Error: '+e.message;}
223
+ }catch(e){
224
+ d.className='msg error';
225
+ const errMsg=e.message||'';
226
+ if(errMsg.includes('401')||errMsg.includes('HTTP 401')){
227
+ d.innerHTML='⚠️ <b>请先配置 API Key</b><br>编辑项目根目录的 <code>.env</code> 文件,设置 <code>OPC_LLM_API_KEY</code> 为你的实际 API Key。';
228
+ }else{d.textContent='Error: '+errMsg;}
229
+ }
224
230
  sending=false;btn.disabled=false;input.focus();
225
231
  }
226
232