@qcluffy/agent-bootstrap 0.0.3 → 0.0.4

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.
@@ -1,176 +1,107 @@
1
1
  /**
2
- * Bootstrap System Hook Handler
2
+ * Bootstrap System Hook Handler - TypeScript 版本
3
3
  *
4
- * 集成 Python bootstrap-system 到 OpenClaw
4
+ * 直接调用 TypeScript 编译后的 bootstrap 模块
5
5
  */
6
6
 
7
- const fs = require('fs').promises;
8
7
  const path = require('path');
9
- const { spawn } = require('child_process');
10
- const os = require('os');
8
+ const fs = require('fs');
11
9
 
12
- // 配置
10
+ // 获取插件目录
11
+ const pluginDir = __dirname;
12
+
13
+ // 配置 - 指向 dist/systems
13
14
  const CONFIG = {
14
- bootstrapSystemPath: 'templates/bootstrap-system',
15
- mainScript: 'main.py',
15
+ bootstrapSystemPath: path.join(pluginDir, 'dist', 'systems'),
16
16
  };
17
17
 
18
18
  /**
19
- * 运行 Python bootstrap-system CLI
19
+ * 加载 TypeScript 编译后的 BootstrapEngine
20
20
  */
21
- async function runPythonCli(args = []) {
22
- const workspaceDir = process.env.OPENCLAW_WORKSPACE ||
23
- path.join(os.homedir(), '.openclaw', 'workspace');
24
- const pythonScript = path.join(workspaceDir, CONFIG.bootstrapSystemPath, CONFIG.mainScript);
25
-
26
- return new Promise((resolve) => {
27
- fs.access(pythonScript).then(() => {
28
- const proc = spawn('python3', [pythonScript, ...args], {
29
- cwd: workspaceDir,
30
- env: {
31
- ...process.env,
32
- OPENCLAW_WORKSPACE: workspaceDir,
33
- PYTHONPATH: path.join(workspaceDir, CONFIG.bootstrapSystemPath)
34
- }
35
- });
36
-
37
- let output = '';
38
- let error = '';
39
-
40
- proc.stdout.on('data', (data) => { output += data.toString(); });
41
- proc.stderr.on('data', (data) => { error += data.toString(); });
42
-
43
- proc.on('close', (code) => {
44
- resolve({ success: code === 0, output, error });
45
- });
46
-
47
- proc.on('error', (err) => {
48
- resolve({ success: false, error: err.message });
49
- });
50
-
51
- }).catch(() => {
52
- resolve({ success: false, error: 'Bootstrap system not found' });
53
- });
54
- });
55
- }
21
+ let BootstrapEngine = null;
56
22
 
57
- /**
58
- * 从会话消息中提取文本内容
59
- */
60
- function extractMessageText(message) {
61
- if (!message || !message.content) return '';
62
-
63
- if (typeof message.content === 'string') {
64
- return message.content;
65
- }
66
-
67
- if (Array.isArray(message.content)) {
68
- return message.content
69
- .filter((c) => c.type === 'text')
70
- .map((c) => c.text || '')
71
- .join('');
23
+ async function getBootstrapEngine() {
24
+ if (!BootstrapEngine) {
25
+ try {
26
+ const module = await import(path.join(CONFIG.bootstrapSystemPath, 'bootstrap.js'));
27
+ BootstrapEngine = module.BootstrapEngine || module.default;
28
+ } catch (e) {
29
+ console.error('[bootstrap-system] Failed to load bootstrap module:', e.message);
30
+ return null;
31
+ }
72
32
  }
73
-
74
- return '';
33
+ return BootstrapEngine;
75
34
  }
76
35
 
77
36
  /**
78
- * 处理 session_start - 检查是否需要引导
37
+ * 检查是否需要引导
79
38
  */
80
- async function handleSessionStart(event) {
39
+ async function checkBootstrap(event) {
81
40
  console.log('[bootstrap-system] Checking bootstrap status...');
82
41
 
83
- const result = await runPythonCli(['status', '--json']);
84
-
85
- if (result.success && result.output) {
86
- try {
87
- const status = JSON.parse(result.output);
88
- event.context = event.context || {};
89
- event.context.bootstrap = status;
90
-
91
- if (!status.is_completed && status.status === 'not_started') {
92
- // 需要开始引导
93
- event.needsBootstrap = true;
94
- console.log('[bootstrap-system] Bootstrap needed');
95
- } else if (status.is_completed) {
96
- console.log('[bootstrap-system] Bootstrap already completed');
97
- }
98
- } catch (e) {
99
- console.log('[bootstrap-system] Parse error:', e.message);
42
+ try {
43
+ const workspaceDir = process.env.OPENCLAW_WORKSPACE ||
44
+ path.join(process.env.HOME || '', '.openclaw', 'workspace');
45
+
46
+ // 检查关键文件是否存在
47
+ const requiredFiles = ['IDENTITY.md', 'SOUL.md', 'USER.md'];
48
+ const missing = requiredFiles.filter(f =>
49
+ !fs.existsSync(path.join(workspaceDir, f))
50
+ );
51
+
52
+ if (missing.length > 0) {
53
+ console.log('[bootstrap-system] Bootstrap needed, missing:', missing);
54
+ event.needsBootstrap = true;
55
+ event.bootstrapFiles = missing;
56
+ } else {
57
+ console.log('[bootstrap-system] Bootstrap not needed');
58
+ event.needsBootstrap = false;
100
59
  }
60
+ } catch (e) {
61
+ console.log('[bootstrap-system] Check error:', e.message);
101
62
  }
102
63
 
103
64
  return event;
104
65
  }
105
66
 
106
67
  /**
107
- * 处理 bootstrap 命令
68
+ * 处理 bootstrap:start - 开始引导
108
69
  */
109
- async function handleBootstrapCommand(event) {
110
- const action = event.action;
111
- const input = event.input || '';
70
+ async function handleBootstrapStart(event) {
71
+ console.log('[bootstrap-system] Starting bootstrap...');
112
72
 
113
- if (action === 'start' || action === 'begin') {
114
- // 开始引导
115
- const result = await runPythonCli(['start']);
116
- event.response = result.output;
117
- }
118
- else if (action === 'step') {
119
- // 查看当前步骤
120
- const result = await runPythonCli(['step']);
121
- event.response = result.output;
122
- }
123
- else if (action === 'submit' || action === 'next') {
124
- // 提交输入
125
- const result = await runPythonCli(['submit', input]);
126
- event.response = result.output;
127
-
128
- // 检查是否完成
129
- if (result.output.includes('初始化完成') || result.output.includes('completed')) {
130
- event.bootstrapCompleted = true;
73
+ try {
74
+ const BootstrapClass = await getBootstrapEngine();
75
+ if (BootstrapClass) {
76
+ const bootstrap = new BootstrapEngine();
77
+ const context = await bootstrap.start();
78
+
79
+ event.bootstrapContext = context;
80
+ console.log('[bootstrap-system] Bootstrap started');
131
81
  }
132
- }
133
- else if (action === 'status') {
134
- // 查看状态
135
- const result = await runPythonCli(['status']);
136
- event.response = result.output;
137
- }
138
- else if (action === 'reset') {
139
- // 重置
140
- const result = await runPythonCli(['reset']);
141
- event.response = '✓ 引导已重置,请重新开始';
82
+ } catch (e) {
83
+ console.log('[bootstrap-system] Bootstrap error:', e.message);
142
84
  }
143
85
 
144
86
  return event;
145
87
  }
146
88
 
147
89
  /**
148
- * 处理用户消息 - 检查是否是引导输入
90
+ * 处理 bootstrap:complete - 引导完成
149
91
  */
150
- async function handleMessage(event) {
151
- const context = event.context || {};
92
+ async function handleBootstrapComplete(event) {
93
+ console.log('[bootstrap-system] Bootstrap completed...');
152
94
 
153
- // 检查是否正在进行引导
154
- if (context.bootstrap && context.bootstrap.status === 'in_progress') {
155
- const messages = context.messages || [];
156
- const reversed = [...messages].reverse();
157
- const lastUserMsg = reversed.find((m) => m.role === 'user');
158
-
159
- if (lastUserMsg) {
160
- const userText = extractMessageText(lastUserMsg);
95
+ try {
96
+ const BootstrapClass = await getBootstrapEngine();
97
+ if (BootstrapClass) {
98
+ const bootstrap = new BootstrapEngine();
99
+ await bootstrap.complete(event.bootstrapData);
161
100
 
162
- if (userText && !userText.startsWith('/')) {
163
- // 提交作为引导输入
164
- console.log('[bootstrap-system] Submitting bootstrap input:', userText.substring(0, 20));
165
- const result = await runPythonCli(['submit', userText]);
166
-
167
- event.bootstrapResponse = result.output;
168
-
169
- if (result.output.includes('初始化完成') || result.output.includes('completed')) {
170
- event.bootstrapCompleted = true;
171
- }
172
- }
101
+ console.log('[bootstrap-system] Bootstrap completed');
173
102
  }
103
+ } catch (e) {
104
+ console.log('[bootstrap-system] Complete error:', e.message);
174
105
  }
175
106
 
176
107
  return event;
@@ -187,19 +118,13 @@ async function handle(event) {
187
118
 
188
119
  try {
189
120
  if (type === 'session' || type === 'session:start') {
190
- await handleSessionStart(event);
121
+ await checkBootstrap(event);
191
122
  }
192
- else if (type === 'message' || type === 'message:received') {
193
- await handleMessage(event);
123
+ else if (type === 'bootstrap' || type === 'bootstrap:start') {
124
+ await handleBootstrapStart(event);
194
125
  }
195
- else if (type === 'command') {
196
- // 处理引导命令
197
- if (action === 'bootstrap' || action === '引导' || action === '开始') {
198
- await handleBootstrapCommand(event);
199
- }
200
- else if (['start', 'step', 'submit', 'status', 'reset'].includes(action)) {
201
- await handleBootstrapCommand(event);
202
- }
126
+ else if (type === 'bootstrap' || type === 'bootstrap:complete') {
127
+ await handleBootstrapComplete(event);
203
128
  }
204
129
  } catch (error) {
205
130
  console.error('[bootstrap-system] Handler error:', error.message);
@@ -212,8 +137,8 @@ module.exports = handle;
212
137
  module.exports.handle = handle;
213
138
  module.exports.metadata = {
214
139
  name: 'bootstrap-system',
215
- description: '初始化引导系统,交互式收集用户配置、塑造Agent人格',
216
- events: ['session', 'message', 'command'],
140
+ description: 'Bootstrap System: interactive agent initialization and configuration',
141
+ events: ['session', 'bootstrap'],
217
142
  version: '1.0.0',
218
143
  };
219
144
 
@@ -1,143 +1,79 @@
1
1
  /**
2
- * Cognition System Hook Handler
2
+ * Cognition System Hook Handler - TypeScript 版本
3
3
  *
4
- * 集成 Python cognition-system 到 OpenClaw
4
+ * 直接调用 TypeScript 编译后的 cognition 模块
5
5
  */
6
6
 
7
- const fs = require('fs').promises;
8
7
  const path = require('path');
9
- const { spawn } = require('child_process');
10
- const os = require('os');
11
8
 
12
- // 配置
9
+ // 获取插件目录
10
+ const pluginDir = __dirname;
11
+
12
+ // 配置 - 指向 dist/systems
13
13
  const CONFIG = {
14
- cognitionSystemPath: 'templates/cognition-system',
15
- mainScript: 'main.py',
14
+ cognitionSystemPath: path.join(pluginDir, 'dist', 'systems'),
16
15
  };
17
16
 
18
17
  /**
19
- * 运行 Python cognition-system CLI
18
+ * 加载 TypeScript 编译后的 CognitionSystem
20
19
  */
21
- async function runPythonCli(args = []) {
22
- const workspaceDir = process.env.OPENCLAW_WORKSPACE ||
23
- path.join(os.homedir(), '.openclaw', 'workspace');
24
- const pythonScript = path.join(workspaceDir, CONFIG.cognitionSystemPath, CONFIG.mainScript);
25
-
26
- return new Promise((resolve) => {
27
- fs.access(pythonScript).then(() => {
28
- const proc = spawn('python3', [pythonScript, ...args], {
29
- cwd: workspaceDir,
30
- env: {
31
- ...process.env,
32
- OPENCLAW_WORKSPACE: workspaceDir,
33
- PYTHONPATH: path.join(workspaceDir, CONFIG.cognitionSystemPath)
34
- }
35
- });
36
-
37
- let output = '';
38
- let error = '';
39
-
40
- proc.stdout.on('data', (data) => { output += data.toString(); });
41
- proc.stderr.on('data', (data) => { error += data.toString(); });
42
-
43
- proc.on('close', (code) => {
44
- resolve({ success: code === 0, output, error });
45
- });
46
-
47
- proc.on('error', (err) => {
48
- resolve({ success: false, error: err.message });
49
- });
50
-
51
- }).catch(() => {
52
- resolve({ success: false, error: 'Cognition system not found' });
53
- });
54
- });
55
- }
20
+ let CognitionSystem = null;
56
21
 
57
- /**
58
- * 从会话消息中提取文本内容
59
- */
60
- function extractMessageText(message) {
61
- if (!message || !message.content) return '';
62
-
63
- if (typeof message.content === 'string') {
64
- return message.content;
65
- }
66
-
67
- if (Array.isArray(message.content)) {
68
- return message.content
69
- .filter((c) => c.type === 'text')
70
- .map((c) => c.text || '')
71
- .join('');
22
+ async function getCognitionSystem() {
23
+ if (!CognitionSystem) {
24
+ try {
25
+ const module = await import(path.join(CONFIG.cognitionSystemPath, 'cognition.js'));
26
+ CognitionSystem = module.CognitionSystem || module.default;
27
+ } catch (e) {
28
+ console.error('[cognition-system] Failed to load cognition module:', e.message);
29
+ return null;
30
+ }
72
31
  }
73
-
74
- return '';
32
+ return CognitionSystem;
75
33
  }
76
34
 
77
35
  /**
78
- * 处理 message:received - 认知处理
36
+ * 处理 message:received - 更新认知上下文
79
37
  */
80
38
  async function handleMessageReceived(event) {
81
- console.log('[cognition-system] Processing with cognition...');
82
-
83
- const context = event.context || {};
84
- const messages = context.messages || [];
85
-
86
- if (messages.length === 0) return event;
87
-
88
- // 获取最新用户消息
89
- const reversed = [...messages].reverse();
90
- const lastUserMsg = reversed.find((m) => m.role === 'user');
91
-
92
- if (!lastUserMsg) return event;
93
-
94
- const userText = extractMessageText(lastUserMsg);
95
-
96
- if (!userText || userText.startsWith('/')) return event;
39
+ console.log('[cognition-system] Updating cognition context...');
97
40
 
98
- // 获取已分析的意图(来自 input-system)
99
- const intent = context.intent || {};
100
-
101
- if (intent.type) {
102
- // 使用认知系统处理
103
- const result = await runPythonCli(['process', JSON.stringify({
104
- action: intent.action || intent.type,
105
- type: intent.type,
106
- }), '--json']);
107
-
108
- if (result.success && result.output) {
109
- try {
110
- const cognitionResult = JSON.parse(result.output);
111
- context.cognition = cognitionResult;
112
-
113
- // 根据任务步骤调整回复策略
114
- if (cognitionResult.allowed && cognitionResult.next_step) {
115
- context.replyStrategy = {
116
- ...context.replyStrategy,
117
- task: cognitionResult.task,
118
- nextStep: cognitionResult.next_step,
119
- };
120
- }
121
-
122
- console.log('[cognition-system] Cognition result:', cognitionResult.allowed ? 'allowed' : 'denied');
123
- } catch (e) {
124
- console.log('[cognition-system] Parse error:', e.message);
125
- }
41
+ try {
42
+ const CognitionClass = await getCognitionSystem();
43
+ if (CognitionClass) {
44
+ const cognition = new CognitionClass();
45
+ const context = event.context || {};
46
+ const messages = context.messages || [];
47
+
48
+ cognition.updateFromContext(messages);
49
+ console.log('[cognition-system] Context updated');
126
50
  }
51
+ } catch (e) {
52
+ console.log('[cognition-system] Update error:', e.message);
127
53
  }
128
54
 
129
55
  return event;
130
56
  }
131
57
 
132
58
  /**
133
- * 处理 feedback 命令
59
+ * 处理 agent:before - 推理规划
134
60
  */
135
- async function handleFeedback(event) {
136
- const feedback = event.feedback || event.text || '';
61
+ async function handleBeforeAgent(event) {
62
+ console.log('[cognition-system] Reasoning and planning...');
137
63
 
138
- if (feedback) {
139
- const result = await runPythonCli(['learn', feedback]);
140
- console.log('[cognition-system] Learning:', feedback);
64
+ try {
65
+ const CognitionClass = await getCognitionSystem();
66
+ if (CognitionClass) {
67
+ const cognition = new CognitionClass();
68
+ const context = event.context || {};
69
+
70
+ // 可以在这里进行任务分解、决策等
71
+ // 目前是占位符
72
+
73
+ console.log('[cognition-system] Reasoning completed');
74
+ }
75
+ } catch (e) {
76
+ console.log('[cognition-system] Reasoning error:', e.message);
141
77
  }
142
78
 
143
79
  return event;
@@ -148,24 +84,15 @@ async function handleFeedback(event) {
148
84
  */
149
85
  async function handle(event) {
150
86
  const type = event.type || event.event || '';
151
- const action = event.action || '';
152
87
 
153
- console.log(`[cognition-system] Event: ${type}/${action}`);
88
+ console.log(`[cognition-system] Event: ${type}`);
154
89
 
155
90
  try {
156
91
  if (type === 'message' || type === 'message:received') {
157
92
  await handleMessageReceived(event);
158
93
  }
159
- else if (type === 'command') {
160
- if (action === 'learn' || action === 'feedback') {
161
- await handleFeedback(event);
162
- }
163
- else if (action === 'cognition' || action === 'status') {
164
- const result = await runPythonCli(['status', '--json']);
165
- if (result.success) {
166
- event.response = result.output;
167
- }
168
- }
94
+ else if (type === 'agent' || type === 'agent:before') {
95
+ await handleBeforeAgent(event);
169
96
  }
170
97
  } catch (error) {
171
98
  console.error('[cognition-system] Handler error:', error.message);
@@ -178,8 +105,8 @@ module.exports = handle;
178
105
  module.exports.handle = handle;
179
106
  module.exports.metadata = {
180
107
  name: 'cognition-system',
181
- description: '认知系统,推理规划、任务分解、学习适应、决策判断',
182
- events: ['message', 'command'],
108
+ description: 'Cognition System: reasoning, planning, task decomposition',
109
+ events: ['message', 'agent'],
183
110
  version: '1.0.0',
184
111
  };
185
112