opc-agent 1.4.0 → 2.0.1

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 (198) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +91 -32
  3. package/dist/channels/email.d.ts +32 -26
  4. package/dist/channels/email.js +239 -62
  5. package/dist/channels/feishu.d.ts +21 -6
  6. package/dist/channels/feishu.js +225 -126
  7. package/dist/channels/telegram.d.ts +30 -9
  8. package/dist/channels/telegram.js +125 -33
  9. package/dist/channels/websocket.d.ts +46 -3
  10. package/dist/channels/websocket.js +306 -37
  11. package/dist/channels/wechat.d.ts +33 -13
  12. package/dist/channels/wechat.js +229 -42
  13. package/dist/cli.js +1127 -19
  14. package/dist/core/a2a.d.ts +17 -0
  15. package/dist/core/a2a.js +43 -1
  16. package/dist/core/agent.d.ts +39 -0
  17. package/dist/core/agent.js +228 -3
  18. package/dist/core/runtime.d.ts +7 -0
  19. package/dist/core/runtime.js +205 -2
  20. package/dist/core/sandbox.d.ts +26 -0
  21. package/dist/core/sandbox.js +117 -0
  22. package/dist/core/scheduler.d.ts +52 -0
  23. package/dist/core/scheduler.js +168 -0
  24. package/dist/core/subagent.d.ts +28 -0
  25. package/dist/core/subagent.js +65 -0
  26. package/dist/core/workflow-graph.d.ts +93 -0
  27. package/dist/core/workflow-graph.js +247 -0
  28. package/dist/daemon.d.ts +3 -0
  29. package/dist/daemon.js +134 -0
  30. package/dist/doctor.d.ts +15 -0
  31. package/dist/doctor.js +183 -0
  32. package/dist/eval/index.d.ts +65 -0
  33. package/dist/eval/index.js +191 -0
  34. package/dist/index.d.ts +37 -6
  35. package/dist/index.js +75 -3
  36. package/dist/plugins/content-filter.d.ts +7 -0
  37. package/dist/plugins/content-filter.js +25 -0
  38. package/dist/plugins/index.d.ts +42 -0
  39. package/dist/plugins/index.js +108 -2
  40. package/dist/plugins/logger.d.ts +6 -0
  41. package/dist/plugins/logger.js +20 -0
  42. package/dist/plugins/rate-limiter.d.ts +7 -0
  43. package/dist/plugins/rate-limiter.js +35 -0
  44. package/dist/protocols/a2a/client.d.ts +25 -0
  45. package/dist/protocols/a2a/client.js +115 -0
  46. package/dist/protocols/a2a/index.d.ts +6 -0
  47. package/dist/protocols/a2a/index.js +12 -0
  48. package/dist/protocols/a2a/server.d.ts +41 -0
  49. package/dist/protocols/a2a/server.js +295 -0
  50. package/dist/protocols/a2a/types.d.ts +91 -0
  51. package/dist/protocols/a2a/types.js +15 -0
  52. package/dist/protocols/a2a/utils.d.ts +6 -0
  53. package/dist/protocols/a2a/utils.js +47 -0
  54. package/dist/protocols/agui/client.d.ts +10 -0
  55. package/dist/protocols/agui/client.js +75 -0
  56. package/dist/protocols/agui/index.d.ts +4 -0
  57. package/dist/protocols/agui/index.js +25 -0
  58. package/dist/protocols/agui/server.d.ts +37 -0
  59. package/dist/protocols/agui/server.js +191 -0
  60. package/dist/protocols/agui/types.d.ts +107 -0
  61. package/dist/protocols/agui/types.js +17 -0
  62. package/dist/protocols/index.d.ts +2 -0
  63. package/dist/protocols/index.js +19 -0
  64. package/dist/protocols/mcp/agent-tools.d.ts +11 -0
  65. package/dist/protocols/mcp/agent-tools.js +129 -0
  66. package/dist/protocols/mcp/index.d.ts +5 -0
  67. package/dist/protocols/mcp/index.js +11 -0
  68. package/dist/protocols/mcp/server.d.ts +31 -0
  69. package/dist/protocols/mcp/server.js +248 -0
  70. package/dist/protocols/mcp/types.d.ts +92 -0
  71. package/dist/protocols/mcp/types.js +17 -0
  72. package/dist/providers/index.d.ts +5 -1
  73. package/dist/providers/index.js +16 -9
  74. package/dist/publish/index.d.ts +45 -0
  75. package/dist/publish/index.js +350 -0
  76. package/dist/schema/oad.d.ts +859 -67
  77. package/dist/schema/oad.js +47 -3
  78. package/dist/security/approval.d.ts +36 -0
  79. package/dist/security/approval.js +113 -0
  80. package/dist/security/index.d.ts +4 -0
  81. package/dist/security/index.js +8 -0
  82. package/dist/security/keys.d.ts +16 -0
  83. package/dist/security/keys.js +117 -0
  84. package/dist/skills/auto-learn.d.ts +28 -0
  85. package/dist/skills/auto-learn.js +257 -0
  86. package/dist/studio/server.d.ts +63 -0
  87. package/dist/studio/server.js +625 -0
  88. package/dist/studio-ui/index.html +662 -0
  89. package/dist/telemetry/index.d.ts +93 -0
  90. package/dist/telemetry/index.js +285 -0
  91. package/dist/tools/builtin/datetime.d.ts +3 -0
  92. package/dist/tools/builtin/datetime.js +44 -0
  93. package/dist/tools/builtin/file.d.ts +3 -0
  94. package/dist/tools/builtin/file.js +151 -0
  95. package/dist/tools/builtin/index.d.ts +15 -0
  96. package/dist/tools/builtin/index.js +30 -0
  97. package/dist/tools/builtin/shell.d.ts +3 -0
  98. package/dist/tools/builtin/shell.js +43 -0
  99. package/dist/tools/builtin/web.d.ts +3 -0
  100. package/dist/tools/builtin/web.js +37 -0
  101. package/dist/tools/mcp-client.d.ts +24 -0
  102. package/dist/tools/mcp-client.js +119 -0
  103. package/package.json +5 -3
  104. package/scripts/install.ps1 +31 -0
  105. package/scripts/install.sh +40 -0
  106. package/src/channels/email.ts +351 -177
  107. package/src/channels/feishu.ts +349 -236
  108. package/src/channels/telegram.ts +212 -90
  109. package/src/channels/websocket.ts +399 -87
  110. package/src/channels/wechat.ts +329 -149
  111. package/src/cli.ts +1201 -20
  112. package/src/core/a2a.ts +60 -0
  113. package/src/core/agent.ts +420 -152
  114. package/src/core/runtime.ts +174 -0
  115. package/src/core/sandbox.ts +143 -0
  116. package/src/core/scheduler.ts +187 -0
  117. package/src/core/subagent.ts +98 -0
  118. package/src/core/workflow-graph.ts +365 -0
  119. package/src/daemon.ts +96 -0
  120. package/src/doctor.ts +156 -0
  121. package/src/eval/index.ts +211 -0
  122. package/src/eval/suites/basic.json +16 -0
  123. package/src/eval/suites/memory.json +12 -0
  124. package/src/eval/suites/safety.json +14 -0
  125. package/src/index.ts +65 -6
  126. package/src/plugins/content-filter.ts +23 -0
  127. package/src/plugins/index.ts +133 -2
  128. package/src/plugins/logger.ts +18 -0
  129. package/src/plugins/rate-limiter.ts +38 -0
  130. package/src/protocols/a2a/client.ts +132 -0
  131. package/src/protocols/a2a/index.ts +8 -0
  132. package/src/protocols/a2a/server.ts +333 -0
  133. package/src/protocols/a2a/types.ts +88 -0
  134. package/src/protocols/a2a/utils.ts +50 -0
  135. package/src/protocols/agui/client.ts +83 -0
  136. package/src/protocols/agui/index.ts +4 -0
  137. package/src/protocols/agui/server.ts +218 -0
  138. package/src/protocols/agui/types.ts +153 -0
  139. package/src/protocols/index.ts +2 -0
  140. package/src/protocols/mcp/agent-tools.ts +134 -0
  141. package/src/protocols/mcp/index.ts +8 -0
  142. package/src/protocols/mcp/server.ts +262 -0
  143. package/src/protocols/mcp/types.ts +69 -0
  144. package/src/providers/index.ts +354 -339
  145. package/src/publish/index.ts +376 -0
  146. package/src/schema/oad.ts +204 -154
  147. package/src/security/approval.ts +131 -0
  148. package/src/security/index.ts +3 -0
  149. package/src/security/keys.ts +87 -0
  150. package/src/skills/auto-learn.ts +262 -0
  151. package/src/studio/server.ts +629 -0
  152. package/src/studio-ui/index.html +662 -0
  153. package/src/telemetry/index.ts +324 -0
  154. package/src/tools/builtin/datetime.ts +41 -0
  155. package/src/tools/builtin/file.ts +107 -0
  156. package/src/tools/builtin/index.ts +28 -0
  157. package/src/tools/builtin/shell.ts +43 -0
  158. package/src/tools/builtin/web.ts +35 -0
  159. package/src/tools/mcp-client.ts +131 -0
  160. package/src/types/agent-workstation.d.ts +2 -0
  161. package/tests/a2a-protocol.test.ts +285 -0
  162. package/tests/agui-protocol.test.ts +246 -0
  163. package/tests/auto-learn.test.ts +105 -0
  164. package/tests/builtin-tools.test.ts +83 -0
  165. package/tests/channels/discord.test.ts +79 -0
  166. package/tests/channels/email.test.ts +148 -0
  167. package/tests/channels/feishu.test.ts +123 -0
  168. package/tests/channels/telegram.test.ts +129 -0
  169. package/tests/channels/websocket.test.ts +53 -0
  170. package/tests/channels/wechat.test.ts +170 -0
  171. package/tests/chat-cli.test.ts +160 -0
  172. package/tests/cli.test.ts +46 -0
  173. package/tests/daemon.test.ts +135 -0
  174. package/tests/deepbrain-wire.test.ts +234 -0
  175. package/tests/doctor.test.ts +38 -0
  176. package/tests/eval.test.ts +173 -0
  177. package/tests/init-role.test.ts +124 -0
  178. package/tests/mcp-client.test.ts +92 -0
  179. package/tests/mcp-server.test.ts +178 -0
  180. package/tests/plugin-a2a-enhanced.test.ts +230 -0
  181. package/tests/publish.test.ts +231 -0
  182. package/tests/scheduler.test.ts +200 -0
  183. package/tests/security-enhanced.test.ts +233 -0
  184. package/tests/skill-learner.test.ts +161 -0
  185. package/tests/studio.test.ts +229 -0
  186. package/tests/subagent.test.ts +193 -0
  187. package/tests/telegram-discord.test.ts +60 -0
  188. package/tests/telemetry.test.ts +186 -0
  189. package/tests/tools/builtin-extended.test.ts +138 -0
  190. package/tests/workflow-graph.test.ts +279 -0
  191. package/tutorial/customer-service-agent/README.md +612 -0
  192. package/tutorial/customer-service-agent/SOUL.md +26 -0
  193. package/tutorial/customer-service-agent/agent.yaml +63 -0
  194. package/tutorial/customer-service-agent/package.json +19 -0
  195. package/tutorial/customer-service-agent/src/index.ts +69 -0
  196. package/tutorial/customer-service-agent/src/skills/faq.ts +27 -0
  197. package/tutorial/customer-service-agent/src/skills/ticket.ts +22 -0
  198. package/tutorial/customer-service-agent/tsconfig.json +14 -0
@@ -1,15 +1,56 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.AgentRuntime = void 0;
4
37
  exports.truncateOutput = truncateOutput;
38
+ const plugins_1 = require("../plugins");
39
+ const logger_1 = require("../plugins/logger");
40
+ const rate_limiter_1 = require("../plugins/rate-limiter");
41
+ const content_filter_1 = require("../plugins/content-filter");
5
42
  const agent_1 = require("./agent");
6
43
  const config_1 = require("./config");
7
- const logger_1 = require("./logger");
44
+ const logger_2 = require("./logger");
8
45
  const web_1 = require("../channels/web");
9
46
  const telegram_1 = require("../channels/telegram");
10
47
  const websocket_1 = require("../channels/websocket");
48
+ const wechat_1 = require("../channels/wechat");
49
+ const feishu_1 = require("../channels/feishu");
50
+ const email_1 = require("../channels/email");
11
51
  const deepbrain_1 = require("../memory/deepbrain");
12
52
  const analytics_1 = require("../analytics");
53
+ const scheduler_1 = require("./scheduler");
13
54
  const MAX_TOOL_OUTPUT = 5000;
14
55
  const DEFAULT_HISTORY_LIMIT = 50;
15
56
  function truncateOutput(output, maxChars = MAX_TOOL_OUTPUT) {
@@ -21,11 +62,16 @@ function truncateOutput(output, maxChars = MAX_TOOL_OUTPUT) {
21
62
  class AgentRuntime {
22
63
  agent = null;
23
64
  config = null;
24
- logger = new logger_1.Logger('runtime');
65
+ logger = new logger_2.Logger('runtime');
25
66
  historyLimit = DEFAULT_HISTORY_LIMIT;
26
67
  shutdownHandlers = [];
27
68
  isShuttingDown = false;
28
69
  analytics = new analytics_1.Analytics();
70
+ scheduler = null;
71
+ pluginManager = new plugins_1.PluginManager();
72
+ brain = null;
73
+ agentBrain = null;
74
+ evolveScheduler = null;
29
75
  async loadConfig(filePath) {
30
76
  this.config = (0, config_1.loadOAD)(filePath);
31
77
  this.logger.info('Config loaded', { name: this.config.metadata.name });
@@ -103,8 +149,88 @@ class AgentRuntime {
103
149
  this.agent.bindChannel(new websocket_1.WebSocketChannel(ch.port ?? 3002));
104
150
  this.logger.info('Bound websocket channel', { port: ch.port ?? 3002 });
105
151
  }
152
+ else if (ch.type === 'wechat') {
153
+ this.agent.bindChannel(new wechat_1.WeChatChannel({
154
+ appId: ch.config?.appId ?? process.env.WECHAT_APP_ID ?? '',
155
+ appSecret: ch.config?.appSecret ?? process.env.WECHAT_APP_SECRET ?? '',
156
+ token: ch.config?.token ?? process.env.WECHAT_TOKEN ?? '',
157
+ encodingAESKey: ch.config?.encodingAESKey,
158
+ port: ch.port,
159
+ }));
160
+ this.logger.info('Bound wechat channel', { port: ch.port ?? 8080 });
161
+ }
162
+ else if (ch.type === 'feishu') {
163
+ this.agent.bindChannel(new feishu_1.FeishuChannel({
164
+ appId: ch.config?.appId ?? process.env.FEISHU_APP_ID,
165
+ appSecret: ch.config?.appSecret ?? process.env.FEISHU_APP_SECRET,
166
+ verificationToken: ch.config?.verificationToken ?? process.env.FEISHU_VERIFICATION_TOKEN,
167
+ encryptKey: ch.config?.encryptKey,
168
+ port: ch.port,
169
+ }));
170
+ this.logger.info('Bound feishu channel', { port: ch.port ?? 8081 });
171
+ }
172
+ else if (ch.type === 'email') {
173
+ this.agent.bindChannel(new email_1.EmailChannel({
174
+ mode: ch.config?.mode ?? 'webhook',
175
+ smtp: ch.config?.smtp,
176
+ imap: ch.config?.imap,
177
+ webhookPort: ch.port,
178
+ filters: ch.config?.filters,
179
+ }));
180
+ this.logger.info('Bound email channel', { mode: ch.config?.mode ?? 'webhook', port: ch.port ?? 8082 });
181
+ }
106
182
  }
107
183
  await this.agent.init();
184
+ // === Auto-wire DeepBrain long-term memory (Brain/AgentBrain) ===
185
+ const longTermCfg = memCfg && typeof memCfg.longTerm === 'object' ? memCfg.longTerm : null;
186
+ if (longTermCfg?.provider === 'deepbrain') {
187
+ try {
188
+ const deepbrainModule = await Promise.resolve().then(() => __importStar(require(/* webpackIgnore: true */ 'deepbrain')));
189
+ const BrainClass = deepbrainModule.Brain ?? deepbrainModule.default?.Brain;
190
+ const AgentBrainClass = deepbrainModule.AgentBrain ?? deepbrainModule.default?.AgentBrain;
191
+ if (BrainClass && AgentBrainClass) {
192
+ const dbConfig = longTermCfg.config ?? {};
193
+ const dbPath = dbConfig.database || './data/brain.db';
194
+ const embeddingProvider = dbConfig.embeddingProvider || 'ollama';
195
+ this.brain = new BrainClass({
196
+ database: dbPath,
197
+ embedding_provider: embeddingProvider,
198
+ });
199
+ await this.brain.connect();
200
+ this.agentBrain = new AgentBrainClass(this.brain, cfg.metadata.name);
201
+ this.agent.setLongTermMemory(this.agentBrain, {
202
+ autoLearn: dbConfig.autoLearn !== false,
203
+ autoRecall: dbConfig.autoRecall !== false,
204
+ });
205
+ this.logger.info('DeepBrain Brain/AgentBrain connected', { database: dbPath });
206
+ // Brain seed loading
207
+ const { existsSync, readFileSync, renameSync } = await Promise.resolve().then(() => __importStar(require('fs')));
208
+ const seedPath = './data/brain-seed.md';
209
+ if (existsSync(seedPath)) {
210
+ const seed = readFileSync(seedPath, 'utf-8');
211
+ await this.brain.put('brain-seed', seed, { type: 'seed', tags: ['seed', 'initial'] });
212
+ renameSync(seedPath, './data/brain-seed.loaded.md');
213
+ this.logger.info('Brain seed loaded');
214
+ }
215
+ // Auto-evolve scheduling
216
+ const evolveInterval = dbConfig.evolveInterval;
217
+ if (evolveInterval && evolveInterval > 0) {
218
+ const AutoEvolveSchedulerClass = deepbrainModule.AutoEvolveScheduler ?? deepbrainModule.default?.AutoEvolveScheduler;
219
+ if (AutoEvolveSchedulerClass) {
220
+ this.evolveScheduler = new AutoEvolveSchedulerClass();
221
+ this.evolveScheduler.start(this.agentBrain, evolveInterval);
222
+ this.logger.info('DeepBrain auto-evolve scheduled', { interval: evolveInterval });
223
+ }
224
+ }
225
+ }
226
+ else {
227
+ this.logger.warn('DeepBrain module found but Brain/AgentBrain classes not available');
228
+ }
229
+ }
230
+ catch (e) {
231
+ this.logger.warn('DeepBrain not available (install with: npm install deepbrain)', { error: e.message });
232
+ }
233
+ }
108
234
  // Wire analytics to agent events
109
235
  this.agent.on('message:out', () => {
110
236
  // responseTime is approximated; real timing is done via skill/llm events
@@ -116,6 +242,57 @@ class AgentRuntime {
116
242
  this.analytics.recordError();
117
243
  });
118
244
  this.logger.info('Agent initialized', { name: cfg.metadata.name });
245
+ // Load enhanced plugins from OAD config
246
+ const pluginsCfg = cfg.spec.plugins;
247
+ if (pluginsCfg && Array.isArray(pluginsCfg)) {
248
+ const builtinPlugins = {
249
+ 'logger': () => logger_1.loggerPlugin,
250
+ 'rate-limiter': (c) => (0, rate_limiter_1.createRateLimiterPlugin)(c?.maxPerMinute ?? 60),
251
+ 'content-filter': (c) => (0, content_filter_1.createContentFilterPlugin)(c?.blocklist ?? []),
252
+ };
253
+ for (const entry of pluginsCfg) {
254
+ const factory = builtinPlugins[entry.name];
255
+ if (factory) {
256
+ this.pluginManager.registerEnhanced(factory(entry.config));
257
+ this.logger.info('Enhanced plugin loaded from config', { name: entry.name });
258
+ }
259
+ }
260
+ }
261
+ await this.pluginManager.initAll(this);
262
+ // Initialize scheduler if jobs are configured
263
+ const schedulerCfg = cfg.spec.scheduler;
264
+ if (schedulerCfg?.jobs && Array.isArray(schedulerCfg.jobs) && schedulerCfg.jobs.length > 0) {
265
+ this.scheduler = new scheduler_1.Scheduler(async (job) => {
266
+ this.logger.info('Scheduler firing job', { name: job.name, task: job.task });
267
+ if (this.agent) {
268
+ const msg = {
269
+ id: `cron-${job.id}-${Date.now()}`,
270
+ role: 'user',
271
+ content: job.task,
272
+ timestamp: Date.now(),
273
+ metadata: { source: 'scheduler', jobId: job.id, jobName: job.name },
274
+ };
275
+ try {
276
+ await this.agent.handleMessage(msg);
277
+ }
278
+ catch (err) {
279
+ this.logger.error('Scheduler job failed', { name: job.name, error: err instanceof Error ? err.message : String(err) });
280
+ }
281
+ }
282
+ });
283
+ for (let i = 0; i < schedulerCfg.jobs.length; i++) {
284
+ const j = schedulerCfg.jobs[i];
285
+ const id = j.id || j.name?.toLowerCase().replace(/\s+/g, '-') || `job-${i}`;
286
+ this.scheduler.addJob({
287
+ id,
288
+ name: j.name || id,
289
+ schedule: j.schedule,
290
+ task: j.task || '',
291
+ enabled: j.enabled !== false,
292
+ });
293
+ }
294
+ this.logger.info('Scheduler configured', { jobs: schedulerCfg.jobs.length });
295
+ }
119
296
  return this.agent;
120
297
  }
121
298
  async start() {
@@ -123,12 +300,35 @@ class AgentRuntime {
123
300
  throw new Error('Agent not initialized.');
124
301
  this.setupGracefulShutdown();
125
302
  await this.agent.start();
303
+ if (this.scheduler) {
304
+ this.scheduler.start();
305
+ this.logger.info('Scheduler started');
306
+ }
126
307
  this.logger.info('Agent started');
127
308
  }
128
309
  async stop() {
129
310
  if (!this.agent)
130
311
  return;
131
312
  this.logger.info('Stopping agent...');
313
+ if (this.evolveScheduler) {
314
+ try {
315
+ this.evolveScheduler.stop();
316
+ }
317
+ catch { /* ignore */ }
318
+ this.logger.info('DeepBrain auto-evolve stopped');
319
+ }
320
+ if (this.brain) {
321
+ try {
322
+ await this.brain.disconnect();
323
+ this.logger.info('DeepBrain disconnected');
324
+ }
325
+ catch { /* ignore */ }
326
+ }
327
+ if (this.scheduler) {
328
+ this.scheduler.stop();
329
+ this.logger.info('Scheduler stopped');
330
+ }
331
+ await this.pluginManager.shutdownAll();
132
332
  await this.agent.stop();
133
333
  for (const handler of this.shutdownHandlers) {
134
334
  await handler();
@@ -169,6 +369,9 @@ class AgentRuntime {
169
369
  getConfig() {
170
370
  return this.config;
171
371
  }
372
+ getPluginManager() {
373
+ return this.pluginManager;
374
+ }
172
375
  }
173
376
  exports.AgentRuntime = AgentRuntime;
174
377
  //# sourceMappingURL=runtime.js.map
@@ -4,6 +4,22 @@ export interface SandboxConfig {
4
4
  agentDir: string;
5
5
  networkAllowlist?: string[];
6
6
  shellAllowed?: boolean;
7
+ allowedCommands?: string[];
8
+ blockedCommands?: string[];
9
+ maxFileSize?: number;
10
+ maxFiles?: number;
11
+ networkAccess?: boolean;
12
+ readOnlyPaths?: string[];
13
+ timeout?: number;
14
+ }
15
+ export interface ValidationResult {
16
+ allowed: boolean;
17
+ reason?: string;
18
+ }
19
+ export interface SandboxStatus {
20
+ files: number;
21
+ totalSize: number;
22
+ violations: number;
7
23
  }
8
24
  export interface SandboxRestrictions {
9
25
  fileSystem: {
@@ -18,11 +34,21 @@ export interface SandboxRestrictions {
18
34
  export declare class Sandbox {
19
35
  private config;
20
36
  private restrictions;
37
+ private violations;
38
+ private maxFileSize;
39
+ private maxFiles;
21
40
  constructor(config: SandboxConfig);
22
41
  get trustLevel(): TrustLevelType;
23
42
  getRestrictions(): SandboxRestrictions;
24
43
  checkFileAccess(filePath: string, mode: 'read' | 'write'): boolean;
25
44
  checkNetworkAccess(url: string): boolean;
26
45
  checkShellAccess(): boolean;
46
+ validateFileOp(action: 'read' | 'write' | 'delete', filePath: string): ValidationResult;
47
+ validateCommand(command: string): ValidationResult;
48
+ validateNetwork(url: string): ValidationResult;
49
+ getStatus(): SandboxStatus;
50
+ getViolations(): number;
51
+ getMaxFileSize(): number;
52
+ getMaxFiles(): number;
27
53
  }
28
54
  //# sourceMappingURL=sandbox.d.ts.map
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.Sandbox = void 0;
37
37
  const path = __importStar(require("path"));
38
+ const fs = __importStar(require("fs"));
38
39
  const TRUST_RESTRICTIONS = {
39
40
  sandbox: {
40
41
  fileSystem: { read: ['.'], write: ['.'] },
@@ -60,6 +61,9 @@ const TRUST_RESTRICTIONS = {
60
61
  class Sandbox {
61
62
  config;
62
63
  restrictions;
64
+ violations = 0;
65
+ maxFileSize;
66
+ maxFiles;
63
67
  constructor(config) {
64
68
  this.config = config;
65
69
  this.restrictions = {
@@ -71,6 +75,11 @@ class Sandbox {
71
75
  if (config.shellAllowed !== undefined) {
72
76
  this.restrictions.shell = config.shellAllowed;
73
77
  }
78
+ if (config.networkAccess === false) {
79
+ this.restrictions.network.allowed = [];
80
+ }
81
+ this.maxFileSize = config.maxFileSize ?? 10 * 1024 * 1024; // 10MB
82
+ this.maxFiles = config.maxFiles ?? 1000;
74
83
  }
75
84
  get trustLevel() {
76
85
  return this.config.trustLevel;
@@ -113,6 +122,114 @@ class Sandbox {
113
122
  checkShellAccess() {
114
123
  return this.restrictions.shell;
115
124
  }
125
+ validateFileOp(action, filePath) {
126
+ const resolved = path.resolve(filePath);
127
+ if (action === 'write' || action === 'delete') {
128
+ // Check read-only paths
129
+ if (this.config.readOnlyPaths) {
130
+ for (const ro of this.config.readOnlyPaths) {
131
+ const roResolved = path.resolve(ro);
132
+ if (resolved.startsWith(roResolved) || resolved === roResolved) {
133
+ this.violations++;
134
+ return { allowed: false, reason: `Path is read-only: ${ro}` };
135
+ }
136
+ }
137
+ }
138
+ // Check file size for writes
139
+ if (action === 'write') {
140
+ try {
141
+ if (fs.existsSync(resolved)) {
142
+ const stat = fs.statSync(resolved);
143
+ if (stat.size > this.maxFileSize) {
144
+ this.violations++;
145
+ return { allowed: false, reason: `File exceeds max size: ${this.maxFileSize} bytes` };
146
+ }
147
+ }
148
+ }
149
+ catch {
150
+ // File doesn't exist yet — that's fine
151
+ }
152
+ }
153
+ }
154
+ const mode = action === 'read' ? 'read' : 'write';
155
+ if (!this.checkFileAccess(filePath, mode)) {
156
+ this.violations++;
157
+ return { allowed: false, reason: `File access denied for ${action}: ${filePath}` };
158
+ }
159
+ return { allowed: true };
160
+ }
161
+ validateCommand(command) {
162
+ if (!this.restrictions.shell) {
163
+ this.violations++;
164
+ return { allowed: false, reason: 'Shell access is disabled' };
165
+ }
166
+ // Check blocklist
167
+ if (this.config.blockedCommands) {
168
+ for (const blocked of this.config.blockedCommands) {
169
+ if (command.includes(blocked)) {
170
+ this.violations++;
171
+ return { allowed: false, reason: `Command is blocked: ${blocked}` };
172
+ }
173
+ }
174
+ }
175
+ // Check allowlist (if set, only allowed commands pass)
176
+ if (this.config.allowedCommands && this.config.allowedCommands.length > 0) {
177
+ const allowed = this.config.allowedCommands.some(a => command.startsWith(a) || command.includes(a));
178
+ if (!allowed) {
179
+ this.violations++;
180
+ return { allowed: false, reason: 'Command not in allowlist' };
181
+ }
182
+ }
183
+ return { allowed: true };
184
+ }
185
+ validateNetwork(url) {
186
+ if (this.config.networkAccess === false) {
187
+ this.violations++;
188
+ return { allowed: false, reason: 'Network access is disabled' };
189
+ }
190
+ if (!this.checkNetworkAccess(url)) {
191
+ this.violations++;
192
+ return { allowed: false, reason: `Network access denied for: ${url}` };
193
+ }
194
+ return { allowed: true };
195
+ }
196
+ getStatus() {
197
+ let files = 0;
198
+ let totalSize = 0;
199
+ try {
200
+ const agentDir = path.resolve(this.config.agentDir);
201
+ if (fs.existsSync(agentDir)) {
202
+ const countFiles = (dir) => {
203
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
204
+ for (const entry of entries) {
205
+ const full = path.join(dir, entry.name);
206
+ if (entry.isDirectory() && entry.name !== 'node_modules') {
207
+ countFiles(full);
208
+ }
209
+ else if (entry.isFile()) {
210
+ files++;
211
+ try {
212
+ totalSize += fs.statSync(full).size;
213
+ }
214
+ catch { }
215
+ }
216
+ }
217
+ };
218
+ countFiles(agentDir);
219
+ }
220
+ }
221
+ catch { }
222
+ return { files, totalSize, violations: this.violations };
223
+ }
224
+ getViolations() {
225
+ return this.violations;
226
+ }
227
+ getMaxFileSize() {
228
+ return this.maxFileSize;
229
+ }
230
+ getMaxFiles() {
231
+ return this.maxFiles;
232
+ }
116
233
  }
117
234
  exports.Sandbox = Sandbox;
118
235
  //# sourceMappingURL=sandbox.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Simple cron scheduler — no external dependencies.
3
+ * Supports cron expressions: star, star-slash-N, M-N, M,N for minute/hour/day/month/weekday.
4
+ */
5
+ export interface CronJob {
6
+ id: string;
7
+ name: string;
8
+ schedule: string;
9
+ task: string;
10
+ enabled: boolean;
11
+ lastRun?: Date;
12
+ nextRun?: Date;
13
+ }
14
+ type CronField = {
15
+ type: 'any';
16
+ } | {
17
+ type: 'every';
18
+ step: number;
19
+ } | {
20
+ type: 'list';
21
+ values: number[];
22
+ };
23
+ interface ParsedCron {
24
+ minute: CronField;
25
+ hour: CronField;
26
+ dayOfMonth: CronField;
27
+ month: CronField;
28
+ dayOfWeek: CronField;
29
+ }
30
+ export declare function parseCron(expr: string): ParsedCron;
31
+ export declare function cronMatches(parsed: ParsedCron, date: Date): boolean;
32
+ export type JobHandler = (job: CronJob) => void | Promise<void>;
33
+ export declare class Scheduler {
34
+ private jobs;
35
+ private parsed;
36
+ private timer;
37
+ private handler;
38
+ constructor(handler: JobHandler);
39
+ addJob(job: CronJob): void;
40
+ removeJob(id: string): void;
41
+ enableJob(id: string): void;
42
+ disableJob(id: string): void;
43
+ getJobs(): CronJob[];
44
+ getJob(id: string): CronJob | undefined;
45
+ /** Run a specific job immediately */
46
+ runJob(id: string): Promise<boolean>;
47
+ start(): void;
48
+ stop(): void;
49
+ private tick;
50
+ }
51
+ export {};
52
+ //# sourceMappingURL=scheduler.d.ts.map
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ /**
3
+ * Simple cron scheduler — no external dependencies.
4
+ * Supports cron expressions: star, star-slash-N, M-N, M,N for minute/hour/day/month/weekday.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.Scheduler = void 0;
8
+ exports.parseCron = parseCron;
9
+ exports.cronMatches = cronMatches;
10
+ function parseField(field, min, max) {
11
+ if (field === '*')
12
+ return { type: 'any' };
13
+ if (field.startsWith('*/')) {
14
+ const step = parseInt(field.slice(2), 10);
15
+ if (isNaN(step) || step <= 0)
16
+ throw new Error(`Invalid cron step: ${field}`);
17
+ return { type: 'every', step };
18
+ }
19
+ // Could be comma-separated, each part could be a range
20
+ const values = [];
21
+ for (const part of field.split(',')) {
22
+ if (part.includes('-')) {
23
+ const [a, b] = part.split('-').map(Number);
24
+ if (isNaN(a) || isNaN(b))
25
+ throw new Error(`Invalid cron range: ${part}`);
26
+ for (let i = a; i <= b; i++)
27
+ values.push(i);
28
+ }
29
+ else {
30
+ const n = parseInt(part, 10);
31
+ if (isNaN(n))
32
+ throw new Error(`Invalid cron value: ${part}`);
33
+ values.push(n);
34
+ }
35
+ }
36
+ return { type: 'list', values };
37
+ }
38
+ function parseCron(expr) {
39
+ const parts = expr.trim().split(/\s+/);
40
+ if (parts.length !== 5)
41
+ throw new Error(`Invalid cron expression (need 5 fields): ${expr}`);
42
+ return {
43
+ minute: parseField(parts[0], 0, 59),
44
+ hour: parseField(parts[1], 0, 23),
45
+ dayOfMonth: parseField(parts[2], 1, 31),
46
+ month: parseField(parts[3], 1, 12),
47
+ dayOfWeek: parseField(parts[4], 0, 6),
48
+ };
49
+ }
50
+ function fieldMatches(field, value) {
51
+ switch (field.type) {
52
+ case 'any': return true;
53
+ case 'every': return value % field.step === 0;
54
+ case 'list': return field.values.includes(value);
55
+ }
56
+ }
57
+ function cronMatches(parsed, date) {
58
+ return (fieldMatches(parsed.minute, date.getMinutes()) &&
59
+ fieldMatches(parsed.hour, date.getHours()) &&
60
+ fieldMatches(parsed.dayOfMonth, date.getDate()) &&
61
+ fieldMatches(parsed.month, date.getMonth() + 1) &&
62
+ fieldMatches(parsed.dayOfWeek, date.getDay()));
63
+ }
64
+ /** Compute approximate next run (scans forward up to 48h). */
65
+ function computeNextRun(parsed, from) {
66
+ const d = new Date(from);
67
+ d.setSeconds(0, 0);
68
+ d.setMinutes(d.getMinutes() + 1);
69
+ const limit = 48 * 60; // 48 hours in minutes
70
+ for (let i = 0; i < limit; i++) {
71
+ if (cronMatches(parsed, d))
72
+ return new Date(d);
73
+ d.setMinutes(d.getMinutes() + 1);
74
+ }
75
+ return undefined;
76
+ }
77
+ class Scheduler {
78
+ jobs = new Map();
79
+ parsed = new Map();
80
+ timer = null;
81
+ handler;
82
+ constructor(handler) {
83
+ this.handler = handler;
84
+ }
85
+ addJob(job) {
86
+ const p = parseCron(job.schedule);
87
+ this.parsed.set(job.id, p);
88
+ job.nextRun = computeNextRun(p, new Date()) ?? undefined;
89
+ this.jobs.set(job.id, job);
90
+ }
91
+ removeJob(id) {
92
+ this.jobs.delete(id);
93
+ this.parsed.delete(id);
94
+ }
95
+ enableJob(id) {
96
+ const job = this.jobs.get(id);
97
+ if (job)
98
+ job.enabled = true;
99
+ }
100
+ disableJob(id) {
101
+ const job = this.jobs.get(id);
102
+ if (job)
103
+ job.enabled = false;
104
+ }
105
+ getJobs() {
106
+ return Array.from(this.jobs.values());
107
+ }
108
+ getJob(id) {
109
+ return this.jobs.get(id);
110
+ }
111
+ /** Run a specific job immediately */
112
+ async runJob(id) {
113
+ const job = this.jobs.get(id);
114
+ if (!job)
115
+ return false;
116
+ job.lastRun = new Date();
117
+ await this.handler(job);
118
+ const parsed = this.parsed.get(id);
119
+ if (parsed)
120
+ job.nextRun = computeNextRun(parsed, new Date());
121
+ return true;
122
+ }
123
+ start() {
124
+ if (this.timer)
125
+ return;
126
+ // Check every 60 seconds
127
+ this.timer = setInterval(() => this.tick(), 60_000);
128
+ // Also tick immediately
129
+ this.tick();
130
+ }
131
+ stop() {
132
+ if (this.timer) {
133
+ clearInterval(this.timer);
134
+ this.timer = null;
135
+ }
136
+ }
137
+ tick() {
138
+ const now = new Date();
139
+ for (const [id, job] of this.jobs) {
140
+ if (!job.enabled)
141
+ continue;
142
+ const parsed = this.parsed.get(id);
143
+ if (!parsed)
144
+ continue;
145
+ if (cronMatches(parsed, now)) {
146
+ // Avoid double-fire: check lastRun isn't same minute
147
+ if (job.lastRun) {
148
+ const last = job.lastRun;
149
+ if (last.getFullYear() === now.getFullYear() &&
150
+ last.getMonth() === now.getMonth() &&
151
+ last.getDate() === now.getDate() &&
152
+ last.getHours() === now.getHours() &&
153
+ last.getMinutes() === now.getMinutes()) {
154
+ continue;
155
+ }
156
+ }
157
+ job.lastRun = new Date(now);
158
+ job.nextRun = computeNextRun(parsed, now);
159
+ // Fire and forget (log errors)
160
+ Promise.resolve(this.handler(job)).catch((err) => {
161
+ console.error(`[scheduler] Job "${job.name}" failed:`, err);
162
+ });
163
+ }
164
+ }
165
+ }
166
+ }
167
+ exports.Scheduler = Scheduler;
168
+ //# sourceMappingURL=scheduler.js.map