company.js
75.7 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
/**
* Company Routes — 公司管理 API
*
* 挂载: /api/company
*/
const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
const { CompanyService } = require('../services/company-service');
const { ScheduleService } = require('../services/schedule-service');
const orgGraphService = require('../services/org-graph-service');
const companyService = new CompanyService();
const scheduleService = new ScheduleService();
/**
* fire-and-forget 触发 orggraph-planning 规划这家公司的 workflow(27-P2 §4.4)。
* 不 await —— 一轮真实 Claude CLI 对话是分钟级的,调用方必须立即返回。
* 写法与本文件 /hire 里触发 agent-creator / innovator 的自调用保持一致。
*/
function triggerOrgGraphPlanning(company, tag = 'OrgGraph') {
const config = require('../config');
const PORT = config.port || 3000;
const { id, name, goal, description } = company || {};
// ⚠️ 必须用 `${companyId}:orggraph-planning` 这个公司限定地址。
// orggraph-planning 是被 hire 进公司的,住在 data/companies/{id}/agents/ 下,
// 裸名 /api/agent/orggraph-planning/chat 会 404 Agent not found。
const namespacedId = `${id}:orggraph-planning`;
fetch(`http://127.0.0.1:${PORT}/api/agent/${encodeURIComponent(namespacedId)}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: `公司 ${id}(${name})已创建。\n公司目标(company-goal):${goal || '(未填写)'}\n公司描述:${description || '(未填写)'}\n请按 orggraph-planning 工作流规划并建立这家公司的 workflow:读 system/org-graph-templates/ 候选骨架 + 可招角色清单,产出执行流图后调用 POST /api/company/${id}/org-graph 落库,再按拓扑序完成招聘。`,
conversationId: `orggraph-bootstrap-${id}-${Date.now().toString(36)}`,
}),
})
// fetch 不会因为 4xx/5xx 而 reject,只在网络层出错时 reject。
// 不显式检查 res.ok 的话,地址写错这类问题会被完全静默吞掉(实测踩过)。
.then(res => {
if (!res.ok) {
console.error(`[${tag}] orggraph-planning 触发失败: HTTP ${res.status} @ ${namespacedId}`);
} else {
console.log(`[${tag}] ✅ 已触发 ${namespacedId} 规划 org graph`);
}
})
.catch(e => console.error(`[${tag}] orggraph-planning 触发失败(网络):`, e.message));
}
// ═══════════════════════════════════════
// Company CRUD
// ═══════════════════════════════════════
// POST /api/company/create
router.post('/create', async (req, res) => {
try {
const { id, name, goal, description } = req.body;
if (!id || !name) return res.status(400).json({ error: 'id 和 name 为必填项' });
// 校验 id 格式 (小写字母、数字、-)
if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(id) && id.length < 2) {
return res.status(400).json({ error: 'id 格式无效 (只允许小写字母、数字、-)' });
}
const company = companyService.create({ id, name, goal, description });
// ── P2 T6:自动招聘 orggraph-planning 并异步触发组织结构规划 ──
// 降级约定(27-P2 §4.4):这一步任何失败都不能影响公司创建本身,
// 最差退化成一家没有 workflow 的空壳公司(等同 P2 上线前的现状)。
try {
const bootstrap = companyService.hire(id, 'orggraph-planning', {});
// 只有拿到真模板(或目录已在)才值得起一轮对话:模板缺失时 hire 会退化成 base 空骨架,
// 那个骨架里没有 §4.1 的八步工作流,触发了也规划不出东西。
if (bootstrap.status === 'hired_from_template' || bootstrap.status === 'already_exists') {
triggerOrgGraphPlanning(company, 'Create');
} else {
console.warn(`[Create] orggraph-planning 招聘未走模板分支 (status=${bootstrap.status}),跳过自动规划;模板就绪后可调 POST /api/company/${id}/org-graph/replan 补跑`);
}
} catch (e) {
console.error('[Create] orggraph-planning 自动招聘失败(不影响公司创建):', e.message);
}
res.json({ success: true, company, message: '公司已创建,正在由 orggraph-planning 自动规划组织结构(异步进行中)。' });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/company/list
router.get('/list', (req, res) => {
res.json(companyService.list());
});
// GET /api/company/templates
router.get('/templates', (req, res) => {
res.json(companyService.listTemplates());
});
// PATCH /api/company/templates/:templateId — 修改模板元信息 (名称, 类型, 描述)
router.patch('/templates/:templateId', (req, res) => {
try {
const { templateId } = req.params;
const { name, type, description } = req.body;
if (name !== undefined && !name.trim()) return res.status(400).json({ error: 'name 为必填项' });
const path = require('path');
const fs = require('fs');
const TEMPLATES_DIR = path.resolve(__dirname, '../../system/templates');
const templateDir = path.join(TEMPLATES_DIR, templateId);
if (!fs.existsSync(templateDir)) {
return res.status(404).json({ error: `模板 "${templateId}" 不存在` });
}
// 1. 更新 config.json 中的字段
const configPath = path.join(templateDir, 'config.json');
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
if (name !== undefined) config.name = name.trim();
if (type !== undefined) config.type = type.trim();
if (description !== undefined) config.description = description.trim();
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
}
// 2. 更新 _registry.json 中的字段
const registryPath = path.join(TEMPLATES_DIR, '_registry.json');
if (fs.existsSync(registryPath)) {
try {
const registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
const entry = registry.find(t => t.id === templateId);
if (entry) {
if (name !== undefined) entry.name = name.trim();
if (type !== undefined) entry.type = type.trim();
if (description !== undefined) entry.description = description.trim();
fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2) + '\n', 'utf-8');
}
} catch {}
}
console.log(`[Template] ✏️ 模板 ${templateId} 元信息已更新`);
res.json({ success: true, id: templateId, name: name?.trim(), type: type?.trim(), description: description?.trim() });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// DELETE /api/company/templates/:templateId — 删除模板
router.delete('/templates/:templateId', (req, res) => {
try {
const { templateId } = req.params;
const path = require('path');
const fs = require('fs');
const TEMPLATES_DIR = path.resolve(__dirname, '../../system/templates');
const templateDir = path.join(TEMPLATES_DIR, templateId);
if (!fs.existsSync(templateDir)) {
return res.status(404).json({ error: `模板 "${templateId}" 不存在` });
}
// 1. 删除模版文件夹
fs.rmSync(templateDir, { recursive: true, force: true });
// 2. 更新 registry
const registryPath = path.join(TEMPLATES_DIR, '_registry.json');
if (fs.existsSync(registryPath)) {
try {
let registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
registry = registry.filter(t => t.id !== templateId);
fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2) + '\n', 'utf-8');
} catch {}
}
console.log(`[Template] 🗑️ 模板 ${templateId} 已被删除`);
res.json({ success: true, message: `模板 ${templateId} 已删除` });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/templates — 创建新模板 Agent
router.post('/templates', async (req, res) => {
try {
const { id, name, type, description } = req.body;
if (!id || !name) return res.status(400).json({ error: 'id 和 name 为必填项' });
if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) {
return res.status(400).json({ error: 'id 格式无效 (只允许小写字母、数字、-)' });
}
const path = require('path');
const fs = require('fs');
const TEMPLATES_DIR = path.resolve(__dirname, '../../system/templates');
const templateDir = path.join(TEMPLATES_DIR, id);
if (fs.existsSync(templateDir)) {
return res.status(409).json({ error: `模板 "${id}" 已存在` });
}
// 使用 AgentScaffold 创建标准骨架
const { AgentScaffold } = await import('../../packages/agent-core/AgentScaffold.js');
const scaffold = new AgentScaffold(TEMPLATES_DIR);
await scaffold.create({
id,
type: type || 'skill',
name: name,
parentId: null,
});
// 如果有 description,追加到 config.json
if (description) {
const configPath = path.join(templateDir, 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
config.description = description;
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
}
console.log(`[Template] ✅ 新模板已创建: ${id} (${type || 'skill'})`);
res.status(201).json({ success: true, id, name, type: type || 'skill' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/templates/:templateId/generate — 调用 Agent Creator 生成定义文件
router.post('/templates/:templateId/generate', async (req, res) => {
try {
const { templateId } = req.params;
const { description } = req.body;
const path = require('path');
const fs = require('fs');
const config = require('../config');
const TEMPLATES_DIR = path.resolve(__dirname, '../../system/templates');
const templateDir = path.join(TEMPLATES_DIR, templateId);
if (!fs.existsSync(templateDir)) {
return res.status(404).json({ error: `模板 "${templateId}" 不存在` });
}
const PORT = config.port || 3000;
const prompt = `请你为模板 Agent "${templateId}" 编写完整的定义文件。
模板位于 \`../../system/templates/${templateId}\` 目录。
该 Agent 的描述/用途: ${description || '通用执行型 Agent'}
请使用 Write 工具为其补充完整的 agent.md, identity.md, soul.md, user.md, tools.md 定义文件。
写完后用 ls 验证目录结构。务必使用 Write 工具写入,不要使用 Edit 工具。`;
// 异步调用 agent-creator
fetch(`http://127.0.0.1:${PORT}/api/agent/agent-creator/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: prompt,
conversationId: `tpl-gen-${templateId}-${Date.now().toString(36)}`,
}),
}).catch(e => console.error('[Template] Agent Creator 请求失败:', e.message));
console.log(`[Template] 🤖 已触发 Agent Creator 为 ${templateId} 生成定义`);
res.json({ success: true, message: `已触发 Agent Creator 为 "${templateId}" 生成定义文件`, status: 'generating' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/templates/:templateId/train — 调用 Innovator 训练模板
router.post('/templates/:templateId/train', async (req, res) => {
try {
const { templateId } = req.params;
const { instructions } = req.body;
const path = require('path');
const fs = require('fs');
const config = require('../config');
const TEMPLATES_DIR = path.resolve(__dirname, '../../system/templates');
const templateDir = path.join(TEMPLATES_DIR, templateId);
if (!fs.existsSync(templateDir)) {
return res.status(404).json({ error: `模板 "${templateId}" 不存在` });
}
const PORT = config.port || 3000;
let prompt = `请你对模板 Agent "${templateId}" 进行评估和训练。
模板位于 \`../../system/templates/${templateId}\` 目录。
请使用 FDE pipeline 对该模板的技能进行评测和进化训练,目标: Benchmark Score ≥ 95。
训练过程包括 Hunt(验证数据), Digest(知识消化), Evolver(技能进化) 等。`;
if (instructions) {
prompt += `\n**【额外训练要求/指令】**\n${instructions}\n`;
}
prompt += `\n请立即开始评估和训练,训练完成后请汇报最终分数。`;
// 异步调用 innovator
fetch(`http://127.0.0.1:${PORT}/api/agent/innovator/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: prompt,
conversationId: `tpl-train-${templateId}-${Date.now().toString(36)}`,
}),
}).catch(e => console.error('[Template] Innovator 请求失败:', e.message));
console.log(`[Template] 🎓 已触发 Innovator 训练 ${templateId}`);
res.json({ success: true, message: `已触发 Innovator 训练 "${templateId}"`, status: 'training' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/templates/:templateId/skills/upload — 上传 Skill 文件/ZIP 包
const multer = require('multer');
const AdmZip = require('adm-zip');
const skillUploadStorage = multer.diskStorage({
destination: (req, file, cb) => {
const os = require('os');
const tmpDir = path.join(os.tmpdir(), `skill-upload-${Date.now()}`);
fs.mkdirSync(tmpDir, { recursive: true });
cb(null, tmpDir);
},
filename: (req, file, cb) => {
// Sanitize filename
const safe = file.originalname.replace(/[^a-zA-Z0-9._-]/g, '_');
cb(null, safe);
},
});
const skillUpload = multer({
storage: skillUploadStorage,
limits: { fileSize: 50 * 1024 * 1024, files: 50 }, // 50MB per file, 50 files max
});
router.post('/templates/:templateId/skills/upload', skillUpload.array('files', 50), async (req, res) => {
try {
const { templateId } = req.params;
const targetSubdir = req.body.targetDir || '.claude/skills'; // default to .claude/skills/ (Claude Code ACP reads from here)
const TEMPLATES_DIR = path.resolve(__dirname, '../../system/templates');
const templateDir = path.join(TEMPLATES_DIR, templateId);
if (!fs.existsSync(templateDir)) {
return res.status(404).json({ error: `模板 "${templateId}" 不存在` });
}
const destDir = path.join(templateDir, targetSubdir);
fs.mkdirSync(destDir, { recursive: true });
const uploadedFiles = req.files || [];
if (uploadedFiles.length === 0) {
return res.status(400).json({ error: '没有上传任何文件' });
}
let extractedCount = 0;
let copiedCount = 0;
const details = [];
for (const file of uploadedFiles) {
const ext = path.extname(file.originalname).toLowerCase();
if (ext === '.zip') {
// ── ZIP 解压 ──
try {
const zip = new AdmZip(file.path);
const entries = zip.getEntries();
// 检测是否整个 ZIP 包在一个顶级目录下(常见的 GitHub 下载格式)
const topDirs = new Set();
for (const entry of entries) {
const firstSegment = entry.entryName.split('/')[0];
topDirs.add(firstSegment);
}
const hasWrapper = topDirs.size === 1 && entries.some(e => e.isDirectory && e.entryName === [...topDirs][0] + '/');
const stripPrefix = hasWrapper ? [...topDirs][0] + '/' : '';
for (const entry of entries) {
if (entry.isDirectory) continue;
// 安全:跳过 __MACOSX、.DS_Store 等系统文件
if (entry.entryName.includes('__MACOSX') || entry.entryName.endsWith('.DS_Store')) continue;
let relativePath = entry.entryName;
if (stripPrefix && relativePath.startsWith(stripPrefix)) {
relativePath = relativePath.substring(stripPrefix.length);
}
if (!relativePath) continue;
const outputPath = path.join(destDir, relativePath);
// 防止路径穿越
if (!outputPath.startsWith(destDir)) continue;
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, entry.getData());
extractedCount++;
details.push({ action: 'extracted', file: `${targetSubdir}/${relativePath}` });
}
} catch (zipErr) {
details.push({ action: 'error', file: file.originalname, error: `ZIP 解压失败: ${zipErr.message}` });
}
} else {
// ── 普通文件直接复制 ──
// 如果上传了带有 webkitRelativePath 的文件夹结构,保留相对路径
const relativePath = file.originalname;
const outputPath = path.join(destDir, relativePath);
// 防止路径穿越
if (!outputPath.startsWith(destDir)) continue;
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.copyFileSync(file.path, outputPath);
copiedCount++;
details.push({ action: 'copied', file: `${targetSubdir}/${relativePath}` });
}
// 清理临时文件
try { fs.unlinkSync(file.path); } catch {}
}
// 清理临时上传目录
for (const file of uploadedFiles) {
try { fs.rmdirSync(path.dirname(file.path)); } catch {}
}
console.log(`[Template] 📥 ${templateId}: Skill 导入完成 - ${extractedCount} extracted, ${copiedCount} copied`);
res.json({
success: true,
templateId,
targetDir: targetSubdir,
stats: { extractedFromZip: extractedCount, copiedFiles: copiedCount, totalFiles: extractedCount + copiedCount },
details,
});
} catch (err) {
console.error('[Template] Skill upload error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* POST /api/company/templates/:templateId/provision
* 系统级依赖安装 — 绕过 ACP,直接 shell 执行
*
* Body: { commands: ["pip install rembg", "npm install ..."], agentDir?: string }
* - commands: 要执行的 shell 命令数组
* - agentDir: 可选,指定公司 agent 目录(不传则在 template 目录执行)
*
* 特点:
* 1. 不走 Claude CLI / ACP,不受 45s idle timeout 限制
* 2. 用 child_process.exec 同步执行,每个命令独立超时 10 分钟
* 3. 返回每个命令的 stdout/stderr 供前端展示
*/
router.post('/templates/:templateId/provision', async (req, res) => {
try {
const { templateId } = req.params;
const { commands, agentDir } = req.body;
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
if (!commands || !Array.isArray(commands) || commands.length === 0) {
return res.status(400).json({ error: '请提供 commands 数组' });
}
// 确定工作目录
const TEMPLATES_DIR = path.resolve(__dirname, '../../data/system/templates');
let workDir;
if (agentDir) {
// 公司 agent 目录
workDir = path.resolve(__dirname, '../../', agentDir);
} else {
workDir = path.join(TEMPLATES_DIR, templateId);
}
if (!fs.existsSync(workDir)) {
return res.status(404).json({ error: `目录不存在: ${workDir}` });
}
// 安全检查:禁止危险命令
const BLOCKED_PATTERNS = [/rm\s+-rf\s+\//, /mkfs/, /dd\s+if=/, />\s*\/dev\//];
for (const cmd of commands) {
if (BLOCKED_PATTERNS.some(p => p.test(cmd))) {
return res.status(400).json({ error: `命令被安全策略拒绝: ${cmd}` });
}
}
console.log(`[Provision] 🔧 ${templateId}: 开始执行 ${commands.length} 个系统命令`);
const results = [];
for (const cmd of commands) {
console.log(`[Provision] ▶ ${cmd}`);
try {
const { stdout, stderr } = await execAsync(cmd, {
cwd: workDir,
timeout: 10 * 60 * 1000, // 每个命令最多 10 分钟
maxBuffer: 10 * 1024 * 1024, // 10MB output buffer
env: { ...process.env, PIP_PROGRESS_BAR: 'off' },
});
results.push({ command: cmd, status: 'success', stdout: stdout.slice(-2000), stderr: stderr.slice(-1000) });
console.log(`[Provision] ✅ ${cmd} 完成`);
} catch (err) {
results.push({ command: cmd, status: 'error', error: err.message, stdout: err.stdout?.slice(-2000), stderr: err.stderr?.slice(-1000) });
console.error(`[Provision] ❌ ${cmd} 失败:`, err.message);
}
}
const allOk = results.every(r => r.status === 'success');
res.json({
success: allOk,
templateId,
workDir,
results,
});
} catch (err) {
console.error('[Provision] Error:', err);
res.status(500).json({ error: err.message });
}
});
// GET /api/company/templates/:templateId/logs — 获取模板相关的 agent-creator / innovator 执行日志
router.get('/templates/:templateId/logs', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const templateId = req.params.templateId;
const AGENTS_DIR = path.resolve(__dirname, '../../system/agents');
const logs = [];
// 扫描 agent-creator 和 innovator 的对话,匹配 tpl-gen-{id} 和 tpl-train-{id}
const scanAgents = [
{ agentId: 'agent-creator', prefix: `tpl-gen-${templateId}`, type: 'generate', label: '🤖 Agent Creator' },
{ agentId: 'innovator', prefix: `tpl-train-${templateId}`, type: 'train', label: '🎓 Innovator' },
];
for (const scan of scanAgents) {
const convDir = path.join(AGENTS_DIR, scan.agentId, 'conversations');
if (!fs.existsSync(convDir)) continue;
const dirs = fs.readdirSync(convDir, { withFileTypes: true })
.filter(d => d.isDirectory() && d.name.startsWith(scan.prefix));
for (const d of dirs) {
const metaPath = path.join(convDir, d.name, 'meta.json');
const histPath = path.join(convDir, d.name, 'history.json');
let meta = {}, history = [];
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')); } catch {}
try { history = JSON.parse(fs.readFileSync(histPath, 'utf-8')); } catch {}
// 提取最后一条 assistant 消息作为摘要
const lastAssistant = [...history].reverse().find(m => m.role === 'assistant');
logs.push({
conversationId: d.name,
agentId: scan.agentId,
type: scan.type,
label: scan.label,
createdAt: meta.createdAt || null,
messageCount: history.length,
summary: lastAssistant ? (lastAssistant.content || '').slice(0, 500) : '(执行中...)',
status: lastAssistant ? 'done' : 'running',
});
}
}
// 按时间倒序
logs.sort((a, b) => new Date(b.createdAt || 0).getTime() - new Date(a.createdAt || 0).getTime());
res.json(logs);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/templates/:templateId/files
router.get('/templates/:templateId/files', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../system/templates');
const templateDir = path.join(DATA_DIR, req.params.templateId);
if (!fs.existsSync(templateDir)) {
return res.json({ tree: [], totalFiles: 0 });
}
function scanDir(dirPath, relativePath = '') {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
const nodes = [];
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if ((entry.name.startsWith('.') && entry.name !== '.claude') || entry.name === 'node_modules') continue;
if (entry.isDirectory()) {
const children = scanDir(fullPath, relPath);
nodes.push({
name: entry.name,
path: relPath,
type: 'directory',
children,
fileCount: children.reduce((sum, c) => sum + (c.type === 'file' ? 1 : (c.fileCount || 0)), 0),
});
} else {
const stat = fs.statSync(fullPath);
nodes.push({
name: entry.name,
path: relPath,
type: 'file',
size: stat.size,
modifiedAt: stat.mtime.toISOString(),
});
}
}
return nodes.sort((a, b) => {
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
return a.name.localeCompare(b.name);
});
}
const tree = scanDir(templateDir);
const countFiles = (nodes) => nodes.reduce((sum, n) => sum + (n.type === 'file' ? 1 : countFiles(n.children || [])), 0);
res.json({ tree, totalFiles: countFiles(tree) });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/templates/:templateId/files/content
router.get('/templates/:templateId/files/content', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../system/templates');
const filePath = req.query.path;
if (!filePath) return res.status(400).json({ error: 'path 参数为必填' });
const absPath = path.resolve(DATA_DIR, req.params.templateId, filePath);
const safeBoundary = path.resolve(DATA_DIR, req.params.templateId);
if (!absPath.startsWith(safeBoundary)) {
return res.status(403).json({ error: '路径越界' });
}
if (!fs.existsSync(absPath)) {
return res.status(404).json({ error: '文件不存在' });
}
const stat = fs.statSync(absPath);
if (stat.size > 512 * 1024) {
return res.json({ content: '(文件过大,跳过预览)', truncated: true, size: stat.size });
}
const content = fs.readFileSync(absPath, 'utf-8');
res.json({ content, size: stat.size, path: filePath });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// PUT /api/company/templates/:templateId/files/content — 保存模板文件内容
router.put('/templates/:templateId/files/content', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../system/templates');
const filePath = req.body.path;
if (!filePath) return res.status(400).json({ error: 'path 参数为必填' });
const absPath = path.resolve(DATA_DIR, req.params.templateId, filePath);
const safeBoundary = path.resolve(DATA_DIR, req.params.templateId);
if (!absPath.startsWith(safeBoundary)) {
return res.status(403).json({ error: '路径越界' });
}
// 确保目录存在
const dir = path.dirname(absPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(absPath, req.body.content || '', 'utf-8');
console.log(`[Template] 💾 已保存模板文件 ${req.params.templateId}/${filePath}`);
res.json({ success: true, path: filePath });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId
router.get('/:companyId', (req, res) => {
const company = companyService.get(req.params.companyId);
if (!company) return res.status(404).json({ error: '公司不存在' });
res.json(company);
});
// PUT /api/company/:companyId
router.put('/:companyId', (req, res) => {
const company = companyService.update(req.params.companyId, req.body);
if (!company) return res.status(404).json({ error: '公司不存在' });
res.json({ success: true, company });
});
// DELETE /api/company/:companyId
router.delete('/:companyId', (req, res) => {
const company = companyService.delete(req.params.companyId);
if (!company) return res.status(404).json({ error: '公司不存在' });
res.json({ success: true, company });
});
// POST /api/company/:companyId/shutdown
router.post('/:companyId/shutdown', (req, res) => {
const company = companyService.shutdown(req.params.companyId);
if (!company) return res.status(404).json({ error: '公司不存在' });
// 停止该公司下所有 Agent 的心跳
try {
const heartbeatService = require('../services/heartbeat-service');
const agents = companyService.listAgents(req.params.companyId);
for (const agent of agents) {
const namespacedId = `${req.params.companyId}:${agent.id}`;
if (heartbeatService.timers.has(namespacedId)) {
clearInterval(heartbeatService.timers.get(namespacedId));
heartbeatService.timers.delete(namespacedId);
console.log(`[Company] 🛑 已停止 ${namespacedId} 的心跳`);
}
}
} catch (err) {
console.warn(`[Company] ⚠️ 停止心跳时出错: ${err.message}`);
}
res.json({ success: true, company });
});
// POST /api/company/:companyId/start — 启动公司
router.post('/:companyId/start', (req, res) => {
try {
const company = companyService.get(req.params.companyId);
if (!company) return res.status(404).json({ error: '公司不存在' });
// 更新状态
const updated = companyService.update(req.params.companyId, {
status: 'running',
heartbeat: { enabled: true },
});
// 激活该公司下所有 Agent 的心跳
try {
const heartbeatService = require('../services/heartbeat-service');
const agents = companyService.listAgents(req.params.companyId);
for (const agent of agents) {
const namespacedId = `${req.params.companyId}:${agent.id}`;
heartbeatService._setupAgentHeartbeat(namespacedId);
}
console.log(`[Company] ✅ ${req.params.companyId} 已启动,${agents.length} 个 Agent 心跳已激活`);
} catch (err) {
console.warn(`[Company] ⚠️ 激活心跳时出错: ${err.message}`);
}
res.json({ success: true, company: updated });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId/status — 获取公司运行状态(含 Agent 进程信息)
router.get('/:companyId/status', (req, res) => {
try {
const company = companyService.get(req.params.companyId);
if (!company) return res.status(404).json({ error: '公司不存在' });
const agents = companyService.listAgents(req.params.companyId);
const heartbeatService = require('../services/heartbeat-service');
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
// 计算运行时长
const uptimeMs = company.status === 'running' && company.startedAt
? Date.now() - new Date(company.startedAt).getTime()
: 0;
const agentStatuses = agents.map(agent => {
const namespacedId = `${req.params.companyId}:${agent.id}`;
const hasHeartbeat = heartbeatService.timers.has(namespacedId);
// 读取每个 Agent 自己的心跳配置
let heartbeatConfig = { enabled: false, intervalMinutes: 15 };
try {
const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', agent.id, 'config.json');
if (fs.existsSync(configPath)) {
const cfg = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
if (cfg.heartbeat) {
heartbeatConfig = cfg.heartbeat;
}
}
} catch {}
return {
id: agent.id,
name: agent.name,
type: agent.type,
status: agent.status,
heartbeatActive: hasHeartbeat,
heartbeatEnabled: heartbeatConfig.enabled || false,
heartbeatInterval: heartbeatConfig.intervalMinutes || 15,
};
});
res.json({
id: company.id,
name: company.name,
description: company.description,
status: company.status,
createdAt: company.createdAt,
updatedAt: company.updatedAt,
startedAt: company.startedAt || null,
uptimeMs,
heartbeat: company.heartbeat,
agents: agentStatuses,
agentCount: agents.length,
activeAgentCount: agentStatuses.filter(a => a.heartbeatActive).length,
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Per-Agent 心跳控制
// ═══════════════════════════════════════
// PUT /api/company/:companyId/agents/:agentId/heartbeat — 更新 Agent 心跳配置
router.put('/:companyId/agents/:agentId/heartbeat', (req, res) => {
try {
const { intervalMinutes, enabled } = req.body;
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'config.json');
if (!fs.existsSync(configPath)) {
return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` });
}
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
if (!config.heartbeat) config.heartbeat = { intervalMinutes: 15, enabled: false };
// 保证有合理的默认值
if (config.heartbeat.intervalMinutes === undefined) config.heartbeat.intervalMinutes = 15;
if (config.heartbeat.enabled === undefined) config.heartbeat.enabled = false;
if (intervalMinutes !== undefined) config.heartbeat.intervalMinutes = Number(intervalMinutes);
if (enabled !== undefined) config.heartbeat.enabled = Boolean(enabled);
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
// 如果正在运行,重新挂载心跳
const heartbeatService = require('../services/heartbeat-service');
const namespacedId = `${req.params.companyId}:${req.params.agentId}`;
if (config.heartbeat.enabled) {
heartbeatService._setupAgentHeartbeat(namespacedId);
} else if (heartbeatService.timers.has(namespacedId)) {
clearInterval(heartbeatService.timers.get(namespacedId));
heartbeatService.timers.delete(namespacedId);
}
console.log(`[Company] ⚙️ ${namespacedId} 心跳配置更新: interval=${config.heartbeat.intervalMinutes}min, enabled=${config.heartbeat.enabled}`);
res.json({ success: true, heartbeat: config.heartbeat });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/:companyId/agents/:agentId/heartbeat/start — 启动单个 Agent 心跳
router.post('/:companyId/agents/:agentId/heartbeat/start', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'config.json');
if (!fs.existsSync(configPath)) {
return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` });
}
// 更新 config 中的 enabled
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
if (!config.heartbeat) config.heartbeat = { intervalMinutes: 15 };
config.heartbeat.enabled = true;
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
// 激活心跳
const heartbeatService = require('../services/heartbeat-service');
const namespacedId = `${req.params.companyId}:${req.params.agentId}`;
heartbeatService._setupAgentHeartbeat(namespacedId);
console.log(`[Company] 💓 ${namespacedId} 心跳已启动`);
res.json({ success: true, message: `${namespacedId} 心跳已启动` });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/:companyId/agents/:agentId/heartbeat/stop — 停止单个 Agent 心跳
router.post('/:companyId/agents/:agentId/heartbeat/stop', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'config.json');
if (!fs.existsSync(configPath)) {
return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` });
}
// 更新 config 中的 enabled
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
if (!config.heartbeat) config.heartbeat = {};
config.heartbeat.enabled = false;
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
// 停止心跳
const heartbeatService = require('../services/heartbeat-service');
const namespacedId = `${req.params.companyId}:${req.params.agentId}`;
if (heartbeatService.timers.has(namespacedId)) {
clearInterval(heartbeatService.timers.get(namespacedId));
heartbeatService.timers.delete(namespacedId);
}
console.log(`[Company] 🛑 ${namespacedId} 心跳已停止`);
res.json({ success: true, message: `${namespacedId} 心跳已停止` });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Agent 技能查询
// ═══════════════════════════════════════
// GET /api/company/:companyId/agents/:agentId/skills — 获取 Agent 技能列表
router.get('/:companyId/agents/:agentId/skills', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const skillsDir = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'skills');
if (!fs.existsSync(skillsDir)) {
return res.json([]);
}
const skills = fs.readdirSync(skillsDir, { withFileTypes: true })
.filter(d => d.isDirectory())
.map(d => d.name);
res.json(skills);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Agent 招聘
// ═══════════════════════════════════════
// POST /api/company/:companyId/hire
router.post('/:companyId/hire', async (req, res) => {
try {
const { role, type, name, description, customAgent, customSoul, customUser } = req.body;
if (!role) return res.status(400).json({ error: 'role 为必填项' });
const result = await companyService.hireWithTraining(req.params.companyId, role, {
type, name: name || role, description, customAgent, customSoul, customUser,
});
// ── 核心逻辑扩展:自动补充定义 + 搜索注入 3 个初始 Skill + Innovator 训练 ──
if (result.status === 'training' || result.needsTraining) {
(async () => {
try {
console.log(`[Hire] 🚀 自动流水线启动: 为新员工 ${role} 安排 [定义 → 技能注入 → 训练]`);
const fs = require('fs');
const path = require('path');
const config = require('../config');
const skillDb = require('../services/skill-db');
const namespacedId = `${req.params.companyId}:${role}`;
const agentDir = result.agentDir || path.resolve(__dirname, '../../data/companies', req.params.companyId, 'agents', role);
const PORT = config.port || 3000;
// 1. 发起 Agent-Creator 编写骨架定义 (异步不等待)
fetch(`http://127.0.0.1:${PORT}/api/agent/agent-creator/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: `新员工 ${namespacedId} 已由脚手架创建空白目录在 \`../${req.params.companyId}/agents/${role}\`。工作需求: ${description || name || role}。\n请你按照标准模板,使用 Write 工具为该员工补充完整的定义文件(agent.md, identity.md, soul.md, user.md等)并使用工具 ls 验证。务必要使用 Write 写文件,不要使用 Edit 工具。写完后请答复。`,
conversationId: `create-${req.params.companyId}-${role}-${Date.now().toString(36)}`
})
}).catch(e => console.error('[Hire] Agent-Creator 请求错误:', e.message));
// 2. 去网上/Arena搜索并注入 3 个基础 Skill
const skills = skillDb.searchSkills(role, { limit: 3 });
const skillsDir = path.join(agentDir, 'skills');
if (skills && skills.length > 0) {
if (!fs.existsSync(skillsDir)) fs.mkdirSync(skillsDir, { recursive: true });
const copyDir = (src, dest) => {
fs.mkdirSync(dest, { recursive: true });
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const e of entries) {
if (e.isDirectory()) copyDir(path.join(src, e.name), path.join(dest, e.name));
else fs.copyFileSync(path.join(src, e.name), path.join(dest, e.name));
}
};
for (const skill of skills) {
if (skill.directory && fs.existsSync(skill.directory)) {
const targetPath = path.join(skillsDir, skill.skillName);
if (!fs.existsSync(targetPath)) {
try {
copyDir(skill.directory, targetPath);
console.log(`[Hire] 💉 成功为其注入基础技能: ${skill.skillName}`);
} catch (e) {
console.error(`[Hire] 注入技能 ${skill.skillName} 失败:`, e.message);
}
}
}
}
} else {
console.log(`[Hire] ⚠️ 网上/Arena 未找到该角色的匹配 Skill,将交由 Innovator 凭空生成`);
}
// 3. 延时 5 秒触发 Innovator 进行评估与训练 (等 creator 写入完毕)
setTimeout(() => {
fetch(`http://127.0.0.1:${PORT}/api/agent/innovator/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: `公司 ${req.params.companyId} 的员工 ${role} 骨架和基础技能已注入完毕。请你使用 FDE pipeline 对该 Agent ${namespacedId} (特别是它的技能)进行评测和进化训练,直到 Benchmark 达标 (Score ≥ 95)。训练过程包括 Hunt(验证数据), Digest, Evolver 等。请立即开始评估和训练,并保持向我汇报。`,
conversationId: `train-${req.params.companyId}-${role}-${Date.now().toString(36)}`
})
}).catch(e => console.error('[Hire] Innovator 请求错误:', e.message));
}, 5000);
} catch (err) {
console.error(`[Hire Orchestration] 自动流水线编排异常: ${err.message}`);
}
})();
}
// ── P0 FIX: 动态心跳挂载 ──
// 招聘成功后,立即为这个新 Agent 注册心跳定时器(如果它的 config.json 里 heartbeat.enabled = true)
try {
const heartbeatService = require('../services/heartbeat-service');
const namespacedId = `${req.params.companyId}:${role}`;
heartbeatService._setupAgentHeartbeat(namespacedId);
console.log(`[Hire] 💓 已为 ${namespacedId} 动态挂载心跳`);
} catch (hbErr) {
console.warn(`[Hire] ⚠️ 心跳挂载跳过: ${hbErr.message}`);
}
res.json(result);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// POST /api/company/:companyId/fire — 辞退 Agent(招留管退之"退")
router.post('/:companyId/fire', (req, res) => {
try {
const { role, archive } = req.body;
if (!role) return res.status(400).json({ error: 'role 为必填项' });
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const companyId = req.params.companyId;
const agentDir = path.join(DATA_DIR, companyId, 'agents', role);
if (!fs.existsSync(agentDir)) {
return res.status(404).json({ error: `Agent ${role} 不存在于公司 ${companyId}` });
}
// 1. 停止心跳
const heartbeatService = require('../services/heartbeat-service');
const namespacedId = `${companyId}:${role}`;
if (heartbeatService.timers.has(namespacedId)) {
clearInterval(heartbeatService.timers.get(namespacedId));
heartbeatService.timers.delete(namespacedId);
}
// 2. 归档或直接删除
if (archive !== false) {
const archiveDir = path.join(DATA_DIR, companyId, '_archived_agents', role);
fs.mkdirSync(path.dirname(archiveDir), { recursive: true });
fs.renameSync(agentDir, archiveDir);
console.log(`[Fire] 📦 ${namespacedId} 已归档到 ${archiveDir}`);
} else {
fs.rmSync(agentDir, { recursive: true, force: true });
console.log(`[Fire] 🗑️ ${namespacedId} 已彻底删除`);
}
// 3. 从公司 agents 列表中移除
const company = companyService.get(companyId);
if (company) {
company.agents = (company.agents || []).filter(a => a !== role);
company.updatedAt = new Date().toISOString();
companyService._saveCompany(company);
}
// 4. P2 T7:org_graph 里对应节点软删除(级联失效它的进出边)
try {
orgGraphService.removeNode(companyId, role);
} catch (e) {
console.warn('[Fire] org_graph 清理失败(不影响辞退结果):', e.message);
}
console.log(`[Fire] 🔴 ${namespacedId} 已辞退`);
res.json({ success: true, message: `${namespacedId} 已辞退`, archived: archive !== false });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Org Graph — 公司级 workflow 图(P2 / 27-P2 §4.3)
// ═══════════════════════════════════════
// POST /api/company/:companyId/org-graph — 整体写入(规划产物落库)
// body: { nodes: [{roleName, systemAgentId?}], edges: [{from, to, condition, edgeKind?}] }(边的 from/to 是 roleName)
router.post('/:companyId/org-graph', (req, res) => {
try {
const { nodes, edges } = req.body || {};
const result = orgGraphService.writeGraph(req.params.companyId, { nodes, edges });
// 校验失败返回 400 + errors[{rule, detail}],供 orggraph-planning 自行修正后重试
if (!result.ok) return res.status(400).json({ error: '图不合法', errors: result.errors });
res.json({ success: true, ...result });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// PATCH /api/company/:companyId/org-graph — 增量修改(改完整张图仍须合法,否则整体回滚)
// body: { addNodes?, removeNodes?, addEdges?, removeEdges? }
router.patch('/:companyId/org-graph', (req, res) => {
try {
const result = orgGraphService.patchGraph(req.params.companyId, req.body || {});
if (!result.ok) return res.status(400).json({ error: '图不合法', errors: result.errors });
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId/org-graph — 只读;公司无图时返回空数组,不报错
// 返回 { nodes: [{id, roleName, systemAgentId, status}], edges: [{from, to, condition, edgeKind}] }(边的 from/to 是节点 id)
router.get('/:companyId/org-graph', (req, res) => {
try {
res.json(orgGraphService.getGraph(req.params.companyId));
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/:companyId/org-graph/replan — 对已有公司手动重跑规划(存量公司补图入口)
// 异步:立即返回,agent 跑完后自己调上面的 POST 写入新图
router.post('/:companyId/org-graph/replan', (req, res) => {
try {
const company = companyService.get(req.params.companyId);
if (!company) return res.status(404).json({ error: `公司 ${req.params.companyId} 不存在` });
try {
// 幂等:已经雇过就是 already_exists,不重复建目录
companyService.hire(company.id, 'orggraph-planning', {});
} catch (e) {
console.warn('[Replan] orggraph-planning 招聘跳过:', e.message);
}
triggerOrgGraphPlanning(company, 'Replan');
res.json({ status: 'replanning', companyId: company.id });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/company/:companyId/deposit-template — 训练合格后沉淀为模板
router.post('/:companyId/deposit-template', (req, res) => {
try {
const { agentId, benchmarkScore } = req.body;
if (!agentId || benchmarkScore === undefined) {
return res.status(400).json({ error: 'agentId 和 benchmarkScore 为必填项' });
}
const result = companyService.depositTemplate(
req.params.companyId, agentId, Number(benchmarkScore)
);
res.json(result);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/company/:companyId/agents
router.get('/:companyId/agents', (req, res) => {
const agents = companyService.listAgents(req.params.companyId);
res.json(agents);
});
// ═══════════════════════════════════════
// Company Goals / OKR (公司级 OKR)
// ═══════════════════════════════════════
const { OkrService } = require('../services/okr-service');
// 公司级 OKR 路由。每条同时挂 /okr(新,27-NAMING §六)与 /goals(旧,向后兼容别名)。
// 路径参数统一叫 :objectiveId(原 :goalId)——第 1 层节点已正名为 Objective。
const okrPath = (suffix = '') => [
`/:companyId/okr${suffix}`,
`/:companyId/goals${suffix}`,
];
// GET /api/company/:companyId/okr
router.get(okrPath(), (req, res) => {
const okr = new OkrService(req.params.companyId);
res.json(okr.list());
});
// POST /api/company/:companyId/okr
router.post(okrPath(), (req, res) => {
try {
const { title, description, owner } = req.body;
if (!title || !owner) {
return res.status(400).json({ error: 'title 和 owner 为必填项' });
}
const okr = new OkrService(req.params.companyId);
res.status(201).json(okr.create({ title, description, owner }));
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId/okr/:objectiveId
router.get(okrPath('/:objectiveId'), (req, res) => {
const okr = new OkrService(req.params.companyId);
const objective = okr.get(req.params.objectiveId);
if (!objective) return res.status(404).json({ error: 'Objective not found' });
res.json(objective);
});
// PUT /api/company/:companyId/okr/:objectiveId
router.put(okrPath('/:objectiveId'), (req, res) => {
const okr = new OkrService(req.params.companyId);
const result = okr.updateObjective(req.params.objectiveId, req.body);
if (!result) return res.status(404).json({ error: 'Objective not found' });
res.json(result);
});
// POST /api/company/:companyId/okr/:objectiveId/nodes
router.post(okrPath('/:objectiveId/nodes'), (req, res) => {
try {
const { parentNodeId, title, owner, priority } = req.body;
if (!title || !owner) {
return res.status(400).json({ error: 'title 和 owner 为必填项' });
}
const okr = new OkrService(req.params.companyId);
const result = okr.addNode(req.params.objectiveId, parentNodeId || null, {
title, owner, priority,
});
if (!result) return res.status(404).json({ error: 'Objective not found' });
res.status(201).json({ nodeId: result.nodeId, node: result.objective.nodes[result.nodeId] });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// PUT /api/company/:companyId/okr/:objectiveId/nodes/:nodeId
router.put(okrPath('/:objectiveId/nodes/:nodeId'), (req, res) => {
const okr = new OkrService(req.params.companyId);
const result = okr.updateNode(req.params.objectiveId, req.params.nodeId, req.body);
if (!result) return res.status(404).json({ error: 'Node not found' });
res.json({ nodeId: result.nodeId, node: result.node });
});
// GET /api/company/:companyId/okr/:objectiveId/progress
router.get(okrPath('/:objectiveId/progress'), (req, res) => {
const okr = new OkrService(req.params.companyId);
const progress = okr.getProgress(req.params.objectiveId);
if (!progress) return res.status(404).json({ error: 'Objective not found' });
res.json(progress);
});
// ═══════════════════════════════════════
// Pipeline / SOP 流水线
// ═══════════════════════════════════════
const { PipelineService } = require('../services/pipeline-service');
// POST /api/company/:companyId/pipelines — 创建流水线
router.post('/:companyId/pipelines', (req, res) => {
try {
const pSvc = new PipelineService(req.params.companyId);
const pipeline = pSvc.createPipeline(req.body);
res.status(201).json(pipeline);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/company/:companyId/pipelines — 列出流水线
router.get('/:companyId/pipelines', (req, res) => {
const pSvc = new PipelineService(req.params.companyId);
res.json(pSvc.listPipelines());
});
// GET /api/company/:companyId/pipelines/:pipelineId — 获取流水线定义
router.get('/:companyId/pipelines/:pipelineId', (req, res) => {
const pSvc = new PipelineService(req.params.companyId);
const pipeline = pSvc.getPipeline(req.params.pipelineId);
if (!pipeline) return res.status(404).json({ error: '流水线不存在' });
res.json(pipeline);
});
// PUT /api/company/:companyId/pipelines/:pipelineId — 更新流水线
router.put('/:companyId/pipelines/:pipelineId', (req, res) => {
const pSvc = new PipelineService(req.params.companyId);
const pipeline = pSvc.updatePipeline(req.params.pipelineId, req.body);
if (!pipeline) return res.status(404).json({ error: '流水线不存在' });
res.json(pipeline);
});
// POST /api/company/:companyId/pipelines/:pipelineId/run — 启动运行
router.post('/:companyId/pipelines/:pipelineId/run', (req, res) => {
try {
const pSvc = new PipelineService(req.params.companyId);
const run = pSvc.startRun(req.params.pipelineId, req.body);
res.status(201).json(run);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/company/:companyId/pipelines/runs/list — 列出运行记录
router.get('/:companyId/pipelines/runs/list', (req, res) => {
const pSvc = new PipelineService(req.params.companyId);
res.json(pSvc.listRuns(req.query.pipelineId));
});
// GET /api/company/:companyId/pipelines/runs/:runId — 获取运行详情
router.get('/:companyId/pipelines/runs/:runId', (req, res) => {
const pSvc = new PipelineService(req.params.companyId);
const run = pSvc.getRun(req.params.runId);
if (!run) return res.status(404).json({ error: '运行记录不存在' });
res.json(run);
});
// POST /api/company/:companyId/pipelines/runs/:runId/advance — 推进步骤
router.post('/:companyId/pipelines/runs/:runId/advance', (req, res) => {
try {
const pSvc = new PipelineService(req.params.companyId);
const { stepIndex, output, status } = req.body;
if (stepIndex === undefined) return res.status(400).json({ error: 'stepIndex 为必填项' });
const run = pSvc.advanceStep(req.params.runId, Number(stepIndex), { output, status });
res.json(run);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/company/:companyId/pipelines/runs/:runId/current — 获取当前任务
router.get('/:companyId/pipelines/runs/:runId/current', (req, res) => {
const pSvc = new PipelineService(req.params.companyId);
const task = pSvc.getCurrentTask(req.params.runId);
if (!task) return res.json({ message: '无就绪任务' });
res.json(task);
});
// POST /api/company/:companyId/pipelines/runs/:runId/reject — COO 驳回步骤
router.post('/:companyId/pipelines/runs/:runId/reject', (req, res) => {
try {
const pSvc = new PipelineService(req.params.companyId);
const { stepIndex, reason, reviewedBy } = req.body;
if (stepIndex === undefined) return res.status(400).json({ error: 'stepIndex 为必填项' });
const run = pSvc.rejectStep(req.params.runId, Number(stepIndex), {
reason: reason || '',
reviewedBy: reviewedBy || 'coo',
});
res.json(run);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// Schedule (日程管理)
// ═══════════════════════════════════════
// GET /api/company/:companyId/schedule — 获取日程
router.get('/:companyId/schedule', (req, res) => {
res.json(scheduleService.getSchedule(req.params.companyId));
});
// POST /api/company/:companyId/schedule/slots — 添加日程
router.post('/:companyId/schedule/slots', (req, res) => {
try {
const slot = scheduleService.addSlot(req.params.companyId, req.body);
res.json(slot);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// PUT /api/company/:companyId/schedule/slots/:slotId — 更新日程
router.put('/:companyId/schedule/slots/:slotId', (req, res) => {
const slot = scheduleService.updateSlot(req.params.companyId, req.params.slotId, req.body);
if (!slot) return res.status(404).json({ error: '日程不存在' });
res.json(slot);
});
// DELETE /api/company/:companyId/schedule/slots/:slotId — 删除日程
router.delete('/:companyId/schedule/slots/:slotId', (req, res) => {
scheduleService.removeSlot(req.params.companyId, req.params.slotId);
res.json({ success: true });
});
// ═══════════════════════════════════════
// DataSource (运营数据接入)
// ═══════════════════════════════════════
const { DataSourceService } = require('../services/datasource-service');
const dataSourceService = new DataSourceService();
// GET /api/company/:companyId/data/metrics — 获取运营指标
router.get('/:companyId/data/metrics', async (req, res) => {
try {
const { source = 'mock', startDate, endDate } = req.query;
const sd = startDate || new Date(Date.now() - 7 * 86400000).toISOString().slice(0, 10);
const ed = endDate || new Date().toISOString().slice(0, 10);
const data = await dataSourceService.fetchMetrics(source, { startDate: sd, endDate: ed });
res.json(data);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/company/:companyId/data/trending — 获取热点趋势
router.get('/:companyId/data/trending', async (req, res) => {
try {
const { source = 'mock', platform = 'weibo', count = '10' } = req.query;
const data = await dataSourceService.fetchTrending(source, { platform, count: parseInt(count, 10) });
res.json(data);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/company/:companyId/data/attribution — 归因分析
router.get('/:companyId/data/attribution', async (req, res) => {
try {
const { source = 'mock' } = req.query;
const now = new Date();
const currentEnd = now.toISOString().slice(0, 10);
const currentStart = new Date(now.getTime() - 7 * 86400000).toISOString().slice(0, 10);
const previousEnd = new Date(now.getTime() - 7 * 86400000).toISOString().slice(0, 10);
const previousStart = new Date(now.getTime() - 14 * 86400000).toISOString().slice(0, 10);
const analysis = await dataSourceService.analyzeAttribution(
source,
{ startDate: currentStart, endDate: currentEnd },
{ startDate: previousStart, endDate: previousEnd }
);
res.json(analysis);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Company Files — 公司级统一文件树
// ═══════════════════════════════════════
// GET /api/company/:companyId/files — 获取公司下所有 Agent 的文件树
router.get('/:companyId/files', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const companyDir = path.join(DATA_DIR, req.params.companyId);
if (!fs.existsSync(companyDir)) {
return res.json({ tree: [], totalFiles: 0 });
}
// 递归扫描目录
function scanDir(dirPath, relativePath = '') {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
const nodes = [];
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
// 跳过隐藏文件和 node_modules
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
// 跳过 conversations 目录(太大)
if (entry.name === 'conversations') continue;
if (entry.isDirectory()) {
const children = scanDir(fullPath, relPath);
nodes.push({
name: entry.name,
path: relPath,
type: 'directory',
children,
fileCount: children.reduce((sum, c) => sum + (c.type === 'file' ? 1 : (c.fileCount || 0)), 0),
});
} else {
const stat = fs.statSync(fullPath);
nodes.push({
name: entry.name,
path: relPath,
type: 'file',
size: stat.size,
modifiedAt: stat.mtime.toISOString(),
});
}
}
// 目录排前面, 然后按名字排序
return nodes.sort((a, b) => {
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
return a.name.localeCompare(b.name);
});
}
const tree = scanDir(companyDir);
const countFiles = (nodes) => nodes.reduce((sum, n) => sum + (n.type === 'file' ? 1 : countFiles(n.children || [])), 0);
res.json({ tree, totalFiles: countFiles(tree) });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId/files/content?path=xxx — 读取文件内容
router.get('/:companyId/files/content', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const filePath = req.query.path;
if (!filePath) return res.status(400).json({ error: 'path 参数为必填' });
// 安全校验:防止路径穿越
const absPath = path.resolve(DATA_DIR, req.params.companyId, filePath);
const safeBoundary = path.resolve(DATA_DIR, req.params.companyId);
if (!absPath.startsWith(safeBoundary)) {
return res.status(403).json({ error: '路径越界' });
}
if (!fs.existsSync(absPath)) {
return res.status(404).json({ error: '文件不存在' });
}
const stat = fs.statSync(absPath);
if (stat.size > 512 * 1024) {
return res.json({ content: '(文件过大,跳过预览)', truncated: true, size: stat.size });
}
const content = fs.readFileSync(absPath, 'utf-8');
res.json({ content, size: stat.size, path: filePath });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// PUT /api/company/:companyId/files/content — 保存文件内容
router.put('/:companyId/files/content', (req, res) => {
try {
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const filePath = req.body.path;
if (!filePath) return res.status(400).json({ error: 'path 参数为必填' });
const absPath = path.resolve(DATA_DIR, req.params.companyId, filePath);
const safeBoundary = path.resolve(DATA_DIR, req.params.companyId);
if (!absPath.startsWith(safeBoundary)) {
return res.status(403).json({ error: '路径越界' });
}
const dir = path.dirname(absPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(absPath, req.body.content || '', 'utf-8');
console.log(`[Company] 💾 已保存文件 ${req.params.companyId}/${filePath}`);
res.json({ success: true, path: filePath });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Company Workspace — 工作区文件管理
// ═══════════════════════════════════════
// GET /api/company/:companyId/workspace/files — 列出 workspace 文件树
router.get('/:companyId/workspace/files', (req, res) => {
try {
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const wsDir = path.join(DATA_DIR, req.params.companyId, 'workspace');
if (!fs.existsSync(wsDir)) {
return res.json({ tree: [], totalFiles: 0 });
}
function scanDir(dirPath, relativePath = '') {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
const nodes = [];
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
if (entry.isDirectory()) {
const children = scanDir(fullPath, relPath);
nodes.push({
name: entry.name, path: relPath, type: 'directory', children,
fileCount: children.reduce((sum, c) => sum + (c.type === 'file' ? 1 : (c.fileCount || 0)), 0),
});
} else {
const stat = fs.statSync(fullPath);
nodes.push({
name: entry.name, path: relPath, type: 'file',
size: stat.size,
createdAt: stat.birthtime.toISOString(),
modifiedAt: stat.mtime.toISOString(),
});
}
}
return nodes.sort((a, b) => {
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
return a.name.localeCompare(b.name);
});
}
const tree = scanDir(wsDir);
const countFiles = (nodes) => nodes.reduce((sum, n) => sum + (n.type === 'file' ? 1 : countFiles(n.children || [])), 0);
res.json({ tree, totalFiles: countFiles(tree) });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId/workspace/files/content?path=xxx — 读取 workspace 文件内容
router.get('/:companyId/workspace/files/content', (req, res) => {
try {
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const filePath = String(req.query.path || '');
if (!filePath) return res.status(400).json({ error: 'path 参数为必填' });
const absPath = path.resolve(DATA_DIR, req.params.companyId, 'workspace', filePath);
const safeBoundary = path.resolve(DATA_DIR, req.params.companyId, 'workspace');
if (!absPath.startsWith(safeBoundary)) {
return res.status(403).json({ error: '路径越界' });
}
if (!fs.existsSync(absPath)) {
return res.status(404).json({ error: '文件不存在' });
}
const stat = fs.statSync(absPath);
if (stat.size > 512 * 1024) {
return res.json({ content: '(文件过大,跳过预览)', truncated: true, size: stat.size });
}
const content = fs.readFileSync(absPath, 'utf-8');
res.json({
content, size: stat.size, path: filePath,
createdAt: stat.birthtime.toISOString(),
modifiedAt: stat.mtime.toISOString(),
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// PUT /api/company/:companyId/workspace/files/content — 保存 workspace 文件
router.put('/:companyId/workspace/files/content', (req, res) => {
try {
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const filePath = req.body.path;
if (!filePath) return res.status(400).json({ error: 'path 参数为必填' });
const absPath = path.resolve(DATA_DIR, req.params.companyId, 'workspace', filePath);
const safeBoundary = path.resolve(DATA_DIR, req.params.companyId, 'workspace');
if (!absPath.startsWith(safeBoundary)) {
return res.status(403).json({ error: '路径越界' });
}
const dir = path.dirname(absPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(absPath, req.body.content || '', 'utf-8');
console.log(`[Workspace] 💾 已保存 ${req.params.companyId}/workspace/${filePath}`);
res.json({ success: true, path: filePath });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Company Messages — 全局消息时间线
// ═══════════════════════════════════════
// GET /api/company/:companyId/messages?limit=100 — 获取公司所有 Agent 的消息时间线
router.get('/:companyId/messages', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data/companies');
const agentsDir = path.join(DATA_DIR, req.params.companyId, 'agents');
const limit = Math.min(parseInt(req.query.limit) || 200, 500);
if (!fs.existsSync(agentsDir)) {
return res.json([]);
}
const allMessages = [];
const agents = fs.readdirSync(agentsDir, { withFileTypes: true }).filter(d => d.isDirectory());
for (const agentEntry of agents) {
const agentId = agentEntry.name;
const convDir = path.join(agentsDir, agentId, 'conversations');
if (!fs.existsSync(convDir)) continue;
const conversations = fs.readdirSync(convDir, { withFileTypes: true }).filter(d => d.isDirectory());
for (const conv of conversations) {
const convId = conv.name;
// 读 meta
let meta = null;
try {
meta = JSON.parse(fs.readFileSync(path.join(convDir, convId, 'meta.json'), 'utf-8'));
} catch { continue; }
// 读 history
let history = [];
try {
history = JSON.parse(fs.readFileSync(path.join(convDir, convId, 'history.json'), 'utf-8'));
} catch { continue; }
for (const msg of history) {
allMessages.push({
agentId: `${req.params.companyId}:${agentId}`,
agentName: agentId,
conversationId: convId,
conversationTitle: meta?.title || convId,
role: msg.role,
content: (msg.content || '').slice(0, 800),
timestamp: msg.timestamp || meta?.createdAt,
messageId: msg.messageId,
taskId: convId.startsWith('task-') ? convId.replace('task-', '') : null,
});
}
}
}
// 按时间倒序
allMessages.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
res.json(allMessages.slice(0, limit));
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ═══════════════════════════════════════
// Company Stats — 统计 API (skills count, jobs status)
// ═══════════════════════════════════════
// GET /api/company/:companyId/stats — 获取公司统计信息
router.get('/:companyId/stats', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data');
const companyId = req.params.companyId;
// 1. Skills 统计 - 统计所有 Agent 的 Skill 数量
let totalSkills = 0;
const agentSkills = [];
const agentsDir = path.join(DATA_DIR, 'companies', companyId, 'agents');
if (fs.existsSync(agentsDir)) {
const agentDirs = fs.readdirSync(agentsDir, { withFileTypes: true }).filter(d => d.isDirectory());
for (const agentDir of agentDirs) {
const skillsDir = path.join(agentsDir, agentDir.name, 'skills');
if (fs.existsSync(skillsDir)) {
const skillCount = fs.readdirSync(skillsDir, { withFileTypes: true }).filter(d => d.isDirectory()).length;
totalSkills += skillCount;
agentSkills.push({ agentId: agentDir.name, skillCount });
}
}
}
// 2. Agents 统计
const agents = companyService.listAgents(companyId);
const agentCount = agents.length;
// 3. Jobs 统计 - 从 jobs 持久化文件读取
let jobsStats = { total: 0, queued: 0, running: 0, completed: 0, failed: 0 };
const jobsFilePath = path.join(DATA_DIR, '.data', 'jobs-openapi.json');
if (fs.existsSync(jobsFilePath)) {
try {
const jobsData = JSON.parse(fs.readFileSync(jobsFilePath, 'utf-8'));
if (Array.isArray(jobsData)) {
jobsStats.total = jobsData.length;
for (const job of jobsData) {
if (jobsStats[job.status] !== undefined) {
jobsStats[job.status]++;
}
}
}
} catch (e) {
console.warn('[Stats] 读取 Jobs 文件失败:', e.message);
}
}
// 4. Pipelines 统计
const pSvc = new PipelineService(companyId);
const pipelines = pSvc.listPipelines();
const runs = pSvc.listRuns();
const pipelinesStats = {
total: pipelines.length,
active: pipelines.filter(p => p.status === 'active').length,
runs: {
total: runs.length,
running: runs.filter(r => r.status === 'running').length,
completed: runs.filter(r => r.status === 'completed').length,
failed: runs.filter(r => r.status === 'failed').length,
}
};
res.json({
companyId,
timestamp: new Date().toISOString(),
skills: { total: totalSkills, byAgent: agentSkills },
agents: { total: agentCount },
jobs: jobsStats,
pipelines: pipelinesStats,
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId/jobs — 获取公司相关的 Job 列表
router.get('/:companyId/jobs', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data');
const jobsFilePath = path.join(DATA_DIR, '.data', 'jobs-openapi.json');
if (!fs.existsSync(jobsFilePath)) {
return res.json([]);
}
const jobsData = JSON.parse(fs.readFileSync(jobsFilePath, 'utf-8'));
if (!Array.isArray(jobsData)) {
return res.json([]);
}
// 过滤与公司相关的 Jobs (通过 domain 或 conversationId 包含 companyId)
const limit = Math.min(parseInt(req.query.limit) || 50, 100);
const companyId = req.params.companyId;
const filtered = jobsData
.filter(job => !job.domain || job.domain.includes(companyId))
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
.slice(0, limit);
res.json(filtered);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/company/:companyId/jobs/:jobId — 获取 Job 详情
router.get('/:companyId/jobs/:jobId', (req, res) => {
try {
const path = require('path');
const fs = require('fs');
const DATA_DIR = path.resolve(__dirname, '../../data');
const jobsFilePath = path.join(DATA_DIR, '.data', 'jobs-openapi.json');
if (!fs.existsSync(jobsFilePath)) {
return res.status(404).json({ error: 'Job 不存在' });
}
const jobsData = JSON.parse(fs.readFileSync(jobsFilePath, 'utf-8'));
if (!Array.isArray(jobsData)) {
return res.status(404).json({ error: 'Job 不存在' });
}
const job = jobsData.find(j => j.jobId === req.params.jobId);
if (!job) {
return res.status(404).json({ error: 'Job 不存在' });
}
// 返回安全版本 (隐藏 apiKey, webhookUrl)
const { apiKey, webhookUrl, ...safeJob } = job;
res.json(safeJob);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;