company-service.js
15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/**
* CompanyService — 公司实例管理
*
* 数据目录: data/{companyId}/
* 模板库: data/templates/
*
* 核心职责:
* 1. Company CRUD (create/get/list/shutdown)
* 2. Agent 招聘 (hire: 模板优先 → 培养兜底)
* 3. resolveAgentDir(companyId, agentId) 统一寻址
*/
const fs = require('fs');
const path = require('path');
const DATA_DIR = path.resolve(__dirname, '../../data');
const TEMPLATES_DIR = path.join(DATA_DIR, 'templates');
const GLOBAL_AGENTS_DIR = path.join(DATA_DIR, 'agents');
// 模板骨架文件白名单 (复制这些,不复制 memory/workspace/conversations 等运行态数据)
const TEMPLATE_FILES = [
'agent.md', 'soul.md', 'identity.md', 'user.md', 'tools.md',
'heartbeat.md', 'plan.md', 'todo.md', 'cron.json', 'config.json',
];
class CompanyService {
// ═══════════════════════════════════════
// Company CRUD
// ═══════════════════════════════════════
/**
* 创建一家新公司
* @param {object} opts - { id, name, description }
*/
create({ id, name, description = '' }) {
const companyDir = path.join(DATA_DIR, id);
if (fs.existsSync(companyDir)) {
throw new Error(`公司 ${id} 已存在`);
}
// 创建目录结构
const subdirs = ['agents', 'goals', 'pipelines', 'workspace', 'workspace/assets', 'workspace/output'];
for (const sub of subdirs) {
fs.mkdirSync(path.join(companyDir, sub), { recursive: true });
}
const now = new Date().toISOString();
const company = {
id,
name,
description,
status: 'creating', // creating → running → paused → shutdown
createdAt: now,
updatedAt: now,
createdBy: 'master',
ceo: null,
sop: null,
agents: [],
heartbeat: {
enabled: false, // CEO 上任后才开启
intervalMinutes: 30,
},
config: {
timezone: 'Asia/Shanghai',
maxAgents: 20,
},
};
this._saveCompany(company);
console.log(`[Company] 🏢 创建公司: ${id} (${name})`);
return company;
}
/**
* 获取公司详情
*/
get(companyId) {
const fp = path.join(DATA_DIR, companyId, 'company.json');
if (!fs.existsSync(fp)) return null;
return JSON.parse(fs.readFileSync(fp, 'utf-8'));
}
/**
* 列出所有公司
*/
list() {
if (!fs.existsSync(DATA_DIR)) return [];
return fs.readdirSync(DATA_DIR, { withFileTypes: true })
.filter(d => d.isDirectory() && fs.existsSync(path.join(DATA_DIR, d.name, 'company.json')))
.map(d => {
const company = this.get(d.name);
if (!company) return null;
return {
id: company.id,
name: company.name,
status: company.status,
agentCount: company.agents ? company.agents.length : 0,
ceo: company.ceo,
updatedAt: company.updatedAt,
};
})
.filter(Boolean);
}
/**
* 更新公司信息
*/
update(companyId, updates) {
const company = this.get(companyId);
if (!company) return null;
if (updates.name !== undefined) company.name = updates.name;
if (updates.description !== undefined) company.description = updates.description;
if (updates.status !== undefined) company.status = updates.status;
if (updates.sop !== undefined) company.sop = updates.sop;
if (updates.heartbeat !== undefined) company.heartbeat = { ...company.heartbeat, ...updates.heartbeat };
company.updatedAt = new Date().toISOString();
this._saveCompany(company);
return company;
}
/**
* 关停公司 (软关停: 标记状态, 停止心跳, 保留数据)
*/
shutdown(companyId) {
const company = this.get(companyId);
if (!company) return null;
company.status = 'shutdown';
company.heartbeat.enabled = false;
company.updatedAt = new Date().toISOString();
this._saveCompany(company);
console.log(`[Company] 🛑 关停公司: ${companyId}`);
return company;
}
// ═══════════════════════════════════════
// Agent 招聘系统 (Hiring Pipeline)
// ═══════════════════════════════════════
/**
* 招聘一个 Agent 到公司
*
* 流程: 模板库查找 → 复制 → 注入公司上下文
* 模板不存在 → 返回 { needsTraining: true } (由上层调用 agent-creator + innovator)
*
* @param {string} companyId
* @param {string} roleName - 角色名 (如 "ceo", "content-writer")
* @param {object} opts - { customAgent, customSoul, ... } 可选的上下文覆盖
* @returns {object} { status, agentId, agentDir, needsTraining? }
*/
hire(companyId, roleName, opts = {}) {
const company = this.get(companyId);
if (!company) throw new Error(`公司 ${companyId} 不存在`);
const targetDir = path.join(DATA_DIR, companyId, 'agents', roleName);
if (fs.existsSync(targetDir)) {
return { status: 'already_exists', agentId: roleName, agentDir: targetDir };
}
// 阶段 A: 在模板库中查找
const templateDir = path.join(TEMPLATES_DIR, roleName);
if (fs.existsSync(templateDir)) {
// ✅ 模板存在 → 复制骨架到公司
this._copyTemplate(templateDir, targetDir);
this._injectCompanyContext(companyId, roleName, opts);
this._updateTemplateUsedCount(roleName);
// 更新公司的 agents 列表
if (!company.agents.includes(roleName)) {
company.agents.push(roleName);
}
// 如果是 CEO,标记到 company.ceo
const agentConfig = this._readAgentConfig(targetDir);
if (agentConfig && agentConfig.type === 'cxo') {
company.ceo = roleName;
}
company.updatedAt = new Date().toISOString();
this._saveCompany(company);
console.log(`[Company] ✅ ${companyId} 招聘 ${roleName} (从模板)`);
return { status: 'hired_from_template', agentId: roleName, agentDir: targetDir };
}
// 阶段 B: 模板不存在 → 需要培养
console.log(`[Company] ⚠️ 模板库中不存在 "${roleName}",需要 agent-creator + innovator 培养`);
return {
status: 'needs_training',
agentId: roleName,
agentDir: targetDir,
needsTraining: true,
};
}
/**
* 解雇 (suspend) 公司内的 Agent
*/
fire(companyId, agentId) {
const company = this.get(companyId);
if (!company) return null;
const agentDir = path.join(DATA_DIR, companyId, 'agents', agentId);
if (!fs.existsSync(agentDir)) return null;
// 更新 config.json 状态
const configPath = path.join(agentDir, 'config.json');
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
config.status = 'suspended';
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
}
// 从公司 agents 列表移除
company.agents = company.agents.filter(a => a !== agentId);
company.updatedAt = new Date().toISOString();
this._saveCompany(company);
console.log(`[Company] 🚪 ${companyId} 解雇 ${agentId}`);
return { status: 'suspended', agentId };
}
/**
* 列出公司内的所有 Agent (含状态)
*/
listAgents(companyId) {
const agentsDir = path.join(DATA_DIR, companyId, 'agents');
if (!fs.existsSync(agentsDir)) return [];
return fs.readdirSync(agentsDir, { withFileTypes: true })
.filter(d => d.isDirectory())
.map(d => {
const config = this._readAgentConfig(path.join(agentsDir, d.name));
return {
id: d.name,
name: config?.name || d.name,
type: config?.type || 'unknown',
status: config?.status || 'unknown',
companyId,
};
});
}
// ═══════════════════════════════════════
// 模板库管理
// ═══════════════════════════════════════
/**
* 列出所有可用模板
*/
listTemplates() {
const registryPath = path.join(TEMPLATES_DIR, '_registry.json');
if (fs.existsSync(registryPath)) {
return JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
}
// 如果没有 registry,从目录扫描生成
return this.rebuildTemplateRegistry();
}
/**
* 重建模板注册表
*/
rebuildTemplateRegistry() {
if (!fs.existsSync(TEMPLATES_DIR)) {
fs.mkdirSync(TEMPLATES_DIR, { recursive: true });
return [];
}
const registry = fs.readdirSync(TEMPLATES_DIR, { withFileTypes: true })
.filter(d => d.isDirectory())
.map(d => {
const config = this._readAgentConfig(path.join(TEMPLATES_DIR, d.name));
return {
id: d.name,
name: config?.name || d.name,
type: config?.type || 'unknown',
description: config?.description || '',
benchmarkScore: config?.benchmarkScore || null,
trainedAt: config?.trainedAt || null,
usedCount: config?.usedCount || 0,
};
});
fs.writeFileSync(
path.join(TEMPLATES_DIR, '_registry.json'),
JSON.stringify(registry, null, 2),
'utf-8'
);
return registry;
}
// ═══════════════════════════════════════
// Agent 统一寻址
// ═══════════════════════════════════════
/**
* 统一定位 Agent 目录
* @param {string|null} companyId - null 表示全局 Agent
* @param {string} agentId
* @returns {string|null} 绝对路径, 不存在则返回 null
*/
static resolveAgentDir(companyId, agentId) {
if (companyId) {
// 公司内 Agent
const dir = path.join(DATA_DIR, companyId, 'agents', agentId);
if (fs.existsSync(dir)) return dir;
}
// 全局 Agent
const globalDir = path.join(GLOBAL_AGENTS_DIR, agentId);
if (fs.existsSync(globalDir)) return globalDir;
return null;
}
// ═══════════════════════════════════════
// 私有方法
// ═══════════════════════════════════════
_saveCompany(company) {
const dir = path.join(DATA_DIR, company.id);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'company.json'), JSON.stringify(company, null, 2), 'utf-8');
}
_readAgentConfig(agentDir) {
const fp = path.join(agentDir, 'config.json');
if (!fs.existsSync(fp)) return null;
try { return JSON.parse(fs.readFileSync(fp, 'utf-8')); }
catch { return null; }
}
/**
* 复制模板骨架到目标目录 (只复制 md/json 骨架文件,不复制运行态数据)
*/
_copyTemplate(srcDir, destDir) {
fs.mkdirSync(destDir, { recursive: true });
// 复制白名单中的骨架文件
for (const file of TEMPLATE_FILES) {
const srcFile = path.join(srcDir, file);
if (fs.existsSync(srcFile)) {
fs.copyFileSync(srcFile, path.join(destDir, file));
}
}
// 复制 skills/ 目录 (如果存在)
const srcSkills = path.join(srcDir, 'skills');
if (fs.existsSync(srcSkills)) {
this._copyDirRecursive(srcSkills, path.join(destDir, 'skills'));
}
// 初始化空的 memory 目录
const memoryDir = path.join(destDir, 'memory');
fs.mkdirSync(memoryDir, { recursive: true });
fs.writeFileSync(path.join(memoryDir, 'memory.md'), '# 我的记忆\n\n## 关键事实\n\n_(刚入职,尚无记忆)_\n\n## 已验证的模式\n\n## 失败教训\n', 'utf-8');
}
_copyDirRecursive(src, dest) {
fs.mkdirSync(dest, { recursive: true });
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
this._copyDirRecursive(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
/**
* 注入公司上下文到新复制的 Agent
*/
_injectCompanyContext(companyId, agentId, opts = {}) {
const company = this.get(companyId);
if (!company) return;
const agentDir = path.join(DATA_DIR, companyId, 'agents', agentId);
// 1. 更新 config.json: 添加 companyId, 设置状态为 active
const configPath = path.join(agentDir, 'config.json');
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
config.companyId = companyId;
config.status = 'active';
if (config.type === 'cxo') {
config.parent_id = 'master';
} else {
config.parent_id = company.ceo || 'ceo';
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
}
// 2. 追加公司信息到 agent.md
const agentMdPath = path.join(agentDir, 'agent.md');
if (fs.existsSync(agentMdPath)) {
const content = fs.readFileSync(agentMdPath, 'utf-8');
const companyContext = [
'',
'---',
'',
'## 所属公司',
`- **公司ID**: ${companyId}`,
`- **公司名称**: ${company.name}`,
`- **公司使命**: ${company.description || '待定义'}`,
'',
`> 你是 **${company.name}** 的员工。你的所有工作都应围绕公司的使命和目标展开。`,
opts.customAgent || '',
].join('\n');
fs.writeFileSync(agentMdPath, content + companyContext, 'utf-8');
}
// 3. 重写 user.md: 指明上级关系
const userMdPath = path.join(agentDir, 'user.md');
const userContent = [
'# 与上级的关系',
'',
'## 所属公司',
`- **公司**: ${company.name} (${companyId})`,
'',
'## 汇报对象',
];
const agentConfig = this._readAgentConfig(agentDir);
if (agentConfig && agentConfig.type === 'cxo') {
userContent.push('- **直接汇报**: Master (公司创始人/董事会)');
userContent.push('- **管理范围**: 公司内所有 Agent');
} else {
userContent.push(`- **直接汇报**: ${company.ceo || 'CEO'} (公司 CEO)`);
userContent.push('- **协同**: 公司内其他同事');
}
userContent.push('', '## 沟通规则');
userContent.push('1. 完成任务后主动向上级汇报结果');
userContent.push('2. 遇到阻碍时及时上报,附带解决建议');
userContent.push('3. 保持透明,坏消息更要及时同步');
userContent.push(opts.customUser || '');
fs.writeFileSync(userMdPath, userContent.join('\n'), 'utf-8');
// 4. 追加公司文化到 soul.md (如有自定义)
if (opts.customSoul) {
const soulPath = path.join(agentDir, 'soul.md');
if (fs.existsSync(soulPath)) {
const soulContent = fs.readFileSync(soulPath, 'utf-8');
fs.writeFileSync(soulPath, soulContent + '\n\n## 公司文化\n' + opts.customSoul + '\n', 'utf-8');
}
}
}
/**
* 更新模板使用次数
*/
_updateTemplateUsedCount(templateId) {
const registryPath = path.join(TEMPLATES_DIR, '_registry.json');
if (!fs.existsSync(registryPath)) return;
try {
const registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
const entry = registry.find(t => t.id === templateId);
if (entry) {
entry.usedCount = (entry.usedCount || 0) + 1;
fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), 'utf-8');
}
} catch (err) {
console.warn(`[Company] ⚠️ 更新模板使用次数失败: ${err.message}`);
}
}
}
module.exports = { CompanyService };