foliko 1.0.75 → 1.0.76

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 (88) hide show
  1. package/.claude/settings.local.json +159 -157
  2. package/cli/bin/foliko.js +12 -12
  3. package/cli/src/commands/chat.js +143 -143
  4. package/cli/src/commands/list.js +93 -93
  5. package/cli/src/index.js +75 -75
  6. package/cli/src/ui/chat-ui.js +201 -201
  7. package/cli/src/utils/ansi.js +40 -40
  8. package/cli/src/utils/markdown.js +292 -292
  9. package/examples/ambient-example.js +194 -194
  10. package/examples/basic.js +115 -115
  11. package/examples/bootstrap.js +121 -121
  12. package/examples/mcp-example.js +56 -56
  13. package/examples/skill-example.js +49 -49
  14. package/examples/test-chat.js +137 -137
  15. package/examples/test-mcp.js +85 -85
  16. package/examples/test-reload.js +59 -59
  17. package/examples/test-telegram.js +50 -50
  18. package/examples/test-tg-bot.js +45 -45
  19. package/examples/test-tg-simple.js +47 -47
  20. package/examples/test-tg.js +62 -62
  21. package/examples/test-think.js +43 -43
  22. package/examples/test-web-plugin.js +103 -103
  23. package/examples/test-weixin-feishu.js +103 -103
  24. package/examples/workflow.js +158 -158
  25. package/package.json +1 -1
  26. package/plugins/ai-plugin.js +102 -102
  27. package/plugins/ambient-agent/EventWatcher.js +113 -113
  28. package/plugins/ambient-agent/ExplorerLoop.js +640 -640
  29. package/plugins/ambient-agent/GoalManager.js +197 -197
  30. package/plugins/ambient-agent/Reflector.js +95 -95
  31. package/plugins/ambient-agent/StateStore.js +90 -90
  32. package/plugins/ambient-agent/constants.js +101 -101
  33. package/plugins/ambient-agent/index.js +579 -579
  34. package/plugins/audit-plugin.js +187 -187
  35. package/plugins/default-plugins.js +662 -662
  36. package/plugins/email/constants.js +64 -64
  37. package/plugins/email/handlers.js +461 -461
  38. package/plugins/email/index.js +278 -278
  39. package/plugins/email/monitor.js +269 -269
  40. package/plugins/email/parser.js +138 -138
  41. package/plugins/email/reply.js +151 -151
  42. package/plugins/email/utils.js +124 -124
  43. package/plugins/feishu-plugin.js +481 -481
  44. package/plugins/file-system-plugin.js +826 -826
  45. package/plugins/install-plugin.js +199 -199
  46. package/plugins/python-executor-plugin.js +367 -367
  47. package/plugins/python-plugin-loader.js +481 -481
  48. package/plugins/rules-plugin.js +294 -294
  49. package/plugins/scheduler-plugin.js +691 -691
  50. package/plugins/session-plugin.js +369 -369
  51. package/plugins/shell-executor-plugin.js +197 -197
  52. package/plugins/storage-plugin.js +240 -240
  53. package/plugins/subagent-plugin.js +845 -845
  54. package/plugins/telegram-plugin.js +482 -482
  55. package/plugins/think-plugin.js +345 -345
  56. package/plugins/tools-plugin.js +196 -196
  57. package/plugins/web-plugin.js +606 -606
  58. package/plugins/weixin-plugin.js +545 -545
  59. package/src/capabilities/index.js +11 -11
  60. package/src/capabilities/skill-manager.js +609 -609
  61. package/src/capabilities/workflow-engine.js +1109 -1109
  62. package/src/core/agent-chat.js +882 -882
  63. package/src/core/agent.js +892 -892
  64. package/src/core/framework.js +465 -465
  65. package/src/core/index.js +19 -19
  66. package/src/core/plugin-base.js +219 -219
  67. package/src/core/plugin-manager.js +863 -863
  68. package/src/core/provider.js +114 -114
  69. package/src/core/sub-agent-config.js +264 -264
  70. package/src/core/system-prompt-builder.js +120 -120
  71. package/src/core/tool-registry.js +517 -517
  72. package/src/core/tool-router.js +297 -297
  73. package/src/executors/executor-base.js +58 -58
  74. package/src/executors/mcp-executor.js +741 -741
  75. package/src/index.js +25 -25
  76. package/src/utils/circuit-breaker.js +301 -301
  77. package/src/utils/error-boundary.js +363 -363
  78. package/src/utils/error.js +374 -374
  79. package/src/utils/event-emitter.js +97 -97
  80. package/src/utils/id.js +133 -133
  81. package/src/utils/index.js +217 -217
  82. package/src/utils/logger.js +181 -181
  83. package/src/utils/plugin-helpers.js +90 -90
  84. package/src/utils/retry.js +122 -122
  85. package/src/utils/sandbox.js +292 -292
  86. package/test/tool-registry-validation.test.js +218 -218
  87. package/website/script.js +136 -136
  88. package/foliko-1.0.75.tgz +0 -0
@@ -1,194 +1,194 @@
1
- /**
2
- * Ambient Agent Example
3
- * Demonstrates how to use the Ambient Agent plugin for autonomous monitoring and actions
4
- */
5
-
6
- const { Framework } = require('../src/core/framework');
7
-
8
- async function main() {
9
- console.log('=== Ambient Agent Example ===\n');
10
-
11
- // Create framework
12
- const framework = new Framework({
13
- debug: true,
14
- });
15
-
16
- // Bootstrap with default plugins (including ambient)
17
- await framework.bootstrap({
18
- agentDir: './.agent',
19
- aiConfig: {
20
- provider: 'deepseek',
21
- model: 'deepseek-chat',
22
- apiKey: process.env.DEEPSEEK_API_KEY || 'your-api-key',
23
- },
24
- });
25
-
26
- console.log('\n=== Framework Ready ===\n');
27
-
28
- // Wait for plugins to start
29
- await new Promise((resolve) => setTimeout(resolve, 1000));
30
-
31
- // Check if ambient plugin is loaded
32
- const ambientPlugin = framework.pluginManager.get('ambient');
33
- if (!ambientPlugin) {
34
- console.error('Ambient plugin not loaded!');
35
- return;
36
- }
37
-
38
- console.log('=== Ambient Plugin Tools Available ===');
39
- const tools = framework.getTools();
40
- const ambientTools = tools.filter((t) => t.name.startsWith('ambient_'));
41
- console.log('Ambient tools:', ambientTools.map((t) => t.name).join(', '));
42
-
43
- console.log('\n=== Example 1: Create a Goal ===');
44
- // Use ambient_goals to create a simple goal
45
- const createResult = await framework.executeTool('ambient_goals', {
46
- action: 'create',
47
- title: 'Monitor System Health',
48
- description: 'Periodically check system information and alert on issues',
49
- priority: 8,
50
- actions: [{ id: 'check_1', type: 'tool', name: 'system_info', args: {} }],
51
- });
52
- console.log('Create goal result:', JSON.stringify(createResult, null, 2));
53
-
54
- console.log('\n=== Example 2: Create a Thinking Goal ===');
55
- // Create a goal that triggers LLM thinking
56
- const thinkGoal = await framework.executeTool('ambient_goals', {
57
- action: 'create',
58
- title: 'Periodic Reflection',
59
- description: 'Regularly reflect on system state and suggest improvements',
60
- priority: 5,
61
- actions: [
62
- { id: 'reflect_1', type: 'think', topic: 'System state review', mode: 'reflect', depth: 3 },
63
- ],
64
- });
65
- console.log('Create thinking goal result:', JSON.stringify(thinkGoal, null, 2));
66
-
67
- console.log('\n=== Example 3: List All Goals ===');
68
- const listResult = await framework.executeTool('ambient_goals', {
69
- action: 'list',
70
- });
71
- console.log('Goals list:', JSON.stringify(listResult, null, 2));
72
-
73
- console.log('\n=== Example 4: Get Ambient Status ===');
74
- const statusResult = await framework.executeTool('ambient_status', {});
75
- console.log('Status:', JSON.stringify(statusResult, null, 2));
76
-
77
- console.log('\n=== Example 5: Store a Memory ===');
78
- const storeResult = await framework.executeTool('ambient_remember', {
79
- action: 'store',
80
- content: 'Important: System check showed high CPU usage at 14:30',
81
- key: 'cpu_alert_1',
82
- });
83
- console.log('Store memory result:', JSON.stringify(storeResult, null, 2));
84
-
85
- console.log('\n=== Example 6: Retrieve Memories ===');
86
- const retrieveResult = await framework.executeTool('ambient_remember', {
87
- action: 'retrieve',
88
- limit: 5,
89
- });
90
- console.log('Retrieve memories result:', JSON.stringify(retrieveResult, null, 2));
91
-
92
- console.log('\n=== Example 7: Search Memories ===');
93
- const searchResult = await framework.executeTool('ambient_remember', {
94
- action: 'search',
95
- query: 'CPU',
96
- });
97
- console.log('Search memories result:', JSON.stringify(searchResult, null, 2));
98
-
99
- console.log('\n=== Example 8: Trigger Thinking ===');
100
- const thinkResult = await framework.executeTool('ambient_think', {
101
- mode: 'brainstorm',
102
- topic: 'What improvements could be made to the current system?',
103
- depth: 3,
104
- });
105
- console.log('Think result:', JSON.stringify(thinkResult, null, 2));
106
-
107
- console.log('\n=== Example 9: Control Loop ===');
108
- console.log('Pausing loop...');
109
- const pauseResult = await framework.executeTool('ambient_control', {
110
- action: 'pause',
111
- });
112
- console.log('Pause result:', JSON.stringify(pauseResult, null, 2));
113
-
114
- await new Promise((resolve) => setTimeout(resolve, 1000));
115
-
116
- console.log('Resuming loop...');
117
- const resumeResult = await framework.executeTool('ambient_control', {
118
- action: 'resume',
119
- });
120
- console.log('Resume result:', JSON.stringify(resumeResult, null, 2));
121
-
122
- console.log('\n=== Example 10: Adjust Loop Settings ===');
123
- const adjustResult = await framework.executeTool('ambient_control', {
124
- action: 'adjust',
125
- tickInterval: 10000, // 10 seconds
126
- cooldownPeriod: 5000, // 5 seconds
127
- });
128
- console.log('Adjust result:', JSON.stringify(adjustResult, null, 2));
129
-
130
- console.log('\n=== Example 11: Get Final Status ===');
131
- const finalStatus = await framework.executeTool('ambient_status', {});
132
- console.log('Final status:', JSON.stringify(finalStatus, null, 2));
133
-
134
- console.log('\n=== Example 12: Activate a Pending Goal ===');
135
- // First create a pending goal (without auto-activation conditions)
136
- const newGoal = await framework.executeTool('ambient_goals', {
137
- action: 'create',
138
- title: 'Inactive Test Goal',
139
- description: 'A goal that starts inactive',
140
- priority: 3,
141
- actions: [],
142
- });
143
- console.log('Created inactive goal:', newGoal.goal ? newGoal.goal.id : 'N/A');
144
-
145
- if (newGoal.goal) {
146
- console.log('Activating goal...');
147
- const activateResult = await framework.executeTool('ambient_goals', {
148
- action: 'activate',
149
- goalId: newGoal.goal.id,
150
- });
151
- console.log('Activate result:', JSON.stringify(activateResult, null, 2));
152
- }
153
-
154
- console.log('\n=== Example 13: Update a Goal ===');
155
- const goals = await framework.executeTool('ambient_goals', { action: 'list' });
156
- if (goals.goals && goals.goals.length > 0) {
157
- const goalToUpdate = goals.goals[0];
158
- console.log(`Updating goal ${goalToUpdate.id}...`);
159
- const updateResult = await framework.executeTool('ambient_goals', {
160
- action: 'update',
161
- goalId: goalToUpdate.id,
162
- priority: 10,
163
- });
164
- console.log('Update result:', JSON.stringify(updateResult, null, 2));
165
- }
166
-
167
- console.log('\n=== Example 14: Delete a Goal ===');
168
- const deleteGoal = await framework.executeTool('ambient_goals', {
169
- action: 'create',
170
- title: 'Goal to Delete',
171
- description: 'This will be deleted',
172
- priority: 1,
173
- });
174
- if (deleteGoal.goal) {
175
- console.log(`Created goal to delete: ${deleteGoal.goal.id}`);
176
- const deleteResult = await framework.executeTool('ambient_goals', {
177
- action: 'delete',
178
- goalId: deleteGoal.goal.id,
179
- });
180
- console.log('Delete result:', JSON.stringify(deleteResult, null, 2));
181
- }
182
-
183
- console.log('\n=== All Examples Completed ===');
184
- console.log('Check .agent/data/ambient/ for persisted data');
185
-
186
- // Cleanup
187
- console.log('\nShutting down...');
188
- await framework.destroy();
189
- }
190
-
191
- main().catch((err) => {
192
- console.error('Example error:', err);
193
- process.exit(1);
194
- });
1
+ /**
2
+ * Ambient Agent Example
3
+ * Demonstrates how to use the Ambient Agent plugin for autonomous monitoring and actions
4
+ */
5
+
6
+ const { Framework } = require('../src/core/framework');
7
+
8
+ async function main() {
9
+ console.log('=== Ambient Agent Example ===\n');
10
+
11
+ // Create framework
12
+ const framework = new Framework({
13
+ debug: true,
14
+ });
15
+
16
+ // Bootstrap with default plugins (including ambient)
17
+ await framework.bootstrap({
18
+ agentDir: './.agent',
19
+ aiConfig: {
20
+ provider: 'deepseek',
21
+ model: 'deepseek-chat',
22
+ apiKey: process.env.DEEPSEEK_API_KEY || 'your-api-key',
23
+ },
24
+ });
25
+
26
+ console.log('\n=== Framework Ready ===\n');
27
+
28
+ // Wait for plugins to start
29
+ await new Promise((resolve) => setTimeout(resolve, 1000));
30
+
31
+ // Check if ambient plugin is loaded
32
+ const ambientPlugin = framework.pluginManager.get('ambient');
33
+ if (!ambientPlugin) {
34
+ console.error('Ambient plugin not loaded!');
35
+ return;
36
+ }
37
+
38
+ console.log('=== Ambient Plugin Tools Available ===');
39
+ const tools = framework.getTools();
40
+ const ambientTools = tools.filter((t) => t.name.startsWith('ambient_'));
41
+ console.log('Ambient tools:', ambientTools.map((t) => t.name).join(', '));
42
+
43
+ console.log('\n=== Example 1: Create a Goal ===');
44
+ // Use ambient_goals to create a simple goal
45
+ const createResult = await framework.executeTool('ambient_goals', {
46
+ action: 'create',
47
+ title: 'Monitor System Health',
48
+ description: 'Periodically check system information and alert on issues',
49
+ priority: 8,
50
+ actions: [{ id: 'check_1', type: 'tool', name: 'system_info', args: {} }],
51
+ });
52
+ console.log('Create goal result:', JSON.stringify(createResult, null, 2));
53
+
54
+ console.log('\n=== Example 2: Create a Thinking Goal ===');
55
+ // Create a goal that triggers LLM thinking
56
+ const thinkGoal = await framework.executeTool('ambient_goals', {
57
+ action: 'create',
58
+ title: 'Periodic Reflection',
59
+ description: 'Regularly reflect on system state and suggest improvements',
60
+ priority: 5,
61
+ actions: [
62
+ { id: 'reflect_1', type: 'think', topic: 'System state review', mode: 'reflect', depth: 3 },
63
+ ],
64
+ });
65
+ console.log('Create thinking goal result:', JSON.stringify(thinkGoal, null, 2));
66
+
67
+ console.log('\n=== Example 3: List All Goals ===');
68
+ const listResult = await framework.executeTool('ambient_goals', {
69
+ action: 'list',
70
+ });
71
+ console.log('Goals list:', JSON.stringify(listResult, null, 2));
72
+
73
+ console.log('\n=== Example 4: Get Ambient Status ===');
74
+ const statusResult = await framework.executeTool('ambient_status', {});
75
+ console.log('Status:', JSON.stringify(statusResult, null, 2));
76
+
77
+ console.log('\n=== Example 5: Store a Memory ===');
78
+ const storeResult = await framework.executeTool('ambient_remember', {
79
+ action: 'store',
80
+ content: 'Important: System check showed high CPU usage at 14:30',
81
+ key: 'cpu_alert_1',
82
+ });
83
+ console.log('Store memory result:', JSON.stringify(storeResult, null, 2));
84
+
85
+ console.log('\n=== Example 6: Retrieve Memories ===');
86
+ const retrieveResult = await framework.executeTool('ambient_remember', {
87
+ action: 'retrieve',
88
+ limit: 5,
89
+ });
90
+ console.log('Retrieve memories result:', JSON.stringify(retrieveResult, null, 2));
91
+
92
+ console.log('\n=== Example 7: Search Memories ===');
93
+ const searchResult = await framework.executeTool('ambient_remember', {
94
+ action: 'search',
95
+ query: 'CPU',
96
+ });
97
+ console.log('Search memories result:', JSON.stringify(searchResult, null, 2));
98
+
99
+ console.log('\n=== Example 8: Trigger Thinking ===');
100
+ const thinkResult = await framework.executeTool('ambient_think', {
101
+ mode: 'brainstorm',
102
+ topic: 'What improvements could be made to the current system?',
103
+ depth: 3,
104
+ });
105
+ console.log('Think result:', JSON.stringify(thinkResult, null, 2));
106
+
107
+ console.log('\n=== Example 9: Control Loop ===');
108
+ console.log('Pausing loop...');
109
+ const pauseResult = await framework.executeTool('ambient_control', {
110
+ action: 'pause',
111
+ });
112
+ console.log('Pause result:', JSON.stringify(pauseResult, null, 2));
113
+
114
+ await new Promise((resolve) => setTimeout(resolve, 1000));
115
+
116
+ console.log('Resuming loop...');
117
+ const resumeResult = await framework.executeTool('ambient_control', {
118
+ action: 'resume',
119
+ });
120
+ console.log('Resume result:', JSON.stringify(resumeResult, null, 2));
121
+
122
+ console.log('\n=== Example 10: Adjust Loop Settings ===');
123
+ const adjustResult = await framework.executeTool('ambient_control', {
124
+ action: 'adjust',
125
+ tickInterval: 10000, // 10 seconds
126
+ cooldownPeriod: 5000, // 5 seconds
127
+ });
128
+ console.log('Adjust result:', JSON.stringify(adjustResult, null, 2));
129
+
130
+ console.log('\n=== Example 11: Get Final Status ===');
131
+ const finalStatus = await framework.executeTool('ambient_status', {});
132
+ console.log('Final status:', JSON.stringify(finalStatus, null, 2));
133
+
134
+ console.log('\n=== Example 12: Activate a Pending Goal ===');
135
+ // First create a pending goal (without auto-activation conditions)
136
+ const newGoal = await framework.executeTool('ambient_goals', {
137
+ action: 'create',
138
+ title: 'Inactive Test Goal',
139
+ description: 'A goal that starts inactive',
140
+ priority: 3,
141
+ actions: [],
142
+ });
143
+ console.log('Created inactive goal:', newGoal.goal ? newGoal.goal.id : 'N/A');
144
+
145
+ if (newGoal.goal) {
146
+ console.log('Activating goal...');
147
+ const activateResult = await framework.executeTool('ambient_goals', {
148
+ action: 'activate',
149
+ goalId: newGoal.goal.id,
150
+ });
151
+ console.log('Activate result:', JSON.stringify(activateResult, null, 2));
152
+ }
153
+
154
+ console.log('\n=== Example 13: Update a Goal ===');
155
+ const goals = await framework.executeTool('ambient_goals', { action: 'list' });
156
+ if (goals.goals && goals.goals.length > 0) {
157
+ const goalToUpdate = goals.goals[0];
158
+ console.log(`Updating goal ${goalToUpdate.id}...`);
159
+ const updateResult = await framework.executeTool('ambient_goals', {
160
+ action: 'update',
161
+ goalId: goalToUpdate.id,
162
+ priority: 10,
163
+ });
164
+ console.log('Update result:', JSON.stringify(updateResult, null, 2));
165
+ }
166
+
167
+ console.log('\n=== Example 14: Delete a Goal ===');
168
+ const deleteGoal = await framework.executeTool('ambient_goals', {
169
+ action: 'create',
170
+ title: 'Goal to Delete',
171
+ description: 'This will be deleted',
172
+ priority: 1,
173
+ });
174
+ if (deleteGoal.goal) {
175
+ console.log(`Created goal to delete: ${deleteGoal.goal.id}`);
176
+ const deleteResult = await framework.executeTool('ambient_goals', {
177
+ action: 'delete',
178
+ goalId: deleteGoal.goal.id,
179
+ });
180
+ console.log('Delete result:', JSON.stringify(deleteResult, null, 2));
181
+ }
182
+
183
+ console.log('\n=== All Examples Completed ===');
184
+ console.log('Check .agent/data/ambient/ for persisted data');
185
+
186
+ // Cleanup
187
+ console.log('\nShutting down...');
188
+ await framework.destroy();
189
+ }
190
+
191
+ main().catch((err) => {
192
+ console.error('Example error:', err);
193
+ process.exit(1);
194
+ });
package/examples/basic.js CHANGED
@@ -1,115 +1,115 @@
1
- /**
2
- * 基础示例
3
- * 展示如何使用 Framework 和 Agent
4
- */
5
-
6
- const { Framework } = require('../src');
7
- const { AIPlugin } = require('../plugins/ai-plugin');
8
- const { z } = require('zod');
9
-
10
- async function main() {
11
- // 创建框架实例
12
- const framework = new Framework({ debug: true });
13
-
14
- // 加载 AI 插件
15
- await framework.loadPlugin(
16
- new AIPlugin({
17
- provider: 'deepseek',
18
- model: 'deepseek-chat',
19
- apiKey: process.env.DEEPSEEK_API_KEY || 'your-api-key',
20
- })
21
- );
22
-
23
- // 注册自定义工具(使用 inputSchema 格式)
24
- framework.registerTool({
25
- name: 'hello',
26
- description: '打招呼工具',
27
- inputSchema: z.object({
28
- name: z.string().optional().describe('姓名'),
29
- }),
30
- execute: async (args) => {
31
- return `Hello, ${args.name || 'World'}!`;
32
- },
33
- });
34
-
35
- // 注册计算器工具
36
- framework.registerTool({
37
- name: 'calculate',
38
- description: '简单的计算器',
39
- inputSchema: z.object({
40
- expression: z.string().describe('数学表达式,如 2+3*4'),
41
- }),
42
- execute: async (args) => {
43
- try {
44
- // 安全计算(仅支持基本运算)
45
- const result = Function(`"use strict"; return (${args.expression})`)();
46
- return { result };
47
- } catch (e) {
48
- return { error: e.message };
49
- }
50
- },
51
- });
52
-
53
- console.log('[Framework] Ready!');
54
- console.log(
55
- '[Tools]',
56
- framework.getTools().map((t) => t.name)
57
- );
58
-
59
- // 创建 Agent
60
- const agent = framework.createAgent({
61
- name: 'MyAgent',
62
- systemPrompt: '你是一个有帮助的助手。当需要计算时,使用 calculate 工具。',
63
- });
64
-
65
- // 监听事件
66
- agent.on('tool-call', (tool) => {
67
- console.log('[Agent] Tool call:', tool.name, tool.args);
68
- });
69
-
70
- agent.on('tool-result', (result) => {
71
- console.log('[Agent] Tool result:', result.name, result.result);
72
- });
73
-
74
- // AI 对话示例
75
- console.log('\n=== AI Chat Example ===');
76
- try {
77
- const response = await agent.chat('你好!');
78
- console.log('[Agent] Response:', response.message);
79
- } catch (err) {
80
- console.error('[Agent] Error:', err.message);
81
- }
82
-
83
- // 使用工具的对话示例
84
- console.log('\n=== AI Chat with Tool Call ===');
85
- try {
86
- const response = await agent.chat('请帮我计算 (15 + 25) * 2 等于多少?');
87
- console.log('[Agent] Response:', response.message);
88
- } catch (err) {
89
- console.error('[Agent] Error:', err.message);
90
- }
91
-
92
- // 流式对话示例
93
- console.log('\n=== Streaming Chat ===');
94
- try {
95
- for await (const chunk of agent.chatStream('请用中文介绍一下你自己')) {
96
- if (chunk.type === 'text') {
97
- process.stdout.write(chunk.text);
98
- }
99
- }
100
- console.log('\n');
101
- } catch (err) {
102
- console.error('[Agent] Stream Error:', err.message);
103
- }
104
-
105
- // 热重载示例
106
- console.log('\n=== Hot Reload ===');
107
- await framework.reloadPlugin('ai');
108
- console.log('AI plugin reloaded!');
109
-
110
- // 清理
111
- await framework.destroy();
112
- console.log('\n[Done]');
113
- }
114
-
115
- main().catch(console.error);
1
+ /**
2
+ * 基础示例
3
+ * 展示如何使用 Framework 和 Agent
4
+ */
5
+
6
+ const { Framework } = require('../src');
7
+ const { AIPlugin } = require('../plugins/ai-plugin');
8
+ const { z } = require('zod');
9
+
10
+ async function main() {
11
+ // 创建框架实例
12
+ const framework = new Framework({ debug: true });
13
+
14
+ // 加载 AI 插件
15
+ await framework.loadPlugin(
16
+ new AIPlugin({
17
+ provider: 'deepseek',
18
+ model: 'deepseek-chat',
19
+ apiKey: process.env.DEEPSEEK_API_KEY || 'your-api-key',
20
+ })
21
+ );
22
+
23
+ // 注册自定义工具(使用 inputSchema 格式)
24
+ framework.registerTool({
25
+ name: 'hello',
26
+ description: '打招呼工具',
27
+ inputSchema: z.object({
28
+ name: z.string().optional().describe('姓名'),
29
+ }),
30
+ execute: async (args) => {
31
+ return `Hello, ${args.name || 'World'}!`;
32
+ },
33
+ });
34
+
35
+ // 注册计算器工具
36
+ framework.registerTool({
37
+ name: 'calculate',
38
+ description: '简单的计算器',
39
+ inputSchema: z.object({
40
+ expression: z.string().describe('数学表达式,如 2+3*4'),
41
+ }),
42
+ execute: async (args) => {
43
+ try {
44
+ // 安全计算(仅支持基本运算)
45
+ const result = Function(`"use strict"; return (${args.expression})`)();
46
+ return { result };
47
+ } catch (e) {
48
+ return { error: e.message };
49
+ }
50
+ },
51
+ });
52
+
53
+ console.log('[Framework] Ready!');
54
+ console.log(
55
+ '[Tools]',
56
+ framework.getTools().map((t) => t.name)
57
+ );
58
+
59
+ // 创建 Agent
60
+ const agent = framework.createAgent({
61
+ name: 'MyAgent',
62
+ systemPrompt: '你是一个有帮助的助手。当需要计算时,使用 calculate 工具。',
63
+ });
64
+
65
+ // 监听事件
66
+ agent.on('tool-call', (tool) => {
67
+ console.log('[Agent] Tool call:', tool.name, tool.args);
68
+ });
69
+
70
+ agent.on('tool-result', (result) => {
71
+ console.log('[Agent] Tool result:', result.name, result.result);
72
+ });
73
+
74
+ // AI 对话示例
75
+ console.log('\n=== AI Chat Example ===');
76
+ try {
77
+ const response = await agent.chat('你好!');
78
+ console.log('[Agent] Response:', response.message);
79
+ } catch (err) {
80
+ console.error('[Agent] Error:', err.message);
81
+ }
82
+
83
+ // 使用工具的对话示例
84
+ console.log('\n=== AI Chat with Tool Call ===');
85
+ try {
86
+ const response = await agent.chat('请帮我计算 (15 + 25) * 2 等于多少?');
87
+ console.log('[Agent] Response:', response.message);
88
+ } catch (err) {
89
+ console.error('[Agent] Error:', err.message);
90
+ }
91
+
92
+ // 流式对话示例
93
+ console.log('\n=== Streaming Chat ===');
94
+ try {
95
+ for await (const chunk of agent.chatStream('请用中文介绍一下你自己')) {
96
+ if (chunk.type === 'text') {
97
+ process.stdout.write(chunk.text);
98
+ }
99
+ }
100
+ console.log('\n');
101
+ } catch (err) {
102
+ console.error('[Agent] Stream Error:', err.message);
103
+ }
104
+
105
+ // 热重载示例
106
+ console.log('\n=== Hot Reload ===');
107
+ await framework.reloadPlugin('ai');
108
+ console.log('AI plugin reloaded!');
109
+
110
+ // 清理
111
+ await framework.destroy();
112
+ console.log('\n[Done]');
113
+ }
114
+
115
+ main().catch(console.error);