@kenhkl/agent-gate 0.8.2 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/trigger_rules.yaml +585 -0
- package/dist/shared/storage/db.d.ts +26 -9
- package/dist/shared/storage/db.js +281 -47
- package/dist/v1/cli.js +419 -64
- package/dist/v1/server.js +326 -64
- package/dist/v3/cli.js +545 -236
- package/package.json +1 -1
package/dist/v1/cli.js
CHANGED
|
@@ -54,6 +54,8 @@ __export(security_exports, {
|
|
|
54
54
|
agentInflight: () => agentInflight,
|
|
55
55
|
agentTokens: () => agentTokens,
|
|
56
56
|
allowedOrigins: () => allowedOrigins,
|
|
57
|
+
archiveKeepRecords: () => archiveKeepRecords,
|
|
58
|
+
archiveThresholdRecords: () => archiveThresholdRecords,
|
|
57
59
|
authConfigError: () => authConfigError,
|
|
58
60
|
authEnabled: () => authEnabled,
|
|
59
61
|
authMode: () => authMode,
|
|
@@ -66,6 +68,8 @@ __export(security_exports, {
|
|
|
66
68
|
checkToken: () => checkToken,
|
|
67
69
|
cookiePathAllowed: () => cookiePathAllowed,
|
|
68
70
|
describe: () => describe,
|
|
71
|
+
diskDegradePercent: () => diskDegradePercent,
|
|
72
|
+
diskWarnPercent: () => diskWarnPercent,
|
|
69
73
|
ensureAutoToken: () => ensureAutoToken,
|
|
70
74
|
ensurePrivateDir: () => ensurePrivateDir,
|
|
71
75
|
failFastOnAuthError: () => failFastOnAuthError,
|
|
@@ -78,6 +82,7 @@ __export(security_exports, {
|
|
|
78
82
|
maxConnections: () => maxConnections,
|
|
79
83
|
maxInflight: () => maxInflight,
|
|
80
84
|
maxQueue: () => maxQueue,
|
|
85
|
+
maxRecordBytes: () => maxRecordBytes,
|
|
81
86
|
normalizeOrigin: () => normalizeOrigin,
|
|
82
87
|
noteQueueReject: () => noteQueueReject,
|
|
83
88
|
noteSessionAccess: () => noteSessionAccess,
|
|
@@ -363,6 +368,21 @@ function bindAgent(principal, agentType) {
|
|
|
363
368
|
function maxBodyBytes() {
|
|
364
369
|
return envInt("AGENT_GATE_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
365
370
|
}
|
|
371
|
+
function maxRecordBytes() {
|
|
372
|
+
return envInt("AGENT_GATE_MAX_RECORD_BYTES", 1024 * 1024);
|
|
373
|
+
}
|
|
374
|
+
function archiveThresholdRecords() {
|
|
375
|
+
return envInt("AGENT_GATE_ARCHIVE_THRESHOLD", 1e5);
|
|
376
|
+
}
|
|
377
|
+
function archiveKeepRecords() {
|
|
378
|
+
return envInt("AGENT_GATE_ARCHIVE_KEEP", 5e4);
|
|
379
|
+
}
|
|
380
|
+
function diskWarnPercent() {
|
|
381
|
+
return envInt("AGENT_GATE_DISK_WARN_PERCENT", 5);
|
|
382
|
+
}
|
|
383
|
+
function diskDegradePercent() {
|
|
384
|
+
return envInt("AGENT_GATE_DISK_DEGRADE_PERCENT", 2);
|
|
385
|
+
}
|
|
366
386
|
function maxInflight() {
|
|
367
387
|
return poolLimit("biz");
|
|
368
388
|
}
|
|
@@ -581,6 +601,66 @@ var init_security = __esm({
|
|
|
581
601
|
}
|
|
582
602
|
});
|
|
583
603
|
|
|
604
|
+
// src/shared/storage/record-guard.ts
|
|
605
|
+
function clipText(value, limit = maxRecordBytes()) {
|
|
606
|
+
const s = String(value ?? "");
|
|
607
|
+
if (limit <= 0 || s.length <= limit) return s;
|
|
608
|
+
const head = s.slice(0, limit);
|
|
609
|
+
const digest = (0, import_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 16);
|
|
610
|
+
return `${head}\u2026[truncated ${s.length - limit}B sha256:${digest}]`;
|
|
611
|
+
}
|
|
612
|
+
function diskFreePercent(targetPath) {
|
|
613
|
+
try {
|
|
614
|
+
const st = (0, import_fs.statfsSync)((0, import_path.dirname)(targetPath));
|
|
615
|
+
const total = Number(st.blocks) || 0;
|
|
616
|
+
const avail = Number(st.bavail) || 0;
|
|
617
|
+
if (!total) return 100;
|
|
618
|
+
return avail / total * 100;
|
|
619
|
+
} catch {
|
|
620
|
+
return 100;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function shouldDegradeWrites(targetPath) {
|
|
624
|
+
const degrade = diskDegradePercent();
|
|
625
|
+
if (degrade <= 0) return false;
|
|
626
|
+
return diskFreePercent(targetPath) < degrade;
|
|
627
|
+
}
|
|
628
|
+
function degradeRecord(rec) {
|
|
629
|
+
const command = String(rec.command ?? "");
|
|
630
|
+
const clipped = command.length > DEGRADE_COMMAND_BYTES ? `${command.slice(0, DEGRADE_COMMAND_BYTES)}\u2026[degraded]` : command;
|
|
631
|
+
return {
|
|
632
|
+
...rec,
|
|
633
|
+
command: clipped,
|
|
634
|
+
action_detail: String(rec.action_detail ?? "") > "" ? String(rec.action_detail).slice(0, DEGRADE_COMMAND_BYTES) : "",
|
|
635
|
+
description: "",
|
|
636
|
+
reason: String(rec.reason ?? "").slice(0, 256)
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
function prepareRecordForStorage(rec, targetPath) {
|
|
640
|
+
let out = {
|
|
641
|
+
...rec,
|
|
642
|
+
command: clipText(rec.command),
|
|
643
|
+
action_detail: clipText(rec.action_detail),
|
|
644
|
+
reason: clipText(rec.reason, 4096),
|
|
645
|
+
description: clipText(rec.description, 4096)
|
|
646
|
+
};
|
|
647
|
+
const degraded = shouldDegradeWrites(targetPath);
|
|
648
|
+
if (degraded) out = degradeRecord(out);
|
|
649
|
+
return { record: out, degraded };
|
|
650
|
+
}
|
|
651
|
+
var import_crypto, import_fs, import_path, DEGRADE_COMMAND_BYTES;
|
|
652
|
+
var init_record_guard = __esm({
|
|
653
|
+
"src/shared/storage/record-guard.ts"() {
|
|
654
|
+
"use strict";
|
|
655
|
+
init_cjs_shims();
|
|
656
|
+
import_crypto = require("crypto");
|
|
657
|
+
import_fs = require("fs");
|
|
658
|
+
import_path = require("path");
|
|
659
|
+
init_security();
|
|
660
|
+
DEGRADE_COMMAND_BYTES = 512;
|
|
661
|
+
}
|
|
662
|
+
});
|
|
663
|
+
|
|
584
664
|
// src/shared/storage/json-storage.ts
|
|
585
665
|
var json_storage_exports = {};
|
|
586
666
|
__export(json_storage_exports, {
|
|
@@ -591,17 +671,18 @@ function nowISO() {
|
|
|
591
671
|
}
|
|
592
672
|
function getDefaultDataDir() {
|
|
593
673
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
594
|
-
const xdgData = process.env.XDG_DATA_HOME || (0,
|
|
595
|
-
return (0,
|
|
674
|
+
const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
|
|
675
|
+
return (0, import_path2.join)(xdgData, "agent_gate", "storage");
|
|
596
676
|
}
|
|
597
|
-
var
|
|
677
|
+
var import_fs2, import_path2, JsonStorage;
|
|
598
678
|
var init_json_storage = __esm({
|
|
599
679
|
"src/shared/storage/json-storage.ts"() {
|
|
600
680
|
"use strict";
|
|
601
681
|
init_cjs_shims();
|
|
602
|
-
|
|
603
|
-
|
|
682
|
+
import_fs2 = require("fs");
|
|
683
|
+
import_path2 = require("path");
|
|
604
684
|
init_security();
|
|
685
|
+
init_record_guard();
|
|
605
686
|
JsonStorage = class {
|
|
606
687
|
dataDir;
|
|
607
688
|
agentsPath;
|
|
@@ -614,11 +695,11 @@ var init_json_storage = __esm({
|
|
|
614
695
|
sessionLocks = /* @__PURE__ */ new Map();
|
|
615
696
|
constructor(dataDir) {
|
|
616
697
|
this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
|
|
617
|
-
this.agentsPath = (0,
|
|
618
|
-
this.sessionsPath = (0,
|
|
619
|
-
this.toolCallsDir = (0,
|
|
620
|
-
if (!(0,
|
|
621
|
-
if (!(0,
|
|
698
|
+
this.agentsPath = (0, import_path2.join)(this.dataDir, "agents.json");
|
|
699
|
+
this.sessionsPath = (0, import_path2.join)(this.dataDir, "sessions.json");
|
|
700
|
+
this.toolCallsDir = (0, import_path2.join)(this.dataDir, "tool_calls");
|
|
701
|
+
if (!(0, import_fs2.existsSync)(this.dataDir)) (0, import_fs2.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
|
|
702
|
+
if (!(0, import_fs2.existsSync)(this.toolCallsDir)) (0, import_fs2.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
|
|
622
703
|
this.hardenStoragePermissions();
|
|
623
704
|
this.nextId = this.recoverNextId();
|
|
624
705
|
}
|
|
@@ -630,10 +711,10 @@ var init_json_storage = __esm({
|
|
|
630
711
|
const uid = process.getuid?.();
|
|
631
712
|
const tighten = (p, mode) => {
|
|
632
713
|
try {
|
|
633
|
-
const st = (0,
|
|
714
|
+
const st = (0, import_fs2.statSync)(p);
|
|
634
715
|
if (st.isSymbolicLink()) return;
|
|
635
716
|
if (uid !== void 0 && st.uid !== uid) return;
|
|
636
|
-
if ((st.mode & 511) !== mode) (0,
|
|
717
|
+
if ((st.mode & 511) !== mode) (0, import_fs2.chmodSync)(p, mode);
|
|
637
718
|
} catch {
|
|
638
719
|
}
|
|
639
720
|
};
|
|
@@ -642,9 +723,9 @@ var init_json_storage = __esm({
|
|
|
642
723
|
tighten(this.agentsPath, 384);
|
|
643
724
|
tighten(this.sessionsPath, 384);
|
|
644
725
|
try {
|
|
645
|
-
for (const f of (0,
|
|
726
|
+
for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
|
|
646
727
|
if (f.endsWith(".json") || f.endsWith(".tmp")) {
|
|
647
|
-
tighten((0,
|
|
728
|
+
tighten((0, import_path2.join)(this.toolCallsDir, f), 384);
|
|
648
729
|
}
|
|
649
730
|
}
|
|
650
731
|
} catch {
|
|
@@ -654,9 +735,9 @@ var init_json_storage = __esm({
|
|
|
654
735
|
recoverNextId() {
|
|
655
736
|
let maxId = 0;
|
|
656
737
|
try {
|
|
657
|
-
const files = (0,
|
|
738
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
658
739
|
for (const file of files) {
|
|
659
|
-
const records = this.readJsonFile((0,
|
|
740
|
+
const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
|
|
660
741
|
for (const r of records) {
|
|
661
742
|
if (r.id > maxId) maxId = r.id;
|
|
662
743
|
}
|
|
@@ -667,19 +748,19 @@ var init_json_storage = __esm({
|
|
|
667
748
|
}
|
|
668
749
|
readJsonFile(path, fallback) {
|
|
669
750
|
try {
|
|
670
|
-
if (!(0,
|
|
671
|
-
return JSON.parse((0,
|
|
751
|
+
if (!(0, import_fs2.existsSync)(path)) return fallback;
|
|
752
|
+
return JSON.parse((0, import_fs2.readFileSync)(path, "utf-8"));
|
|
672
753
|
} catch {
|
|
673
754
|
return fallback;
|
|
674
755
|
}
|
|
675
756
|
}
|
|
676
757
|
/** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
|
|
677
758
|
writeJsonFile(path, data) {
|
|
678
|
-
const dir = (0,
|
|
679
|
-
if (!(0,
|
|
759
|
+
const dir = (0, import_path2.dirname)(path);
|
|
760
|
+
if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true, mode: 448 });
|
|
680
761
|
const tmp = path + ".tmp";
|
|
681
|
-
(0,
|
|
682
|
-
(0,
|
|
762
|
+
(0, import_fs2.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
|
|
763
|
+
(0, import_fs2.renameSync)(tmp, path);
|
|
683
764
|
}
|
|
684
765
|
loadAgents() {
|
|
685
766
|
const raw = this.readJsonFile(this.agentsPath, {});
|
|
@@ -697,12 +778,12 @@ var init_json_storage = __esm({
|
|
|
697
778
|
}
|
|
698
779
|
loadToolCalls(sessionId) {
|
|
699
780
|
return this.readJsonFile(
|
|
700
|
-
(0,
|
|
781
|
+
(0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`),
|
|
701
782
|
[]
|
|
702
783
|
);
|
|
703
784
|
}
|
|
704
785
|
saveToolCalls(sessionId, records) {
|
|
705
|
-
this.writeJsonFile((0,
|
|
786
|
+
this.writeJsonFile((0, import_path2.join)(this.toolCallsDir, `${sessionId}.json`), records);
|
|
706
787
|
}
|
|
707
788
|
getOrCreateAgent(agentType, hostname, version2 = "") {
|
|
708
789
|
const agents = this.loadAgents();
|
|
@@ -747,6 +828,10 @@ var init_json_storage = __esm({
|
|
|
747
828
|
return Math.max(...records.map((r) => r.seq)) + 1;
|
|
748
829
|
}
|
|
749
830
|
insertToolCall(record) {
|
|
831
|
+
record = prepareRecordForStorage(
|
|
832
|
+
record,
|
|
833
|
+
this.dataDir
|
|
834
|
+
).record;
|
|
750
835
|
const sessionId = record.session_id;
|
|
751
836
|
const prev = this.sessionLocks.get(sessionId) ?? Promise.resolve();
|
|
752
837
|
const next = prev.then(() => {
|
|
@@ -784,9 +869,9 @@ var init_json_storage = __esm({
|
|
|
784
869
|
allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
|
|
785
870
|
} else {
|
|
786
871
|
try {
|
|
787
|
-
const files = (0,
|
|
872
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
788
873
|
for (const file of files) {
|
|
789
|
-
const records = this.readJsonFile((0,
|
|
874
|
+
const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
|
|
790
875
|
allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
|
|
791
876
|
}
|
|
792
877
|
} catch {
|
|
@@ -795,9 +880,21 @@ var init_json_storage = __esm({
|
|
|
795
880
|
if (params.agentType) {
|
|
796
881
|
allRecords = allRecords.filter((r) => r.agent_type === params.agentType);
|
|
797
882
|
}
|
|
883
|
+
if (params.agentId) {
|
|
884
|
+
allRecords = allRecords.filter((r) => `${r.agent_type}:${r.hostname}` === params.agentId);
|
|
885
|
+
}
|
|
798
886
|
if (params.decision) {
|
|
799
887
|
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
800
888
|
}
|
|
889
|
+
if (params.riskLevel) {
|
|
890
|
+
allRecords = allRecords.filter((r) => r.risk_level === params.riskLevel);
|
|
891
|
+
}
|
|
892
|
+
if (params.fromTime) {
|
|
893
|
+
allRecords = allRecords.filter((r) => r.called_at >= params.fromTime);
|
|
894
|
+
}
|
|
895
|
+
if (params.toTime) {
|
|
896
|
+
allRecords = allRecords.filter((r) => r.called_at <= params.toTime);
|
|
897
|
+
}
|
|
801
898
|
allRecords.sort((a, b) => b.called_at.localeCompare(a.called_at));
|
|
802
899
|
const offset = params.offset || 0;
|
|
803
900
|
const limit = params.limit || 50;
|
|
@@ -808,13 +905,22 @@ var init_json_storage = __esm({
|
|
|
808
905
|
const agents = this.loadAgents();
|
|
809
906
|
let allRecords = [];
|
|
810
907
|
try {
|
|
811
|
-
const files = (0,
|
|
908
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
812
909
|
for (const file of files) {
|
|
813
|
-
const records = this.readJsonFile((0,
|
|
910
|
+
const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
|
|
814
911
|
allRecords.push(...records);
|
|
815
912
|
}
|
|
816
913
|
} catch {
|
|
817
914
|
}
|
|
915
|
+
if (params.sessionId) {
|
|
916
|
+
allRecords = allRecords.filter((r) => r.session_id === params.sessionId);
|
|
917
|
+
}
|
|
918
|
+
if (params.agentId) {
|
|
919
|
+
const allowed = new Set(
|
|
920
|
+
[...sessions.values()].filter((s) => s.agent_id === params.agentId).map((s) => s.id)
|
|
921
|
+
);
|
|
922
|
+
allRecords = allRecords.filter((r) => allowed.has(r.session_id));
|
|
923
|
+
}
|
|
818
924
|
if (params.agentType) {
|
|
819
925
|
const allowed = new Set(
|
|
820
926
|
[...sessions.values()].filter((s) => (agents.get(s.agent_id)?.agent_type || "") === params.agentType).map((s) => s.id)
|
|
@@ -824,6 +930,15 @@ var init_json_storage = __esm({
|
|
|
824
930
|
if (params.decision) {
|
|
825
931
|
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
826
932
|
}
|
|
933
|
+
if (params.riskLevel) {
|
|
934
|
+
allRecords = allRecords.filter((r) => r.risk_level === params.riskLevel);
|
|
935
|
+
}
|
|
936
|
+
if (params.fromTime) {
|
|
937
|
+
allRecords = allRecords.filter((r) => r.called_at >= params.fromTime);
|
|
938
|
+
}
|
|
939
|
+
if (params.toTime) {
|
|
940
|
+
allRecords = allRecords.filter((r) => r.called_at <= params.toTime);
|
|
941
|
+
}
|
|
827
942
|
return allRecords.length;
|
|
828
943
|
}
|
|
829
944
|
getStorageStats() {
|
|
@@ -831,12 +946,12 @@ var init_json_storage = __esm({
|
|
|
831
946
|
let jsonFiles = 0;
|
|
832
947
|
let jsonBytes = 0;
|
|
833
948
|
try {
|
|
834
|
-
const files = (0,
|
|
949
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
835
950
|
for (const file of files) {
|
|
836
|
-
const stat = (0,
|
|
951
|
+
const stat = (0, import_fs2.statSync)((0, import_path2.join)(this.toolCallsDir, file));
|
|
837
952
|
jsonFiles++;
|
|
838
953
|
jsonBytes += stat.size;
|
|
839
|
-
const records = this.readJsonFile((0,
|
|
954
|
+
const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
|
|
840
955
|
toolCalls += records.length;
|
|
841
956
|
}
|
|
842
957
|
} catch {
|
|
@@ -846,9 +961,9 @@ var init_json_storage = __esm({
|
|
|
846
961
|
clearToolCalls() {
|
|
847
962
|
let removed = 0;
|
|
848
963
|
try {
|
|
849
|
-
const files = (0,
|
|
964
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
850
965
|
for (const file of files) {
|
|
851
|
-
(0,
|
|
966
|
+
(0, import_fs2.unlinkSync)((0, import_path2.join)(this.toolCallsDir, file));
|
|
852
967
|
removed++;
|
|
853
968
|
}
|
|
854
969
|
} catch {
|
|
@@ -866,6 +981,49 @@ var init_json_storage = __esm({
|
|
|
866
981
|
hostname: agent?.hostname || ""
|
|
867
982
|
};
|
|
868
983
|
}
|
|
984
|
+
/**
|
|
985
|
+
* 归档最老的记录:JSON 模式下每个 session 一个文件,这里把所有 session 的记录
|
|
986
|
+
* 汇总排序,最老的 (total - keep) 条写进 `<dataDir>/archive/*.jsonl.gz`,
|
|
987
|
+
* 再从各自的 session 文件里移除。数据不丢,只是不在主目录了。
|
|
988
|
+
*/
|
|
989
|
+
archiveOldRecords(keep) {
|
|
990
|
+
if (keep <= 0 || !(0, import_fs2.existsSync)(this.toolCallsDir)) return { archived: 0, file: "" };
|
|
991
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
992
|
+
let total = 0;
|
|
993
|
+
for (const f of (0, import_fs2.readdirSync)(this.toolCallsDir)) {
|
|
994
|
+
if (!f.endsWith(".json")) continue;
|
|
995
|
+
const sid = f.slice(0, -".json".length);
|
|
996
|
+
const recs = this.loadToolCalls(sid);
|
|
997
|
+
if (recs.length) {
|
|
998
|
+
bySession.set(sid, recs);
|
|
999
|
+
total += recs.length;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
if (total <= keep) return { archived: 0, file: "" };
|
|
1003
|
+
const flat = [];
|
|
1004
|
+
for (const [sid, recs] of bySession) for (const rec of recs) flat.push({ sid, rec });
|
|
1005
|
+
flat.sort((a, b) => String(a.rec.called_at).localeCompare(String(b.rec.called_at)));
|
|
1006
|
+
const archiveCount = total - keep;
|
|
1007
|
+
const toArchive = flat.slice(0, archiveCount);
|
|
1008
|
+
const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
|
|
1009
|
+
const { mkdirSync: mkdirSync4, writeFileSync: writeFileSync3 } = require("fs");
|
|
1010
|
+
const { join: join4 } = require("path");
|
|
1011
|
+
const { gzipSync } = require("zlib");
|
|
1012
|
+
const archiveDir = join4(this.dataDir, "archive");
|
|
1013
|
+
if (!(0, import_fs2.existsSync)(archiveDir)) mkdirSync4(archiveDir, { recursive: true, mode: 448 });
|
|
1014
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1015
|
+
const file = join4(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1016
|
+
const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
|
|
1017
|
+
writeFileSync3(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1018
|
+
for (const [sid, recs] of bySession) {
|
|
1019
|
+
const remain = recs.filter((r) => !archiveIds.has(String(r.id)));
|
|
1020
|
+
if (remain.length !== recs.length) this.saveToolCalls(sid, remain);
|
|
1021
|
+
}
|
|
1022
|
+
return { archived: toArchive.length, file };
|
|
1023
|
+
}
|
|
1024
|
+
/** JSON 模式没有需要回收的数据库页,归档已把文件挪走。 */
|
|
1025
|
+
vacuum() {
|
|
1026
|
+
}
|
|
869
1027
|
getAgentsList(agentType) {
|
|
870
1028
|
const agents = this.loadAgents();
|
|
871
1029
|
const sessions = this.loadSessions();
|
|
@@ -900,9 +1058,9 @@ var init_json_storage = __esm({
|
|
|
900
1058
|
getTimeline(limit = 100) {
|
|
901
1059
|
const buckets = /* @__PURE__ */ new Map();
|
|
902
1060
|
try {
|
|
903
|
-
const files = (0,
|
|
1061
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
904
1062
|
for (const file of files) {
|
|
905
|
-
const records = this.readJsonFile((0,
|
|
1063
|
+
const records = this.readJsonFile((0, import_path2.join)(this.toolCallsDir, file), []);
|
|
906
1064
|
for (const r of records) {
|
|
907
1065
|
const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
|
|
908
1066
|
const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
|
|
@@ -933,16 +1091,17 @@ __export(sqlite_storage_exports, {
|
|
|
933
1091
|
});
|
|
934
1092
|
function getDefaultDbPath() {
|
|
935
1093
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
936
|
-
const xdgData = process.env.XDG_DATA_HOME || (0,
|
|
937
|
-
return (0,
|
|
1094
|
+
const xdgData = process.env.XDG_DATA_HOME || (0, import_path3.join)(home, ".local", "share");
|
|
1095
|
+
return (0, import_path3.join)(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
938
1096
|
}
|
|
939
|
-
var
|
|
1097
|
+
var import_fs3, import_path3, SCHEMA, SqliteStorage;
|
|
940
1098
|
var init_sqlite_storage = __esm({
|
|
941
1099
|
"src/shared/storage/sqlite-storage.ts"() {
|
|
942
1100
|
"use strict";
|
|
943
1101
|
init_cjs_shims();
|
|
944
|
-
|
|
945
|
-
|
|
1102
|
+
import_fs3 = require("fs");
|
|
1103
|
+
import_path3 = require("path");
|
|
1104
|
+
init_record_guard();
|
|
946
1105
|
SCHEMA = `
|
|
947
1106
|
CREATE TABLE IF NOT EXISTS agents (
|
|
948
1107
|
id TEXT PRIMARY KEY,
|
|
@@ -1002,8 +1161,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1002
1161
|
);
|
|
1003
1162
|
}
|
|
1004
1163
|
const path = dbPath || getDefaultDbPath();
|
|
1005
|
-
const dir = (0,
|
|
1006
|
-
if (!(0,
|
|
1164
|
+
const dir = (0, import_path3.dirname)(path);
|
|
1165
|
+
if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true });
|
|
1007
1166
|
this.dbPath = path;
|
|
1008
1167
|
this.db = new Database(path);
|
|
1009
1168
|
this.db.pragma("journal_mode = WAL");
|
|
@@ -1037,6 +1196,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1037
1196
|
return row.next;
|
|
1038
1197
|
}
|
|
1039
1198
|
insertToolCall(record) {
|
|
1199
|
+
record = prepareRecordForStorage(
|
|
1200
|
+
record,
|
|
1201
|
+
this.dbPath
|
|
1202
|
+
).record;
|
|
1040
1203
|
const result = this.db.transaction((rec) => {
|
|
1041
1204
|
const row = this.db.prepare(
|
|
1042
1205
|
"SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
|
|
@@ -1080,6 +1243,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1080
1243
|
conditions.push("tc.session_id = ?");
|
|
1081
1244
|
values.push(params.sessionId);
|
|
1082
1245
|
}
|
|
1246
|
+
if (params.agentId) {
|
|
1247
|
+
conditions.push("s.agent_id = ?");
|
|
1248
|
+
values.push(params.agentId);
|
|
1249
|
+
}
|
|
1083
1250
|
if (params.agentType) {
|
|
1084
1251
|
conditions.push("a.agent_type = ?");
|
|
1085
1252
|
values.push(params.agentType);
|
|
@@ -1088,6 +1255,18 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1088
1255
|
conditions.push("tc.decision = ?");
|
|
1089
1256
|
values.push(params.decision);
|
|
1090
1257
|
}
|
|
1258
|
+
if (params.riskLevel) {
|
|
1259
|
+
conditions.push("tc.risk_level = ?");
|
|
1260
|
+
values.push(params.riskLevel);
|
|
1261
|
+
}
|
|
1262
|
+
if (params.fromTime) {
|
|
1263
|
+
conditions.push("tc.called_at >= ?");
|
|
1264
|
+
values.push(params.fromTime);
|
|
1265
|
+
}
|
|
1266
|
+
if (params.toTime) {
|
|
1267
|
+
conditions.push("tc.called_at <= ?");
|
|
1268
|
+
values.push(params.toTime);
|
|
1269
|
+
}
|
|
1091
1270
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1092
1271
|
const limit = params.limit || 50;
|
|
1093
1272
|
const offset = params.offset || 0;
|
|
@@ -1102,14 +1281,34 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1102
1281
|
countToolCalls(params) {
|
|
1103
1282
|
const conditions = [];
|
|
1104
1283
|
const values = [];
|
|
1105
|
-
if (params.
|
|
1106
|
-
conditions.push("tc.
|
|
1107
|
-
values.push(params.
|
|
1284
|
+
if (params.sessionId) {
|
|
1285
|
+
conditions.push("tc.session_id = ?");
|
|
1286
|
+
values.push(params.sessionId);
|
|
1287
|
+
}
|
|
1288
|
+
if (params.agentId) {
|
|
1289
|
+
conditions.push("s.agent_id = ?");
|
|
1290
|
+
values.push(params.agentId);
|
|
1108
1291
|
}
|
|
1109
1292
|
if (params.agentType) {
|
|
1110
1293
|
conditions.push("a.agent_type = ?");
|
|
1111
1294
|
values.push(params.agentType);
|
|
1112
1295
|
}
|
|
1296
|
+
if (params.decision) {
|
|
1297
|
+
conditions.push("tc.decision = ?");
|
|
1298
|
+
values.push(params.decision);
|
|
1299
|
+
}
|
|
1300
|
+
if (params.riskLevel) {
|
|
1301
|
+
conditions.push("tc.risk_level = ?");
|
|
1302
|
+
values.push(params.riskLevel);
|
|
1303
|
+
}
|
|
1304
|
+
if (params.fromTime) {
|
|
1305
|
+
conditions.push("tc.called_at >= ?");
|
|
1306
|
+
values.push(params.fromTime);
|
|
1307
|
+
}
|
|
1308
|
+
if (params.toTime) {
|
|
1309
|
+
conditions.push("tc.called_at <= ?");
|
|
1310
|
+
values.push(params.toTime);
|
|
1311
|
+
}
|
|
1113
1312
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1114
1313
|
const row = this.db.prepare(
|
|
1115
1314
|
`SELECT COUNT(*) as total FROM tool_calls tc
|
|
@@ -1141,6 +1340,49 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1141
1340
|
})();
|
|
1142
1341
|
return result;
|
|
1143
1342
|
}
|
|
1343
|
+
/**
|
|
1344
|
+
* 把最老的记录归档到本地压缩文件,主库只保留最近 `keep` 条。
|
|
1345
|
+
*
|
|
1346
|
+
* 归档文件是 **JSONL + gzip**(一行一条记录),放在 `<数据库目录>/archive/` 下,
|
|
1347
|
+
* 需要翻旧账时用 `zcat archive/xxx.jsonl.gz | grep ...` 即可 —— 数据不丢,只是
|
|
1348
|
+
* 不在主库里了。写完文件、校验落盘后才删主库行,最后 VACUUM 真正释放磁盘。
|
|
1349
|
+
*/
|
|
1350
|
+
archiveOldRecords(keep) {
|
|
1351
|
+
if (keep <= 0) return { archived: 0, file: "" };
|
|
1352
|
+
const total = this.db.prepare("SELECT COUNT(*) as n FROM tool_calls").get().n;
|
|
1353
|
+
if (total <= keep) return { archived: 0, file: "" };
|
|
1354
|
+
const cutoff = this.db.prepare(
|
|
1355
|
+
"SELECT id FROM tool_calls ORDER BY id LIMIT 1 OFFSET ?"
|
|
1356
|
+
).get(total - keep - 1);
|
|
1357
|
+
if (!cutoff) return { archived: 0, file: "" };
|
|
1358
|
+
const rows = this.db.prepare(
|
|
1359
|
+
"SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
|
|
1360
|
+
).all(cutoff.id);
|
|
1361
|
+
if (rows.length === 0) return { archived: 0, file: "" };
|
|
1362
|
+
const { writeFileSync: writeFileSync3, mkdirSync: mkdirSync4, existsSync: existsSync3 } = require("fs");
|
|
1363
|
+
const { dirname: dirname4, join: join4 } = require("path");
|
|
1364
|
+
const { gzipSync } = require("zlib");
|
|
1365
|
+
const archiveDir = join4(dirname4(this.dbPath), "archive");
|
|
1366
|
+
if (!existsSync3(archiveDir)) mkdirSync4(archiveDir, { recursive: true, mode: 448 });
|
|
1367
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1368
|
+
const file = join4(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1369
|
+
const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
|
|
1370
|
+
writeFileSync3(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1371
|
+
const deleted = this.db.transaction(() => {
|
|
1372
|
+
const res = this.db.prepare("DELETE FROM tool_calls WHERE id <= ?").run(cutoff.id);
|
|
1373
|
+
this.db.prepare(`
|
|
1374
|
+
UPDATE sessions SET tool_call_count = (
|
|
1375
|
+
SELECT COUNT(*) FROM tool_calls WHERE tool_calls.session_id = sessions.id
|
|
1376
|
+
)
|
|
1377
|
+
`).run();
|
|
1378
|
+
return Number(res.changes);
|
|
1379
|
+
})();
|
|
1380
|
+
return { archived: deleted, file };
|
|
1381
|
+
}
|
|
1382
|
+
/** 真正释放磁盘空间:DELETE 后必须 VACUUM,否则文件不会变小。 */
|
|
1383
|
+
vacuum() {
|
|
1384
|
+
this.db.exec("VACUUM");
|
|
1385
|
+
}
|
|
1144
1386
|
getAgentsList(agentType) {
|
|
1145
1387
|
const where = agentType ? "WHERE a.agent_type = ?" : "";
|
|
1146
1388
|
return this.db.prepare(`
|
|
@@ -1232,12 +1474,12 @@ function getDb(dbPath) {
|
|
|
1232
1474
|
try {
|
|
1233
1475
|
const Database = require("better-sqlite3");
|
|
1234
1476
|
const { existsSync: existsSync3, mkdirSync: mkdirSync4 } = require("fs");
|
|
1235
|
-
const { join: join4, dirname:
|
|
1477
|
+
const { join: join4, dirname: dirname4 } = require("path");
|
|
1236
1478
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
1237
1479
|
const xdgData = process.env.XDG_DATA_HOME || join4(home, ".local", "share");
|
|
1238
1480
|
const defaultPath = join4(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
1239
1481
|
const path = dbPath || defaultPath;
|
|
1240
|
-
const dir =
|
|
1482
|
+
const dir = dirname4(path);
|
|
1241
1483
|
if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
|
|
1242
1484
|
rawDb = new Database(path);
|
|
1243
1485
|
rawDb.pragma("journal_mode = WAL");
|
|
@@ -1293,15 +1535,29 @@ function sessionHistoryLimit() {
|
|
|
1293
1535
|
const v = Number.isFinite(n) ? n : DEFAULT_MAX_SESSIONS;
|
|
1294
1536
|
return Math.max(1, Math.min(v, 50));
|
|
1295
1537
|
}
|
|
1296
|
-
function buildSessionHistory(queryToolCalls2, sessionId) {
|
|
1538
|
+
function buildSessionHistory(queryToolCalls2, sessionId, listAgentTypes) {
|
|
1297
1539
|
if (!isMultiSessionEnabled()) return [];
|
|
1298
1540
|
const maxSessions = sessionHistoryLimit();
|
|
1299
1541
|
try {
|
|
1300
1542
|
const scanLimit = Math.max(DEFAULT_HISTORY_LIMIT, maxSessions * DEFAULT_ACTIONS_PER_SESSION);
|
|
1301
|
-
const
|
|
1543
|
+
const agentTypes = listAgentTypes?.() ?? [];
|
|
1544
|
+
let recent;
|
|
1545
|
+
if (agentTypes.length > 1) {
|
|
1546
|
+
const perAgent = Math.max(
|
|
1547
|
+
DEFAULT_ACTIONS_PER_SESSION,
|
|
1548
|
+
Math.floor(DEFAULT_HISTORY_LIMIT / agentTypes.length)
|
|
1549
|
+
);
|
|
1550
|
+
recent = agentTypes.flatMap((a) => queryToolCalls2({ limit: perAgent, agentType: a }));
|
|
1551
|
+
} else {
|
|
1552
|
+
recent = queryToolCalls2({ limit: scanLimit });
|
|
1553
|
+
}
|
|
1302
1554
|
const bySession = /* @__PURE__ */ new Map();
|
|
1555
|
+
const sessionAgent = /* @__PURE__ */ new Map();
|
|
1303
1556
|
for (const tc of recent) {
|
|
1304
1557
|
if (tc.session_id === sessionId) continue;
|
|
1558
|
+
if (tc.agent_type && !sessionAgent.has(tc.session_id)) {
|
|
1559
|
+
sessionAgent.set(tc.session_id, tc.agent_type);
|
|
1560
|
+
}
|
|
1305
1561
|
const list = bySession.get(tc.session_id) || [];
|
|
1306
1562
|
list.unshift({
|
|
1307
1563
|
action_type: tc.action_type,
|
|
@@ -1312,6 +1568,7 @@ function buildSessionHistory(queryToolCalls2, sessionId) {
|
|
|
1312
1568
|
}
|
|
1313
1569
|
return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
|
|
1314
1570
|
session_id: sid,
|
|
1571
|
+
...sessionAgent.get(sid) ? { agent_id: sessionAgent.get(sid) } : {},
|
|
1315
1572
|
action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
|
|
1316
1573
|
}));
|
|
1317
1574
|
} catch {
|
|
@@ -1453,7 +1710,7 @@ var init_version = __esm({
|
|
|
1453
1710
|
"src/version.ts"() {
|
|
1454
1711
|
"use strict";
|
|
1455
1712
|
init_cjs_shims();
|
|
1456
|
-
_version = true ? "0.
|
|
1713
|
+
_version = true ? "0.9.1" : (() => {
|
|
1457
1714
|
try {
|
|
1458
1715
|
const require2 = createRequire(importMetaUrl);
|
|
1459
1716
|
const pkg = require2("../package.json");
|
|
@@ -1491,18 +1748,23 @@ var init_models = __esm({
|
|
|
1491
1748
|
text: import_zod.z.string().default(""),
|
|
1492
1749
|
actions: import_zod.z.array(import_zod.z.object({
|
|
1493
1750
|
action_type: import_zod.z.string(),
|
|
1494
|
-
action_detail: import_zod.z.string()
|
|
1751
|
+
action_detail: import_zod.z.string(),
|
|
1752
|
+
output: import_zod.z.string().optional().describe("\u5DE5\u5177\u8FD4\u56DE\u5185\u5BB9\uFF1Bask_user_question \u7684\u7528\u6237\u56DE\u7B54\u9760\u5B83\u4F20\u7ED9 AgentMoss \u5224\u6388\u6743")
|
|
1495
1753
|
})).default([])
|
|
1496
1754
|
})).default([]),
|
|
1497
1755
|
action_history: import_zod.z.array(import_zod.z.object({
|
|
1498
1756
|
action_type: import_zod.z.string(),
|
|
1499
|
-
action_detail: import_zod.z.string()
|
|
1757
|
+
action_detail: import_zod.z.string(),
|
|
1758
|
+
// 授权类规则(改密码 / 删用户)靠 ask_user_question 的 output 判断用户是否已确认。
|
|
1759
|
+
// 此前 schema 里没有这个字段,Agent 传了也会被剥掉 → 必然判成「未授权」。
|
|
1760
|
+
output: import_zod.z.string().optional().describe("\u5DE5\u5177\u8FD4\u56DE\u5185\u5BB9\uFF1Bask_user_question \u7684\u7528\u6237\u56DE\u7B54\u9760\u5B83\u4F20\u7ED9 AgentMoss \u5224\u6388\u6743")
|
|
1500
1761
|
})).default([]),
|
|
1501
1762
|
session_history: import_zod.z.array(import_zod.z.object({
|
|
1502
1763
|
session_id: import_zod.z.string(),
|
|
1503
1764
|
action_history: import_zod.z.array(import_zod.z.object({
|
|
1504
1765
|
action_type: import_zod.z.string(),
|
|
1505
|
-
action_detail: import_zod.z.string()
|
|
1766
|
+
action_detail: import_zod.z.string(),
|
|
1767
|
+
output: import_zod.z.string().optional()
|
|
1506
1768
|
})).default([])
|
|
1507
1769
|
})).default([]).describe("\u591A session \u5386\u53F2\u52A8\u4F5C\uFF08\u53EF\u9009\uFF09\uFF1A\u4F9B AgentMoss L2.4 \u5F62\u5F0F\u5316\u5F15\u64CE\u8DE8\u4F1A\u8BDD\u9A8C\u8BC1"),
|
|
1508
1770
|
metadata: import_zod.z.record(import_zod.z.unknown()).optional()
|
|
@@ -1547,20 +1809,23 @@ var init_models = __esm({
|
|
|
1547
1809
|
function normalize(input, systemContext) {
|
|
1548
1810
|
const actionHistory = input.action_history.map((h) => ({
|
|
1549
1811
|
action_type: h.action_type,
|
|
1550
|
-
action_detail: h.action_detail
|
|
1812
|
+
action_detail: h.action_detail,
|
|
1813
|
+
output: h.output ?? ""
|
|
1551
1814
|
}));
|
|
1552
1815
|
const sessionHistory = (input.session_history || []).map((s) => ({
|
|
1553
1816
|
session_id: s.session_id,
|
|
1554
1817
|
action_history: s.action_history.map((h) => ({
|
|
1555
1818
|
action_type: h.action_type,
|
|
1556
|
-
action_detail: h.action_detail
|
|
1819
|
+
action_detail: h.action_detail,
|
|
1820
|
+
output: h.output ?? ""
|
|
1557
1821
|
}))
|
|
1558
1822
|
}));
|
|
1559
1823
|
const promptHistory = input.prompt_history.map((t) => ({
|
|
1560
1824
|
text: t.text,
|
|
1561
1825
|
actions: t.actions.map((a) => ({
|
|
1562
1826
|
action_type: a.action_type,
|
|
1563
|
-
action_detail: a.action_detail
|
|
1827
|
+
action_detail: a.action_detail,
|
|
1828
|
+
output: a.output ?? ""
|
|
1564
1829
|
}))
|
|
1565
1830
|
}));
|
|
1566
1831
|
const toolName = input.tool_name || input.a_next?.action_type || "unknown";
|
|
@@ -1750,6 +2015,12 @@ function getStorageStats() {
|
|
|
1750
2015
|
function clearToolCalls() {
|
|
1751
2016
|
return store().clearToolCalls();
|
|
1752
2017
|
}
|
|
2018
|
+
function archiveOldRecords(keep) {
|
|
2019
|
+
return store().archiveOldRecords(keep);
|
|
2020
|
+
}
|
|
2021
|
+
function vacuumStore() {
|
|
2022
|
+
store().vacuum();
|
|
2023
|
+
}
|
|
1753
2024
|
function getAgentsList(agentType) {
|
|
1754
2025
|
return store().getAgentsList(agentType);
|
|
1755
2026
|
}
|
|
@@ -1828,7 +2099,9 @@ async function analyzeRoute(c) {
|
|
|
1828
2099
|
if (isMultiSessionEnabled()) {
|
|
1829
2100
|
input.session_history = buildSessionHistory(
|
|
1830
2101
|
(params) => queryToolCalls(params),
|
|
1831
|
-
input.session_id
|
|
2102
|
+
input.session_id,
|
|
2103
|
+
// 多 agent 时按 agent 分组取历史,避免高频 agent 把别人的动作挤出窗口
|
|
2104
|
+
() => getAgentsList().map((a) => a.agent_type)
|
|
1832
2105
|
);
|
|
1833
2106
|
}
|
|
1834
2107
|
const mossRequest = normalize(input, context);
|
|
@@ -1912,13 +2185,22 @@ async function sessionsRoute(c) {
|
|
|
1912
2185
|
return c.json({ session_id: sessionId, tool_calls: rows });
|
|
1913
2186
|
}
|
|
1914
2187
|
async function toolCallsRoute(c) {
|
|
1915
|
-
const
|
|
1916
|
-
|
|
1917
|
-
const
|
|
2188
|
+
const sessionId = c.req.query("session_id") || void 0;
|
|
2189
|
+
let agentId = c.req.query("agent_id") || void 0;
|
|
2190
|
+
const decision = c.req.query("decision") || void 0;
|
|
2191
|
+
const riskLevel = c.req.query("risk_level") || void 0;
|
|
2192
|
+
const fromTime = c.req.query("from") || void 0;
|
|
2193
|
+
const toTime = c.req.query("to") || void 0;
|
|
2194
|
+
const rawLimit = parseInt(c.req.query("limit") || "50", 10);
|
|
2195
|
+
const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 500) : 50;
|
|
2196
|
+
const rawOffset = parseInt(c.req.query("offset") || "0", 10);
|
|
2197
|
+
const offset = Number.isFinite(rawOffset) && rawOffset > 0 ? rawOffset : 0;
|
|
1918
2198
|
const bound = boundAgentOf(c.get("principal") || "");
|
|
2199
|
+
if (bound) agentId = void 0;
|
|
1919
2200
|
const agentType = bound || void 0;
|
|
1920
|
-
const
|
|
1921
|
-
const
|
|
2201
|
+
const filter = { sessionId, agentId, agentType, decision, riskLevel, fromTime, toTime };
|
|
2202
|
+
const total = countToolCalls(filter);
|
|
2203
|
+
const data = queryToolCalls({ ...filter, limit, offset });
|
|
1922
2204
|
return c.json({ total, data });
|
|
1923
2205
|
}
|
|
1924
2206
|
async function agentsRoute(c) {
|
|
@@ -2107,9 +2389,9 @@ async function dashboardRoute(c) {
|
|
|
2107
2389
|
}
|
|
2108
2390
|
}
|
|
2109
2391
|
const { readFileSync: readFileSync3, existsSync: existsSync3 } = await import("fs");
|
|
2110
|
-
const { resolve, dirname:
|
|
2392
|
+
const { resolve, dirname: dirname4 } = await import("path");
|
|
2111
2393
|
const { fileURLToPath } = await import("url");
|
|
2112
|
-
const __dirname =
|
|
2394
|
+
const __dirname = dirname4(fileURLToPath(importMetaUrl));
|
|
2113
2395
|
const paths = [
|
|
2114
2396
|
resolve(__dirname, "dashboard.html"),
|
|
2115
2397
|
resolve(__dirname, "../dashboard.html"),
|
|
@@ -2164,6 +2446,73 @@ p{margin:8px 0;color:#555}</style></head><body>
|
|
|
2164
2446
|
}
|
|
2165
2447
|
});
|
|
2166
2448
|
|
|
2449
|
+
// src/shared/storage/maintenance.ts
|
|
2450
|
+
var maintenance_exports = {};
|
|
2451
|
+
__export(maintenance_exports, {
|
|
2452
|
+
runStorageMaintenance: () => runStorageMaintenance,
|
|
2453
|
+
startStorageMaintenance: () => startStorageMaintenance,
|
|
2454
|
+
stopStorageMaintenance: () => stopStorageMaintenance
|
|
2455
|
+
});
|
|
2456
|
+
async function runStorageMaintenance(agentId = "default") {
|
|
2457
|
+
if (running) return { archived: 0, file: "", skipped: "running" };
|
|
2458
|
+
running = true;
|
|
2459
|
+
try {
|
|
2460
|
+
const threshold = archiveThresholdRecords();
|
|
2461
|
+
const keep = archiveKeepRecords();
|
|
2462
|
+
if (threshold <= 0 || keep <= 0) return { archived: 0, file: "", skipped: "disabled" };
|
|
2463
|
+
const stats = getStorageStats();
|
|
2464
|
+
if (stats.toolCalls < threshold) return { archived: 0, file: "", skipped: "below-threshold" };
|
|
2465
|
+
try {
|
|
2466
|
+
await callAgentMossReview({ agentId, dbPath: getAgentGateDbPath() });
|
|
2467
|
+
} catch (err) {
|
|
2468
|
+
console.error(`[AgentGate] \u5F52\u6863\u524D\u56DE\u987E\u5931\u8D25\uFF08\u7EE7\u7EED\u5F52\u6863\uFF09: ${String(err?.message ?? err)}`);
|
|
2469
|
+
}
|
|
2470
|
+
const res = archiveOldRecords(keep);
|
|
2471
|
+
if (res.archived <= 0) return { archived: 0, file: "", skipped: "nothing-to-archive" };
|
|
2472
|
+
try {
|
|
2473
|
+
vacuumStore();
|
|
2474
|
+
} catch (err) {
|
|
2475
|
+
console.error(`[AgentGate] VACUUM \u5931\u8D25: ${String(err?.message ?? err)}`);
|
|
2476
|
+
}
|
|
2477
|
+
console.error(
|
|
2478
|
+
`[AgentGate] \u5B58\u50A8\u5F52\u6863\u5B8C\u6210: ${res.archived} \u6761 \u2192 ${res.file}\uFF08\u4E3B\u5E93\u4FDD\u7559 ${keep} \u6761\uFF09`
|
|
2479
|
+
);
|
|
2480
|
+
return { archived: res.archived, file: res.file, skipped: "" };
|
|
2481
|
+
} catch (err) {
|
|
2482
|
+
console.error(`[AgentGate] \u5B58\u50A8\u7EF4\u62A4\u5931\u8D25: ${String(err?.message ?? err)}`);
|
|
2483
|
+
return { archived: 0, file: "", skipped: "error" };
|
|
2484
|
+
} finally {
|
|
2485
|
+
running = false;
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
function startStorageMaintenance(agentId = "default", intervalMs = 6 * 60 * 60 * 1e3) {
|
|
2489
|
+
if (timer) return;
|
|
2490
|
+
void runStorageMaintenance(agentId);
|
|
2491
|
+
timer = setInterval(() => {
|
|
2492
|
+
void runStorageMaintenance(agentId);
|
|
2493
|
+
}, intervalMs);
|
|
2494
|
+
timer.unref?.();
|
|
2495
|
+
}
|
|
2496
|
+
function stopStorageMaintenance() {
|
|
2497
|
+
if (timer) {
|
|
2498
|
+
clearInterval(timer);
|
|
2499
|
+
timer = null;
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
var running, timer;
|
|
2503
|
+
var init_maintenance = __esm({
|
|
2504
|
+
"src/shared/storage/maintenance.ts"() {
|
|
2505
|
+
"use strict";
|
|
2506
|
+
init_cjs_shims();
|
|
2507
|
+
init_repository();
|
|
2508
|
+
init_security();
|
|
2509
|
+
init_moss_client();
|
|
2510
|
+
init_db();
|
|
2511
|
+
running = false;
|
|
2512
|
+
timer = null;
|
|
2513
|
+
}
|
|
2514
|
+
});
|
|
2515
|
+
|
|
2167
2516
|
// src/v1/cli.ts
|
|
2168
2517
|
init_cjs_shims();
|
|
2169
2518
|
async function main() {
|
|
@@ -2223,6 +2572,12 @@ async function main() {
|
|
|
2223
2572
|
serve({ fetch: app.fetch, hostname: host, port }, (info) => {
|
|
2224
2573
|
console.log(`Listening on http://${host}:${port}`);
|
|
2225
2574
|
});
|
|
2575
|
+
try {
|
|
2576
|
+
const { startStorageMaintenance: startStorageMaintenance2 } = await Promise.resolve().then(() => (init_maintenance(), maintenance_exports));
|
|
2577
|
+
startStorageMaintenance2("default");
|
|
2578
|
+
} catch (err) {
|
|
2579
|
+
console.error(`[AgentGate] \u5B58\u50A8\u7EF4\u62A4\u542F\u52A8\u5931\u8D25: ${String(err?.message ?? err)}`);
|
|
2580
|
+
}
|
|
2226
2581
|
}
|
|
2227
2582
|
main().catch((err) => {
|
|
2228
2583
|
console.error("Fatal error:", err);
|