@kenhkl/agent-gate 0.9.13 → 0.9.14
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/dashboard.html +20 -1
- package/dist/shared/storage/db.d.ts +2 -0
- package/dist/shared/storage/db.js +44 -5
- package/dist/v1/cli.js +153 -41
- package/dist/v1/server.js +118 -37
- package/dist/v3/cli.js +137 -56
- package/package.json +1 -1
package/dist/dashboard.html
CHANGED
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
<div class="tab" data-panel="flow">Data Flow</div>
|
|
38
38
|
<button class="flow-btn" id="enter-copy" style="margin-left:auto;align-self:center">Copy Records</button>
|
|
39
39
|
</div>
|
|
40
|
-
<div id="calls-panel"><div class="copy-bar" id="copy-bar"><span id="copy-count">0 selected</span><span class="fmt-group"><button id="fmt-tsv" class="active">TSV</button><button id="fmt-json">JSON</button></span><span class="spacer"></span><button id="copy-selected" disabled>Copy Selected</button><button id="copy-page">Copy Current Page</button><button id="exit-copy">Cancel</button></div><div class="table-wrap">
|
|
40
|
+
<div id="calls-panel"><div class="copy-bar" id="copy-bar"><span id="copy-count">0 selected</span><span class="fmt-group"><button id="fmt-tsv" class="active">TSV</button><button id="fmt-json">JSON</button></span><span class="spacer"></span><button id="copy-selected" disabled>Copy Selected</button><button id="copy-page">Copy Current Page</button><button id="delete-selected" disabled style="color:var(--red);border-color:rgba(255,59,48,.35)">Delete Selected</button><button id="exit-copy">Cancel</button></div><div class="table-wrap">
|
|
41
41
|
<table id="recent-calls"><thead><tr><th class="col-check"></th><th>Time</th><th>Agent</th><th>Session</th><th>Tool</th><th>Command</th><th>Decision</th><th>Risk</th><th>Latency</th><th>Reason</th><th>Action</th></tr></thead><tbody id="recent-table"></tbody></table>
|
|
42
42
|
</div><div id="ag-pagination" class="ag-pagination"></div></div>
|
|
43
43
|
<div id="agents-panel"><div class="table-wrap">
|
|
@@ -428,6 +428,7 @@
|
|
|
428
428
|
var n=_selectedIds.size;
|
|
429
429
|
var c=document.getElementById('copy-count'); if(c) c.textContent = n+' selected';
|
|
430
430
|
var cs=document.getElementById('copy-selected'); if(cs) cs.disabled = _copying || n===0;
|
|
431
|
+
var ds=document.getElementById('delete-selected'); if(ds) ds.disabled = _copying || n===0;
|
|
431
432
|
var cp=document.getElementById('copy-page'); if(cp) cp.disabled = _copying || !_currentRows.length;
|
|
432
433
|
var ft=document.getElementById('fmt-tsv'), fj=document.getElementById('fmt-json');
|
|
433
434
|
if(ft) ft.disabled=_copying; if(fj) fj.disabled=_copying;
|
|
@@ -461,6 +462,24 @@
|
|
|
461
462
|
if(!rows.length){ toast('No records on this page'); return; }
|
|
462
463
|
doCopy(rows, 'Copied '+rows.length+' record(s)');
|
|
463
464
|
});
|
|
465
|
+
// 多选删除(与 Python 版同构):DELETE /api/v1/tool_calls {ids}
|
|
466
|
+
var ds=document.getElementById('delete-selected'); if(ds) ds.addEventListener('click', async function(){
|
|
467
|
+
var want=new Set(_selectedIds);
|
|
468
|
+
if(!want.size){ toast('No records selected'); return; }
|
|
469
|
+
if(!confirm('Delete '+want.size+' record(s)? This cannot be undone.')) return;
|
|
470
|
+
try {
|
|
471
|
+
var resp = await fetch('/api/v1/tool_calls', {
|
|
472
|
+
method:'DELETE',
|
|
473
|
+
headers:{'Content-Type':'application/json'},
|
|
474
|
+
body: JSON.stringify({ids: Array.from(want)})
|
|
475
|
+
});
|
|
476
|
+
var data = await resp.json();
|
|
477
|
+
if(!resp.ok){ toast(data.detail || 'Delete failed'); return; }
|
|
478
|
+
_selectedIds.clear();
|
|
479
|
+
toast('Deleted '+(data.deleted||0)+' record(s)');
|
|
480
|
+
refresh();
|
|
481
|
+
} catch(e) { toast('Delete failed'); }
|
|
482
|
+
});
|
|
464
483
|
})();
|
|
465
484
|
|
|
466
485
|
// ==================== Data Flow(会话流,与 Python 版同构)====================
|
|
@@ -98,6 +98,8 @@ interface StorageAdapter {
|
|
|
98
98
|
countToolCalls(params: ToolCallFilter): number;
|
|
99
99
|
getStorageStats(): StorageStats;
|
|
100
100
|
clearToolCalls(): number;
|
|
101
|
+
/** 按 id 删除指定记录,返回实际删除条数(空数组不删任何记录)。 */
|
|
102
|
+
deleteToolCalls(ids: number[]): number;
|
|
101
103
|
/** 归档最老的记录到本地压缩文件,主库保留最近 keep 条。 */
|
|
102
104
|
archiveOldRecords(keep: number): {
|
|
103
105
|
archived: number;
|
|
@@ -70,12 +70,21 @@ var init_security = __esm({
|
|
|
70
70
|
});
|
|
71
71
|
|
|
72
72
|
// src/shared/storage/record-guard.ts
|
|
73
|
+
function bytePrefix(value, limit) {
|
|
74
|
+
const buf = Buffer.from(value, "utf8");
|
|
75
|
+
if (buf.length <= limit) return value;
|
|
76
|
+
let end = limit;
|
|
77
|
+
while (end > 0 && (buf[end] & 192) === 128) end--;
|
|
78
|
+
return buf.subarray(0, end).toString("utf8");
|
|
79
|
+
}
|
|
73
80
|
function clipText(value, limit = maxRecordBytes()) {
|
|
74
81
|
const s = String(value ?? "");
|
|
75
|
-
|
|
76
|
-
|
|
82
|
+
const raw = Buffer.from(s, "utf8");
|
|
83
|
+
if (limit <= 0 || raw.length <= limit) return s;
|
|
84
|
+
const head = bytePrefix(s, limit);
|
|
77
85
|
const digest = (0, import_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 16);
|
|
78
|
-
|
|
86
|
+
const removed = raw.length - Buffer.byteLength(head, "utf8");
|
|
87
|
+
return `${head}\u2026[truncated ${removed}B sha256:${digest}]`;
|
|
79
88
|
}
|
|
80
89
|
function diskFreePercent(targetPath) {
|
|
81
90
|
try {
|
|
@@ -95,11 +104,11 @@ function shouldDegradeWrites(targetPath) {
|
|
|
95
104
|
}
|
|
96
105
|
function degradeRecord(rec) {
|
|
97
106
|
const command = String(rec.command ?? "");
|
|
98
|
-
const clipped = command
|
|
107
|
+
const clipped = Buffer.byteLength(command, "utf8") > DEGRADE_COMMAND_BYTES ? `${bytePrefix(command, DEGRADE_COMMAND_BYTES)}\u2026[degraded]` : command;
|
|
99
108
|
return {
|
|
100
109
|
...rec,
|
|
101
110
|
command: clipped,
|
|
102
|
-
action_detail: String(rec.action_detail ?? "") > "" ? String(rec.action_detail)
|
|
111
|
+
action_detail: String(rec.action_detail ?? "") > "" ? bytePrefix(String(rec.action_detail), DEGRADE_COMMAND_BYTES) : "",
|
|
103
112
|
description: "",
|
|
104
113
|
reason: String(rec.reason ?? "").slice(0, 256)
|
|
105
114
|
};
|
|
@@ -426,6 +435,26 @@ var init_json_storage = __esm({
|
|
|
426
435
|
}
|
|
427
436
|
return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
|
|
428
437
|
}
|
|
438
|
+
deleteToolCalls(ids) {
|
|
439
|
+
if (ids.length === 0) return 0;
|
|
440
|
+
const want = new Set(ids);
|
|
441
|
+
let removed = 0;
|
|
442
|
+
try {
|
|
443
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
444
|
+
for (const file of files) {
|
|
445
|
+
const full = (0, import_path2.join)(this.toolCallsDir, file);
|
|
446
|
+
const records = this.readJsonFile(full, []);
|
|
447
|
+
const kept = records.filter((r) => !want.has(Number(r.id)));
|
|
448
|
+
const diff = records.length - kept.length;
|
|
449
|
+
if (diff > 0) {
|
|
450
|
+
removed += diff;
|
|
451
|
+
this.writeJsonFile(full, kept);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
} catch {
|
|
455
|
+
}
|
|
456
|
+
return removed;
|
|
457
|
+
}
|
|
429
458
|
clearToolCalls() {
|
|
430
459
|
let removed = 0;
|
|
431
460
|
try {
|
|
@@ -828,6 +857,16 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
828
857
|
}
|
|
829
858
|
return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
|
|
830
859
|
}
|
|
860
|
+
deleteToolCalls(ids) {
|
|
861
|
+
if (ids.length === 0) return 0;
|
|
862
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
863
|
+
const result = this.db.transaction(() => {
|
|
864
|
+
const del = this.db.prepare(`DELETE FROM tool_calls WHERE id IN (${placeholders})`).run(...ids);
|
|
865
|
+
this.db.prepare("UPDATE sessions SET tool_call_count = (SELECT COUNT(*) FROM tool_calls WHERE tool_calls.session_id = sessions.id)").run();
|
|
866
|
+
return Number(del.changes);
|
|
867
|
+
})();
|
|
868
|
+
return result;
|
|
869
|
+
}
|
|
831
870
|
clearToolCalls() {
|
|
832
871
|
const result = this.db.transaction(() => {
|
|
833
872
|
const deleted = this.db.prepare("DELETE FROM tool_calls").run();
|
package/dist/v1/cli.js
CHANGED
|
@@ -605,12 +605,21 @@ var init_security = __esm({
|
|
|
605
605
|
});
|
|
606
606
|
|
|
607
607
|
// src/shared/storage/record-guard.ts
|
|
608
|
+
function bytePrefix(value, limit) {
|
|
609
|
+
const buf = Buffer.from(value, "utf8");
|
|
610
|
+
if (buf.length <= limit) return value;
|
|
611
|
+
let end = limit;
|
|
612
|
+
while (end > 0 && (buf[end] & 192) === 128) end--;
|
|
613
|
+
return buf.subarray(0, end).toString("utf8");
|
|
614
|
+
}
|
|
608
615
|
function clipText(value, limit = maxRecordBytes()) {
|
|
609
616
|
const s = String(value ?? "");
|
|
610
|
-
|
|
611
|
-
|
|
617
|
+
const raw = Buffer.from(s, "utf8");
|
|
618
|
+
if (limit <= 0 || raw.length <= limit) return s;
|
|
619
|
+
const head = bytePrefix(s, limit);
|
|
612
620
|
const digest = (0, import_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 16);
|
|
613
|
-
|
|
621
|
+
const removed = raw.length - Buffer.byteLength(head, "utf8");
|
|
622
|
+
return `${head}\u2026[truncated ${removed}B sha256:${digest}]`;
|
|
614
623
|
}
|
|
615
624
|
function diskFreePercent(targetPath) {
|
|
616
625
|
try {
|
|
@@ -630,11 +639,11 @@ function shouldDegradeWrites(targetPath) {
|
|
|
630
639
|
}
|
|
631
640
|
function degradeRecord(rec) {
|
|
632
641
|
const command = String(rec.command ?? "");
|
|
633
|
-
const clipped = command
|
|
642
|
+
const clipped = Buffer.byteLength(command, "utf8") > DEGRADE_COMMAND_BYTES ? `${bytePrefix(command, DEGRADE_COMMAND_BYTES)}\u2026[degraded]` : command;
|
|
634
643
|
return {
|
|
635
644
|
...rec,
|
|
636
645
|
command: clipped,
|
|
637
|
-
action_detail: String(rec.action_detail ?? "") > "" ? String(rec.action_detail)
|
|
646
|
+
action_detail: String(rec.action_detail ?? "") > "" ? bytePrefix(String(rec.action_detail), DEGRADE_COMMAND_BYTES) : "",
|
|
638
647
|
description: "",
|
|
639
648
|
reason: String(rec.reason ?? "").slice(0, 256)
|
|
640
649
|
};
|
|
@@ -961,6 +970,26 @@ var init_json_storage = __esm({
|
|
|
961
970
|
}
|
|
962
971
|
return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
|
|
963
972
|
}
|
|
973
|
+
deleteToolCalls(ids) {
|
|
974
|
+
if (ids.length === 0) return 0;
|
|
975
|
+
const want = new Set(ids);
|
|
976
|
+
let removed = 0;
|
|
977
|
+
try {
|
|
978
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
979
|
+
for (const file of files) {
|
|
980
|
+
const full = (0, import_path2.join)(this.toolCallsDir, file);
|
|
981
|
+
const records = this.readJsonFile(full, []);
|
|
982
|
+
const kept = records.filter((r) => !want.has(Number(r.id)));
|
|
983
|
+
const diff = records.length - kept.length;
|
|
984
|
+
if (diff > 0) {
|
|
985
|
+
removed += diff;
|
|
986
|
+
this.writeJsonFile(full, kept);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
} catch {
|
|
990
|
+
}
|
|
991
|
+
return removed;
|
|
992
|
+
}
|
|
964
993
|
clearToolCalls() {
|
|
965
994
|
let removed = 0;
|
|
966
995
|
try {
|
|
@@ -1010,12 +1039,12 @@ var init_json_storage = __esm({
|
|
|
1010
1039
|
const toArchive = flat.slice(0, archiveCount);
|
|
1011
1040
|
const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
|
|
1012
1041
|
const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync5 } = require("fs");
|
|
1013
|
-
const { join:
|
|
1042
|
+
const { join: join7 } = require("path");
|
|
1014
1043
|
const { gzipSync } = require("zlib");
|
|
1015
|
-
const archiveDir =
|
|
1044
|
+
const archiveDir = join7(this.dataDir, "archive");
|
|
1016
1045
|
if (!(0, import_fs2.existsSync)(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1017
1046
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1018
|
-
const file =
|
|
1047
|
+
const file = join7(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1019
1048
|
const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
|
|
1020
1049
|
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1021
1050
|
for (const [sid, recs] of bySession) {
|
|
@@ -1353,16 +1382,26 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1353
1382
|
const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
|
|
1354
1383
|
let dbBytes = 0;
|
|
1355
1384
|
try {
|
|
1356
|
-
const { statSync: statSync3, existsSync:
|
|
1385
|
+
const { statSync: statSync3, existsSync: existsSync6 } = require("fs");
|
|
1357
1386
|
dbBytes = statSync3(this.dbPath).size;
|
|
1358
1387
|
for (const suffix of ["-wal", "-shm"]) {
|
|
1359
1388
|
const p = this.dbPath + suffix;
|
|
1360
|
-
if (
|
|
1389
|
+
if (existsSync6(p)) dbBytes += statSync3(p).size;
|
|
1361
1390
|
}
|
|
1362
1391
|
} catch {
|
|
1363
1392
|
}
|
|
1364
1393
|
return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
|
|
1365
1394
|
}
|
|
1395
|
+
deleteToolCalls(ids) {
|
|
1396
|
+
if (ids.length === 0) return 0;
|
|
1397
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1398
|
+
const result = this.db.transaction(() => {
|
|
1399
|
+
const del = this.db.prepare(`DELETE FROM tool_calls WHERE id IN (${placeholders})`).run(...ids);
|
|
1400
|
+
this.db.prepare("UPDATE sessions SET tool_call_count = (SELECT COUNT(*) FROM tool_calls WHERE tool_calls.session_id = sessions.id)").run();
|
|
1401
|
+
return Number(del.changes);
|
|
1402
|
+
})();
|
|
1403
|
+
return result;
|
|
1404
|
+
}
|
|
1366
1405
|
clearToolCalls() {
|
|
1367
1406
|
const result = this.db.transaction(() => {
|
|
1368
1407
|
const deleted = this.db.prepare("DELETE FROM tool_calls").run();
|
|
@@ -1390,13 +1429,13 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1390
1429
|
"SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
|
|
1391
1430
|
).all(cutoff.id);
|
|
1392
1431
|
if (rows.length === 0) return { archived: 0, file: "" };
|
|
1393
|
-
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync:
|
|
1394
|
-
const { dirname: dirname6, join:
|
|
1432
|
+
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync: existsSync6 } = require("fs");
|
|
1433
|
+
const { dirname: dirname6, join: join7 } = require("path");
|
|
1395
1434
|
const { gzipSync } = require("zlib");
|
|
1396
|
-
const archiveDir =
|
|
1397
|
-
if (!
|
|
1435
|
+
const archiveDir = join7(dirname6(this.dbPath), "archive");
|
|
1436
|
+
if (!existsSync6(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1398
1437
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1399
|
-
const file =
|
|
1438
|
+
const file = join7(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1400
1439
|
const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
|
|
1401
1440
|
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1402
1441
|
const deleted = this.db.transaction(() => {
|
|
@@ -1525,14 +1564,14 @@ function getDb(dbPath) {
|
|
|
1525
1564
|
if (rawDb) return rawDb;
|
|
1526
1565
|
try {
|
|
1527
1566
|
const Database = require("better-sqlite3");
|
|
1528
|
-
const { existsSync:
|
|
1529
|
-
const { join:
|
|
1567
|
+
const { existsSync: existsSync6, mkdirSync: mkdirSync6 } = require("fs");
|
|
1568
|
+
const { join: join7, dirname: dirname6 } = require("path");
|
|
1530
1569
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
1531
|
-
const xdgData = process.env.XDG_DATA_HOME ||
|
|
1532
|
-
const defaultPath =
|
|
1570
|
+
const xdgData = process.env.XDG_DATA_HOME || join7(home, ".local", "share");
|
|
1571
|
+
const defaultPath = join7(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
1533
1572
|
const path3 = dbPath || defaultPath;
|
|
1534
1573
|
const dir = dirname6(path3);
|
|
1535
|
-
if (!
|
|
1574
|
+
if (!existsSync6(dir)) mkdirSync6(dir, { recursive: true });
|
|
1536
1575
|
rawDb = new Database(path3);
|
|
1537
1576
|
rawDb.pragma("journal_mode = WAL");
|
|
1538
1577
|
return rawDb;
|
|
@@ -1716,8 +1755,28 @@ function logDegraded(notes) {
|
|
|
1716
1755
|
function resetDegradedThrottleForTests() {
|
|
1717
1756
|
DEGRADED_LAST_LOGGED.clear();
|
|
1718
1757
|
}
|
|
1758
|
+
function resolveLocalMossPort(url) {
|
|
1759
|
+
try {
|
|
1760
|
+
const m = url.match(/^(https?):\/\/([^/:]+|\[[^\]]+\])(?::(\d+))?(\/.*)?$/i);
|
|
1761
|
+
if (!m) return url;
|
|
1762
|
+
const [, scheme, host, portStr, rest] = m;
|
|
1763
|
+
if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(host)) return url;
|
|
1764
|
+
const configured = Number(portStr) || (scheme.toLowerCase() === "https" ? 443 : 80);
|
|
1765
|
+
const root = process.env.AGENT_MOSS_DATA_DIR || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".config", "agentmoss");
|
|
1766
|
+
const pf = (0, import_node_path2.join)(root, "agent_moss_server.port.json");
|
|
1767
|
+
if (!(0, import_node_fs2.existsSync)(pf)) return url;
|
|
1768
|
+
const port = Number(JSON.parse((0, import_node_fs2.readFileSync)(pf, "utf-8")).port || 0);
|
|
1769
|
+
if (!port || port === configured) return url;
|
|
1770
|
+
console.warn(
|
|
1771
|
+
`[AgentGate] AgentMoss \u7AEF\u53E3\u6587\u4EF6\u663E\u793A\u5B9E\u9645\u7AEF\u53E3 ${port}\uFF08\u914D\u7F6E ${configured}\uFF09\uFF0C\u91C7\u7528\u5B9E\u9645\u7AEF\u53E3`
|
|
1772
|
+
);
|
|
1773
|
+
return `${scheme}://${host}:${port}${rest || ""}`;
|
|
1774
|
+
} catch {
|
|
1775
|
+
return url;
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1719
1778
|
function setMossUrl(url) {
|
|
1720
|
-
mossUrl = url;
|
|
1779
|
+
mossUrl = resolveLocalMossPort(url);
|
|
1721
1780
|
}
|
|
1722
1781
|
async function callAgentMoss(request) {
|
|
1723
1782
|
try {
|
|
@@ -1807,18 +1866,23 @@ function failClosedResponse(reason, riskType = "service_unavailable") {
|
|
|
1807
1866
|
confidence: 100
|
|
1808
1867
|
};
|
|
1809
1868
|
}
|
|
1810
|
-
var import_node_fetch, DEFAULT_MOSS_URL, DEGRADED_LAST_LOGGED, DEGRADED_LOG_INTERVAL_MS, mossUrl;
|
|
1869
|
+
var import_node_fetch, import_node_fs2, import_node_os2, import_node_path2, DEFAULT_MOSS_URL, DEGRADED_LAST_LOGGED, DEGRADED_LOG_INTERVAL_MS, mossUrl;
|
|
1811
1870
|
var init_moss_client = __esm({
|
|
1812
1871
|
"src/shared/moss-client.ts"() {
|
|
1813
1872
|
"use strict";
|
|
1814
1873
|
init_cjs_shims();
|
|
1815
1874
|
import_node_fetch = __toESM(require("node-fetch"));
|
|
1875
|
+
import_node_fs2 = require("fs");
|
|
1876
|
+
import_node_os2 = require("os");
|
|
1877
|
+
import_node_path2 = require("path");
|
|
1816
1878
|
init_multi_session();
|
|
1817
1879
|
init_security();
|
|
1818
1880
|
DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
|
|
1819
1881
|
DEGRADED_LAST_LOGGED = /* @__PURE__ */ new Map();
|
|
1820
1882
|
DEGRADED_LOG_INTERVAL_MS = 3e5;
|
|
1821
|
-
mossUrl =
|
|
1883
|
+
mossUrl = resolveLocalMossPort(
|
|
1884
|
+
process.env.AGENT_MOSS_URL || process.env.MOSS_URL || DEFAULT_MOSS_URL
|
|
1885
|
+
);
|
|
1822
1886
|
}
|
|
1823
1887
|
});
|
|
1824
1888
|
|
|
@@ -1828,7 +1892,7 @@ var init_version = __esm({
|
|
|
1828
1892
|
"src/version.ts"() {
|
|
1829
1893
|
"use strict";
|
|
1830
1894
|
init_cjs_shims();
|
|
1831
|
-
_version = true ? "0.9.
|
|
1895
|
+
_version = true ? "0.9.14" : (() => {
|
|
1832
1896
|
try {
|
|
1833
1897
|
const require2 = createRequire(importMetaUrl);
|
|
1834
1898
|
const pkg = require2("../package.json");
|
|
@@ -2163,6 +2227,9 @@ function getStorageStats() {
|
|
|
2163
2227
|
function clearToolCalls() {
|
|
2164
2228
|
return store().clearToolCalls();
|
|
2165
2229
|
}
|
|
2230
|
+
function deleteToolCalls(ids) {
|
|
2231
|
+
return store().deleteToolCalls(ids);
|
|
2232
|
+
}
|
|
2166
2233
|
function archiveOldRecords(keep) {
|
|
2167
2234
|
return store().archiveOldRecords(keep);
|
|
2168
2235
|
}
|
|
@@ -2806,7 +2873,9 @@ async function healthRoute(c) {
|
|
|
2806
2873
|
// 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
|
|
2807
2874
|
// 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
|
|
2808
2875
|
// /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
|
|
2809
|
-
instance: process.env.AGENT_GATE_INSTANCE || ""
|
|
2876
|
+
instance: process.env.AGENT_GATE_INSTANCE || "",
|
|
2877
|
+
// 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
|
|
2878
|
+
port: parseInt(process.env.AGENT_GATE_ACTUAL_PORT || "0", 10) || 0
|
|
2810
2879
|
});
|
|
2811
2880
|
}
|
|
2812
2881
|
function storageOversizeInfo() {
|
|
@@ -2988,16 +3057,28 @@ function storageStatsRoute(c) {
|
|
|
2988
3057
|
const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
|
|
2989
3058
|
return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
|
|
2990
3059
|
}
|
|
2991
|
-
function deleteToolCallsRoute(c) {
|
|
3060
|
+
async function deleteToolCallsRoute(c) {
|
|
2992
3061
|
if (boundAgentOf(c.get("principal") || "")) {
|
|
2993
3062
|
return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u6E05\u7406\u8BB0\u5F55" }, 403);
|
|
2994
3063
|
}
|
|
2995
|
-
|
|
2996
|
-
|
|
3064
|
+
let ids;
|
|
3065
|
+
try {
|
|
3066
|
+
const body = await c.req.json();
|
|
3067
|
+
ids = body?.ids;
|
|
3068
|
+
} catch {
|
|
3069
|
+
}
|
|
3070
|
+
if (ids === void 0) {
|
|
3071
|
+
return c.json({ deleted: clearToolCalls() });
|
|
3072
|
+
}
|
|
3073
|
+
if (!Array.isArray(ids)) {
|
|
3074
|
+
return c.json({ detail: "ids must be an array" }, 400);
|
|
3075
|
+
}
|
|
3076
|
+
const numeric = ids.map((v) => Number(v)).filter((n) => Number.isInteger(n) && n > 0);
|
|
3077
|
+
return c.json({ deleted: deleteToolCalls(numeric) });
|
|
2997
3078
|
}
|
|
2998
3079
|
async function sessionLogsRoute(c) {
|
|
2999
3080
|
const { readdirSync: readdirSync2, statSync: statSync3 } = await import("fs");
|
|
3000
|
-
const { join:
|
|
3081
|
+
const { join: join7 } = await import("path");
|
|
3001
3082
|
const { load: load2, summarize: summarize2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
3002
3083
|
const dir = DEFAULT_LOG_DIR2;
|
|
3003
3084
|
let files = [];
|
|
@@ -3007,7 +3088,7 @@ async function sessionLogsRoute(c) {
|
|
|
3007
3088
|
files = [];
|
|
3008
3089
|
}
|
|
3009
3090
|
const logs = files.map((f) => {
|
|
3010
|
-
const full =
|
|
3091
|
+
const full = join7(dir, f);
|
|
3011
3092
|
let mtime = 0;
|
|
3012
3093
|
try {
|
|
3013
3094
|
mtime = statSync3(full).mtimeMs;
|
|
@@ -3026,8 +3107,8 @@ async function sessionLogsRoute(c) {
|
|
|
3026
3107
|
return c.json({ total: logs.length, logs });
|
|
3027
3108
|
}
|
|
3028
3109
|
async function sessionLogDetailRoute(c) {
|
|
3029
|
-
const { existsSync:
|
|
3030
|
-
const { join:
|
|
3110
|
+
const { existsSync: existsSync6 } = await import("fs");
|
|
3111
|
+
const { join: join7 } = await import("path");
|
|
3031
3112
|
const { load: load2, summarize: summarize2, buildTrajectory: buildTrajectory2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
3032
3113
|
const sessionId = c.req.param("id") || "";
|
|
3033
3114
|
const principal = c.get("principal") || "ip:unknown";
|
|
@@ -3038,8 +3119,8 @@ async function sessionLogDetailRoute(c) {
|
|
|
3038
3119
|
}
|
|
3039
3120
|
console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u8DE8\u4F1A\u8BDD\u626B\u63CF: key=${principal} \u7A97\u53E3\u5185\u8BBF\u95EE\u4E86 ${n} \u4E2A\u4E0D\u540C session`);
|
|
3040
3121
|
}
|
|
3041
|
-
const path3 =
|
|
3042
|
-
if (!
|
|
3122
|
+
const path3 = join7(DEFAULT_LOG_DIR2, `${sessionId}.jsonl`);
|
|
3123
|
+
if (!existsSync6(path3)) {
|
|
3043
3124
|
return c.json({ detail: `no session log for ${sessionId}` }, 404);
|
|
3044
3125
|
}
|
|
3045
3126
|
const log = load2(path3, sessionId);
|
|
@@ -3208,7 +3289,7 @@ async function dashboardRoute(c) {
|
|
|
3208
3289
|
return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
|
|
3209
3290
|
}
|
|
3210
3291
|
}
|
|
3211
|
-
const { readFileSync:
|
|
3292
|
+
const { readFileSync: readFileSync6, existsSync: existsSync6 } = await import("fs");
|
|
3212
3293
|
const { resolve: resolve2, dirname: dirname6 } = await import("path");
|
|
3213
3294
|
const { fileURLToPath } = await import("url");
|
|
3214
3295
|
const __dirname = dirname6(fileURLToPath(importMetaUrl));
|
|
@@ -3217,8 +3298,8 @@ async function dashboardRoute(c) {
|
|
|
3217
3298
|
resolve2(__dirname, "../dashboard.html"),
|
|
3218
3299
|
resolve2(__dirname, "../src/v1/dashboard.html")
|
|
3219
3300
|
];
|
|
3220
|
-
const htmlPath = paths.find((p) =>
|
|
3221
|
-
const html =
|
|
3301
|
+
const htmlPath = paths.find((p) => existsSync6(p)) || paths[0];
|
|
3302
|
+
const html = readFileSync6(htmlPath, "utf-8");
|
|
3222
3303
|
return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
|
|
3223
3304
|
}
|
|
3224
3305
|
var import_hono, import_cors, import_logger, import_cookie, PUBLIC_PAGE_PATHS, UNAUTHORIZED_HTML, AGENT_FORBIDDEN_HTML;
|
|
@@ -3335,6 +3416,33 @@ var init_maintenance = __esm({
|
|
|
3335
3416
|
|
|
3336
3417
|
// src/v1/cli.ts
|
|
3337
3418
|
init_cjs_shims();
|
|
3419
|
+
async function findFreePort(startPort, host, scan = 100) {
|
|
3420
|
+
const net = await import("net");
|
|
3421
|
+
for (let candidate = startPort; candidate < startPort + scan; candidate++) {
|
|
3422
|
+
const free = await new Promise((resolve2) => {
|
|
3423
|
+
const srv = net.createServer();
|
|
3424
|
+
srv.once("error", () => resolve2(false));
|
|
3425
|
+
srv.listen(candidate, host, () => srv.close(() => resolve2(true)));
|
|
3426
|
+
});
|
|
3427
|
+
if (free) return candidate;
|
|
3428
|
+
}
|
|
3429
|
+
return startPort;
|
|
3430
|
+
}
|
|
3431
|
+
async function writePortFile(port, dbPath) {
|
|
3432
|
+
try {
|
|
3433
|
+
const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync5, renameSync: renameSync2 } = await import("fs");
|
|
3434
|
+
const { dirname: dirname6, join: join7 } = await import("path");
|
|
3435
|
+
const path3 = join7(dirname6(dbPath), "agent_gate_server.port.json");
|
|
3436
|
+
mkdirSync6(dirname6(path3), { recursive: true });
|
|
3437
|
+
const payload = JSON.stringify({ port, pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
3438
|
+
const tmp = `${path3}.tmp`;
|
|
3439
|
+
writeFileSync5(tmp, payload, "utf-8");
|
|
3440
|
+
renameSync2(tmp, path3);
|
|
3441
|
+
console.log(`[AgentGate] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path3} (port=${port})`);
|
|
3442
|
+
} catch (err) {
|
|
3443
|
+
console.warn("[AgentGate] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3338
3446
|
async function main() {
|
|
3339
3447
|
const args = process.argv.slice(2);
|
|
3340
3448
|
const command = args[0];
|
|
@@ -3382,15 +3490,19 @@ async function main() {
|
|
|
3382
3490
|
const { serve } = await import("@hono/node-server");
|
|
3383
3491
|
const { createApp: createApp2 } = await Promise.resolve().then(() => (init_server(), server_exports));
|
|
3384
3492
|
const app = createApp2();
|
|
3385
|
-
|
|
3493
|
+
const actualPort = await findFreePort(port, host);
|
|
3494
|
+
if (actualPort !== port) console.warn(`[AgentGate] Port ${port} in use, using ${actualPort} instead`);
|
|
3495
|
+
process.env.AGENT_GATE_ACTUAL_PORT = String(actualPort);
|
|
3496
|
+
await writePortFile(actualPort, getAgentGateDbPath2());
|
|
3497
|
+
console.log(`AgentGate HTTP server on ${host}:${actualPort}`);
|
|
3386
3498
|
if (authEnabled2() && authToken2()) {
|
|
3387
|
-
const dash = `http://localhost:${
|
|
3499
|
+
const dash = `http://localhost:${actualPort}/dashboard/?token=${authToken2()}`;
|
|
3388
3500
|
console.log(
|
|
3389
3501
|
`Dashboard: ${process.stdout.isTTY ? dash : dash.replace(/([?&]token=)[^&\s"']+/gi, "$1***")}`
|
|
3390
3502
|
);
|
|
3391
3503
|
}
|
|
3392
|
-
serve({ fetch: app.fetch, hostname: host, port }, (
|
|
3393
|
-
console.log(`Listening on http://${host}:${
|
|
3504
|
+
serve({ fetch: app.fetch, hostname: host, port: actualPort }, () => {
|
|
3505
|
+
console.log(`Listening on http://${host}:${actualPort}`);
|
|
3394
3506
|
});
|
|
3395
3507
|
try {
|
|
3396
3508
|
const { startStorageMaintenance: startStorageMaintenance2 } = await Promise.resolve().then(() => (init_maintenance(), maintenance_exports));
|
package/dist/v1/server.js
CHANGED
|
@@ -606,8 +606,28 @@ function logDegraded(notes) {
|
|
|
606
606
|
function resetDegradedThrottleForTests() {
|
|
607
607
|
DEGRADED_LAST_LOGGED.clear();
|
|
608
608
|
}
|
|
609
|
+
function resolveLocalMossPort(url) {
|
|
610
|
+
try {
|
|
611
|
+
const m = url.match(/^(https?):\/\/([^/:]+|\[[^\]]+\])(?::(\d+))?(\/.*)?$/i);
|
|
612
|
+
if (!m) return url;
|
|
613
|
+
const [, scheme, host, portStr, rest] = m;
|
|
614
|
+
if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(host)) return url;
|
|
615
|
+
const configured = Number(portStr) || (scheme.toLowerCase() === "https" ? 443 : 80);
|
|
616
|
+
const root = process.env.AGENT_MOSS_DATA_DIR || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".config", "agentmoss");
|
|
617
|
+
const pf = (0, import_node_path2.join)(root, "agent_moss_server.port.json");
|
|
618
|
+
if (!(0, import_node_fs2.existsSync)(pf)) return url;
|
|
619
|
+
const port = Number(JSON.parse((0, import_node_fs2.readFileSync)(pf, "utf-8")).port || 0);
|
|
620
|
+
if (!port || port === configured) return url;
|
|
621
|
+
console.warn(
|
|
622
|
+
`[AgentGate] AgentMoss \u7AEF\u53E3\u6587\u4EF6\u663E\u793A\u5B9E\u9645\u7AEF\u53E3 ${port}\uFF08\u914D\u7F6E ${configured}\uFF09\uFF0C\u91C7\u7528\u5B9E\u9645\u7AEF\u53E3`
|
|
623
|
+
);
|
|
624
|
+
return `${scheme}://${host}:${port}${rest || ""}`;
|
|
625
|
+
} catch {
|
|
626
|
+
return url;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
609
629
|
function setMossUrl(url) {
|
|
610
|
-
mossUrl = url;
|
|
630
|
+
mossUrl = resolveLocalMossPort(url);
|
|
611
631
|
}
|
|
612
632
|
async function callAgentMoss(request) {
|
|
613
633
|
try {
|
|
@@ -697,28 +717,42 @@ function failClosedResponse(reason, riskType = "service_unavailable") {
|
|
|
697
717
|
confidence: 100
|
|
698
718
|
};
|
|
699
719
|
}
|
|
700
|
-
var import_node_fetch, DEFAULT_MOSS_URL, DEGRADED_LAST_LOGGED, DEGRADED_LOG_INTERVAL_MS, mossUrl;
|
|
720
|
+
var import_node_fetch, import_node_fs2, import_node_os2, import_node_path2, DEFAULT_MOSS_URL, DEGRADED_LAST_LOGGED, DEGRADED_LOG_INTERVAL_MS, mossUrl;
|
|
701
721
|
var init_moss_client = __esm({
|
|
702
722
|
"src/shared/moss-client.ts"() {
|
|
703
723
|
"use strict";
|
|
704
724
|
init_cjs_shims();
|
|
705
725
|
import_node_fetch = __toESM(require("node-fetch"));
|
|
726
|
+
import_node_fs2 = require("fs");
|
|
727
|
+
import_node_os2 = require("os");
|
|
728
|
+
import_node_path2 = require("path");
|
|
706
729
|
init_multi_session();
|
|
707
730
|
init_security();
|
|
708
731
|
DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
|
|
709
732
|
DEGRADED_LAST_LOGGED = /* @__PURE__ */ new Map();
|
|
710
733
|
DEGRADED_LOG_INTERVAL_MS = 3e5;
|
|
711
|
-
mossUrl =
|
|
734
|
+
mossUrl = resolveLocalMossPort(
|
|
735
|
+
process.env.AGENT_MOSS_URL || process.env.MOSS_URL || DEFAULT_MOSS_URL
|
|
736
|
+
);
|
|
712
737
|
}
|
|
713
738
|
});
|
|
714
739
|
|
|
715
740
|
// src/shared/storage/record-guard.ts
|
|
741
|
+
function bytePrefix(value, limit) {
|
|
742
|
+
const buf = Buffer.from(value, "utf8");
|
|
743
|
+
if (buf.length <= limit) return value;
|
|
744
|
+
let end = limit;
|
|
745
|
+
while (end > 0 && (buf[end] & 192) === 128) end--;
|
|
746
|
+
return buf.subarray(0, end).toString("utf8");
|
|
747
|
+
}
|
|
716
748
|
function clipText(value, limit = maxRecordBytes()) {
|
|
717
749
|
const s = String(value ?? "");
|
|
718
|
-
|
|
719
|
-
|
|
750
|
+
const raw = Buffer.from(s, "utf8");
|
|
751
|
+
if (limit <= 0 || raw.length <= limit) return s;
|
|
752
|
+
const head = bytePrefix(s, limit);
|
|
720
753
|
const digest = (0, import_crypto2.createHash)("sha256").update(s).digest("hex").slice(0, 16);
|
|
721
|
-
|
|
754
|
+
const removed = raw.length - Buffer.byteLength(head, "utf8");
|
|
755
|
+
return `${head}\u2026[truncated ${removed}B sha256:${digest}]`;
|
|
722
756
|
}
|
|
723
757
|
function diskFreePercent(targetPath) {
|
|
724
758
|
try {
|
|
@@ -738,11 +772,11 @@ function shouldDegradeWrites(targetPath) {
|
|
|
738
772
|
}
|
|
739
773
|
function degradeRecord(rec) {
|
|
740
774
|
const command = String(rec.command ?? "");
|
|
741
|
-
const clipped = command
|
|
775
|
+
const clipped = Buffer.byteLength(command, "utf8") > DEGRADE_COMMAND_BYTES ? `${bytePrefix(command, DEGRADE_COMMAND_BYTES)}\u2026[degraded]` : command;
|
|
742
776
|
return {
|
|
743
777
|
...rec,
|
|
744
778
|
command: clipped,
|
|
745
|
-
action_detail: String(rec.action_detail ?? "") > "" ? String(rec.action_detail)
|
|
779
|
+
action_detail: String(rec.action_detail ?? "") > "" ? bytePrefix(String(rec.action_detail), DEGRADE_COMMAND_BYTES) : "",
|
|
746
780
|
description: "",
|
|
747
781
|
reason: String(rec.reason ?? "").slice(0, 256)
|
|
748
782
|
};
|
|
@@ -1069,6 +1103,26 @@ var init_json_storage = __esm({
|
|
|
1069
1103
|
}
|
|
1070
1104
|
return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
|
|
1071
1105
|
}
|
|
1106
|
+
deleteToolCalls(ids) {
|
|
1107
|
+
if (ids.length === 0) return 0;
|
|
1108
|
+
const want = new Set(ids);
|
|
1109
|
+
let removed = 0;
|
|
1110
|
+
try {
|
|
1111
|
+
const files = (0, import_fs3.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
1112
|
+
for (const file of files) {
|
|
1113
|
+
const full = (0, import_path3.join)(this.toolCallsDir, file);
|
|
1114
|
+
const records = this.readJsonFile(full, []);
|
|
1115
|
+
const kept = records.filter((r) => !want.has(Number(r.id)));
|
|
1116
|
+
const diff = records.length - kept.length;
|
|
1117
|
+
if (diff > 0) {
|
|
1118
|
+
removed += diff;
|
|
1119
|
+
this.writeJsonFile(full, kept);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
} catch {
|
|
1123
|
+
}
|
|
1124
|
+
return removed;
|
|
1125
|
+
}
|
|
1072
1126
|
clearToolCalls() {
|
|
1073
1127
|
let removed = 0;
|
|
1074
1128
|
try {
|
|
@@ -1118,12 +1172,12 @@ var init_json_storage = __esm({
|
|
|
1118
1172
|
const toArchive = flat.slice(0, archiveCount);
|
|
1119
1173
|
const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
|
|
1120
1174
|
const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync5 } = require("fs");
|
|
1121
|
-
const { join:
|
|
1175
|
+
const { join: join7 } = require("path");
|
|
1122
1176
|
const { gzipSync } = require("zlib");
|
|
1123
|
-
const archiveDir =
|
|
1177
|
+
const archiveDir = join7(this.dataDir, "archive");
|
|
1124
1178
|
if (!(0, import_fs3.existsSync)(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1125
1179
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1126
|
-
const file =
|
|
1180
|
+
const file = join7(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1127
1181
|
const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
|
|
1128
1182
|
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1129
1183
|
for (const [sid, recs] of bySession) {
|
|
@@ -1461,16 +1515,26 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1461
1515
|
const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
|
|
1462
1516
|
let dbBytes = 0;
|
|
1463
1517
|
try {
|
|
1464
|
-
const { statSync: statSync3, existsSync:
|
|
1518
|
+
const { statSync: statSync3, existsSync: existsSync6 } = require("fs");
|
|
1465
1519
|
dbBytes = statSync3(this.dbPath).size;
|
|
1466
1520
|
for (const suffix of ["-wal", "-shm"]) {
|
|
1467
1521
|
const p = this.dbPath + suffix;
|
|
1468
|
-
if (
|
|
1522
|
+
if (existsSync6(p)) dbBytes += statSync3(p).size;
|
|
1469
1523
|
}
|
|
1470
1524
|
} catch {
|
|
1471
1525
|
}
|
|
1472
1526
|
return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
|
|
1473
1527
|
}
|
|
1528
|
+
deleteToolCalls(ids) {
|
|
1529
|
+
if (ids.length === 0) return 0;
|
|
1530
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1531
|
+
const result = this.db.transaction(() => {
|
|
1532
|
+
const del = this.db.prepare(`DELETE FROM tool_calls WHERE id IN (${placeholders})`).run(...ids);
|
|
1533
|
+
this.db.prepare("UPDATE sessions SET tool_call_count = (SELECT COUNT(*) FROM tool_calls WHERE tool_calls.session_id = sessions.id)").run();
|
|
1534
|
+
return Number(del.changes);
|
|
1535
|
+
})();
|
|
1536
|
+
return result;
|
|
1537
|
+
}
|
|
1474
1538
|
clearToolCalls() {
|
|
1475
1539
|
const result = this.db.transaction(() => {
|
|
1476
1540
|
const deleted = this.db.prepare("DELETE FROM tool_calls").run();
|
|
@@ -1498,13 +1562,13 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1498
1562
|
"SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
|
|
1499
1563
|
).all(cutoff.id);
|
|
1500
1564
|
if (rows.length === 0) return { archived: 0, file: "" };
|
|
1501
|
-
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync:
|
|
1502
|
-
const { dirname: dirname6, join:
|
|
1565
|
+
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync: existsSync6 } = require("fs");
|
|
1566
|
+
const { dirname: dirname6, join: join7 } = require("path");
|
|
1503
1567
|
const { gzipSync } = require("zlib");
|
|
1504
|
-
const archiveDir =
|
|
1505
|
-
if (!
|
|
1568
|
+
const archiveDir = join7(dirname6(this.dbPath), "archive");
|
|
1569
|
+
if (!existsSync6(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1506
1570
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1507
|
-
const file =
|
|
1571
|
+
const file = join7(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1508
1572
|
const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
|
|
1509
1573
|
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1510
1574
|
const deleted = this.db.transaction(() => {
|
|
@@ -1633,14 +1697,14 @@ function getDb(dbPath) {
|
|
|
1633
1697
|
if (rawDb) return rawDb;
|
|
1634
1698
|
try {
|
|
1635
1699
|
const Database = require("better-sqlite3");
|
|
1636
|
-
const { existsSync:
|
|
1637
|
-
const { join:
|
|
1700
|
+
const { existsSync: existsSync6, mkdirSync: mkdirSync6 } = require("fs");
|
|
1701
|
+
const { join: join7, dirname: dirname6 } = require("path");
|
|
1638
1702
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
1639
|
-
const xdgData = process.env.XDG_DATA_HOME ||
|
|
1640
|
-
const defaultPath =
|
|
1703
|
+
const xdgData = process.env.XDG_DATA_HOME || join7(home, ".local", "share");
|
|
1704
|
+
const defaultPath = join7(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
1641
1705
|
const path3 = dbPath || defaultPath;
|
|
1642
1706
|
const dir = dirname6(path3);
|
|
1643
|
-
if (!
|
|
1707
|
+
if (!existsSync6(dir)) mkdirSync6(dir, { recursive: true });
|
|
1644
1708
|
rawDb = new Database(path3);
|
|
1645
1709
|
rawDb.pragma("journal_mode = WAL");
|
|
1646
1710
|
return rawDb;
|
|
@@ -2296,7 +2360,7 @@ var import_zod = require("zod");
|
|
|
2296
2360
|
|
|
2297
2361
|
// src/version.ts
|
|
2298
2362
|
init_cjs_shims();
|
|
2299
|
-
var _version = true ? "0.9.
|
|
2363
|
+
var _version = true ? "0.9.14" : (() => {
|
|
2300
2364
|
try {
|
|
2301
2365
|
const require2 = createRequire(importMetaUrl);
|
|
2302
2366
|
const pkg = require2("../package.json");
|
|
@@ -2591,6 +2655,9 @@ function getStorageStats() {
|
|
|
2591
2655
|
function clearToolCalls() {
|
|
2592
2656
|
return store().clearToolCalls();
|
|
2593
2657
|
}
|
|
2658
|
+
function deleteToolCalls(ids) {
|
|
2659
|
+
return store().deleteToolCalls(ids);
|
|
2660
|
+
}
|
|
2594
2661
|
function getAgentsList(agentType) {
|
|
2595
2662
|
return store().getAgentsList(agentType);
|
|
2596
2663
|
}
|
|
@@ -2629,7 +2696,9 @@ async function healthRoute(c) {
|
|
|
2629
2696
|
// 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
|
|
2630
2697
|
// 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
|
|
2631
2698
|
// /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
|
|
2632
|
-
instance: process.env.AGENT_GATE_INSTANCE || ""
|
|
2699
|
+
instance: process.env.AGENT_GATE_INSTANCE || "",
|
|
2700
|
+
// 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
|
|
2701
|
+
port: parseInt(process.env.AGENT_GATE_ACTUAL_PORT || "0", 10) || 0
|
|
2633
2702
|
});
|
|
2634
2703
|
}
|
|
2635
2704
|
function storageOversizeInfo() {
|
|
@@ -2811,16 +2880,28 @@ function storageStatsRoute(c) {
|
|
|
2811
2880
|
const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
|
|
2812
2881
|
return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
|
|
2813
2882
|
}
|
|
2814
|
-
function deleteToolCallsRoute(c) {
|
|
2883
|
+
async function deleteToolCallsRoute(c) {
|
|
2815
2884
|
if (boundAgentOf(c.get("principal") || "")) {
|
|
2816
2885
|
return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u6E05\u7406\u8BB0\u5F55" }, 403);
|
|
2817
2886
|
}
|
|
2818
|
-
|
|
2819
|
-
|
|
2887
|
+
let ids;
|
|
2888
|
+
try {
|
|
2889
|
+
const body = await c.req.json();
|
|
2890
|
+
ids = body?.ids;
|
|
2891
|
+
} catch {
|
|
2892
|
+
}
|
|
2893
|
+
if (ids === void 0) {
|
|
2894
|
+
return c.json({ deleted: clearToolCalls() });
|
|
2895
|
+
}
|
|
2896
|
+
if (!Array.isArray(ids)) {
|
|
2897
|
+
return c.json({ detail: "ids must be an array" }, 400);
|
|
2898
|
+
}
|
|
2899
|
+
const numeric = ids.map((v) => Number(v)).filter((n) => Number.isInteger(n) && n > 0);
|
|
2900
|
+
return c.json({ deleted: deleteToolCalls(numeric) });
|
|
2820
2901
|
}
|
|
2821
2902
|
async function sessionLogsRoute(c) {
|
|
2822
2903
|
const { readdirSync: readdirSync2, statSync: statSync3 } = await import("fs");
|
|
2823
|
-
const { join:
|
|
2904
|
+
const { join: join7 } = await import("path");
|
|
2824
2905
|
const { load: load2, summarize: summarize2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
2825
2906
|
const dir = DEFAULT_LOG_DIR2;
|
|
2826
2907
|
let files = [];
|
|
@@ -2830,7 +2911,7 @@ async function sessionLogsRoute(c) {
|
|
|
2830
2911
|
files = [];
|
|
2831
2912
|
}
|
|
2832
2913
|
const logs = files.map((f) => {
|
|
2833
|
-
const full =
|
|
2914
|
+
const full = join7(dir, f);
|
|
2834
2915
|
let mtime = 0;
|
|
2835
2916
|
try {
|
|
2836
2917
|
mtime = statSync3(full).mtimeMs;
|
|
@@ -2849,8 +2930,8 @@ async function sessionLogsRoute(c) {
|
|
|
2849
2930
|
return c.json({ total: logs.length, logs });
|
|
2850
2931
|
}
|
|
2851
2932
|
async function sessionLogDetailRoute(c) {
|
|
2852
|
-
const { existsSync:
|
|
2853
|
-
const { join:
|
|
2933
|
+
const { existsSync: existsSync6 } = await import("fs");
|
|
2934
|
+
const { join: join7 } = await import("path");
|
|
2854
2935
|
const { load: load2, summarize: summarize2, buildTrajectory: buildTrajectory2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
2855
2936
|
const sessionId = c.req.param("id") || "";
|
|
2856
2937
|
const principal = c.get("principal") || "ip:unknown";
|
|
@@ -2861,8 +2942,8 @@ async function sessionLogDetailRoute(c) {
|
|
|
2861
2942
|
}
|
|
2862
2943
|
console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u8DE8\u4F1A\u8BDD\u626B\u63CF: key=${principal} \u7A97\u53E3\u5185\u8BBF\u95EE\u4E86 ${n} \u4E2A\u4E0D\u540C session`);
|
|
2863
2944
|
}
|
|
2864
|
-
const path3 =
|
|
2865
|
-
if (!
|
|
2945
|
+
const path3 = join7(DEFAULT_LOG_DIR2, `${sessionId}.jsonl`);
|
|
2946
|
+
if (!existsSync6(path3)) {
|
|
2866
2947
|
return c.json({ detail: `no session log for ${sessionId}` }, 404);
|
|
2867
2948
|
}
|
|
2868
2949
|
const log = load2(path3, sessionId);
|
|
@@ -3041,7 +3122,7 @@ async function dashboardRoute(c) {
|
|
|
3041
3122
|
return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
|
|
3042
3123
|
}
|
|
3043
3124
|
}
|
|
3044
|
-
const { readFileSync:
|
|
3125
|
+
const { readFileSync: readFileSync6, existsSync: existsSync6 } = await import("fs");
|
|
3045
3126
|
const { resolve: resolve2, dirname: dirname6 } = await import("path");
|
|
3046
3127
|
const { fileURLToPath } = await import("url");
|
|
3047
3128
|
const __dirname = dirname6(fileURLToPath(importMetaUrl));
|
|
@@ -3050,8 +3131,8 @@ async function dashboardRoute(c) {
|
|
|
3050
3131
|
resolve2(__dirname, "../dashboard.html"),
|
|
3051
3132
|
resolve2(__dirname, "../src/v1/dashboard.html")
|
|
3052
3133
|
];
|
|
3053
|
-
const htmlPath = paths.find((p) =>
|
|
3054
|
-
const html =
|
|
3134
|
+
const htmlPath = paths.find((p) => existsSync6(p)) || paths[0];
|
|
3135
|
+
const html = readFileSync6(htmlPath, "utf-8");
|
|
3055
3136
|
return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
|
|
3056
3137
|
}
|
|
3057
3138
|
// Annotate the CommonJS export names for ESM import in node:
|
package/dist/v3/cli.js
CHANGED
|
@@ -50,7 +50,7 @@ var init_version = __esm({
|
|
|
50
50
|
"src/version.ts"() {
|
|
51
51
|
"use strict";
|
|
52
52
|
init_cjs_shims();
|
|
53
|
-
_version = true ? "0.9.
|
|
53
|
+
_version = true ? "0.9.14" : (() => {
|
|
54
54
|
try {
|
|
55
55
|
const require2 = createRequire(importMetaUrl);
|
|
56
56
|
const pkg = require2("../package.json");
|
|
@@ -627,12 +627,21 @@ var init_security = __esm({
|
|
|
627
627
|
});
|
|
628
628
|
|
|
629
629
|
// src/shared/storage/record-guard.ts
|
|
630
|
+
function bytePrefix(value, limit) {
|
|
631
|
+
const buf = Buffer.from(value, "utf8");
|
|
632
|
+
if (buf.length <= limit) return value;
|
|
633
|
+
let end = limit;
|
|
634
|
+
while (end > 0 && (buf[end] & 192) === 128) end--;
|
|
635
|
+
return buf.subarray(0, end).toString("utf8");
|
|
636
|
+
}
|
|
630
637
|
function clipText(value, limit = maxRecordBytes()) {
|
|
631
638
|
const s = String(value ?? "");
|
|
632
|
-
|
|
633
|
-
|
|
639
|
+
const raw = Buffer.from(s, "utf8");
|
|
640
|
+
if (limit <= 0 || raw.length <= limit) return s;
|
|
641
|
+
const head = bytePrefix(s, limit);
|
|
634
642
|
const digest = (0, import_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 16);
|
|
635
|
-
|
|
643
|
+
const removed = raw.length - Buffer.byteLength(head, "utf8");
|
|
644
|
+
return `${head}\u2026[truncated ${removed}B sha256:${digest}]`;
|
|
636
645
|
}
|
|
637
646
|
function diskFreePercent(targetPath) {
|
|
638
647
|
try {
|
|
@@ -652,11 +661,11 @@ function shouldDegradeWrites(targetPath) {
|
|
|
652
661
|
}
|
|
653
662
|
function degradeRecord(rec) {
|
|
654
663
|
const command = String(rec.command ?? "");
|
|
655
|
-
const clipped = command
|
|
664
|
+
const clipped = Buffer.byteLength(command, "utf8") > DEGRADE_COMMAND_BYTES ? `${bytePrefix(command, DEGRADE_COMMAND_BYTES)}\u2026[degraded]` : command;
|
|
656
665
|
return {
|
|
657
666
|
...rec,
|
|
658
667
|
command: clipped,
|
|
659
|
-
action_detail: String(rec.action_detail ?? "") > "" ? String(rec.action_detail)
|
|
668
|
+
action_detail: String(rec.action_detail ?? "") > "" ? bytePrefix(String(rec.action_detail), DEGRADE_COMMAND_BYTES) : "",
|
|
660
669
|
description: "",
|
|
661
670
|
reason: String(rec.reason ?? "").slice(0, 256)
|
|
662
671
|
};
|
|
@@ -983,6 +992,26 @@ var init_json_storage = __esm({
|
|
|
983
992
|
}
|
|
984
993
|
return { dbBytes: 0, toolCalls, jsonFiles, jsonBytes };
|
|
985
994
|
}
|
|
995
|
+
deleteToolCalls(ids) {
|
|
996
|
+
if (ids.length === 0) return 0;
|
|
997
|
+
const want = new Set(ids);
|
|
998
|
+
let removed = 0;
|
|
999
|
+
try {
|
|
1000
|
+
const files = (0, import_fs2.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
1001
|
+
for (const file of files) {
|
|
1002
|
+
const full = (0, import_path2.join)(this.toolCallsDir, file);
|
|
1003
|
+
const records = this.readJsonFile(full, []);
|
|
1004
|
+
const kept = records.filter((r) => !want.has(Number(r.id)));
|
|
1005
|
+
const diff = records.length - kept.length;
|
|
1006
|
+
if (diff > 0) {
|
|
1007
|
+
removed += diff;
|
|
1008
|
+
this.writeJsonFile(full, kept);
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
} catch {
|
|
1012
|
+
}
|
|
1013
|
+
return removed;
|
|
1014
|
+
}
|
|
986
1015
|
clearToolCalls() {
|
|
987
1016
|
let removed = 0;
|
|
988
1017
|
try {
|
|
@@ -1032,12 +1061,12 @@ var init_json_storage = __esm({
|
|
|
1032
1061
|
const toArchive = flat.slice(0, archiveCount);
|
|
1033
1062
|
const archiveIds = new Set(toArchive.map((x) => String(x.rec.id)));
|
|
1034
1063
|
const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync5 } = require("fs");
|
|
1035
|
-
const { join:
|
|
1064
|
+
const { join: join14 } = require("path");
|
|
1036
1065
|
const { gzipSync } = require("zlib");
|
|
1037
|
-
const archiveDir =
|
|
1066
|
+
const archiveDir = join14(this.dataDir, "archive");
|
|
1038
1067
|
if (!(0, import_fs2.existsSync)(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1039
1068
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1040
|
-
const file =
|
|
1069
|
+
const file = join14(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1041
1070
|
const payload = toArchive.map((x) => JSON.stringify(x.rec)).join("\n") + "\n";
|
|
1042
1071
|
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1043
1072
|
for (const [sid, recs] of bySession) {
|
|
@@ -1375,16 +1404,26 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1375
1404
|
const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
|
|
1376
1405
|
let dbBytes = 0;
|
|
1377
1406
|
try {
|
|
1378
|
-
const { statSync: statSync10, existsSync:
|
|
1407
|
+
const { statSync: statSync10, existsSync: existsSync14 } = require("fs");
|
|
1379
1408
|
dbBytes = statSync10(this.dbPath).size;
|
|
1380
1409
|
for (const suffix of ["-wal", "-shm"]) {
|
|
1381
1410
|
const p = this.dbPath + suffix;
|
|
1382
|
-
if (
|
|
1411
|
+
if (existsSync14(p)) dbBytes += statSync10(p).size;
|
|
1383
1412
|
}
|
|
1384
1413
|
} catch {
|
|
1385
1414
|
}
|
|
1386
1415
|
return { dbBytes, toolCalls: row?.total ?? 0, jsonFiles: 0, jsonBytes: 0 };
|
|
1387
1416
|
}
|
|
1417
|
+
deleteToolCalls(ids) {
|
|
1418
|
+
if (ids.length === 0) return 0;
|
|
1419
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1420
|
+
const result = this.db.transaction(() => {
|
|
1421
|
+
const del = this.db.prepare(`DELETE FROM tool_calls WHERE id IN (${placeholders})`).run(...ids);
|
|
1422
|
+
this.db.prepare("UPDATE sessions SET tool_call_count = (SELECT COUNT(*) FROM tool_calls WHERE tool_calls.session_id = sessions.id)").run();
|
|
1423
|
+
return Number(del.changes);
|
|
1424
|
+
})();
|
|
1425
|
+
return result;
|
|
1426
|
+
}
|
|
1388
1427
|
clearToolCalls() {
|
|
1389
1428
|
const result = this.db.transaction(() => {
|
|
1390
1429
|
const deleted = this.db.prepare("DELETE FROM tool_calls").run();
|
|
@@ -1412,13 +1451,13 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
1412
1451
|
"SELECT * FROM tool_calls WHERE id <= ? ORDER BY id"
|
|
1413
1452
|
).all(cutoff.id);
|
|
1414
1453
|
if (rows.length === 0) return { archived: 0, file: "" };
|
|
1415
|
-
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync:
|
|
1416
|
-
const { dirname: dirname7, join:
|
|
1454
|
+
const { writeFileSync: writeFileSync5, mkdirSync: mkdirSync6, existsSync: existsSync14 } = require("fs");
|
|
1455
|
+
const { dirname: dirname7, join: join14 } = require("path");
|
|
1417
1456
|
const { gzipSync } = require("zlib");
|
|
1418
|
-
const archiveDir =
|
|
1419
|
-
if (!
|
|
1457
|
+
const archiveDir = join14(dirname7(this.dbPath), "archive");
|
|
1458
|
+
if (!existsSync14(archiveDir)) mkdirSync6(archiveDir, { recursive: true, mode: 448 });
|
|
1420
1459
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1421
|
-
const file =
|
|
1460
|
+
const file = join14(archiveDir, `tool_calls-${stamp}.jsonl.gz`);
|
|
1422
1461
|
const payload = rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
|
|
1423
1462
|
writeFileSync5(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
1424
1463
|
const deleted = this.db.transaction(() => {
|
|
@@ -1547,14 +1586,14 @@ function getDb(dbPath) {
|
|
|
1547
1586
|
if (rawDb) return rawDb;
|
|
1548
1587
|
try {
|
|
1549
1588
|
const Database = require("better-sqlite3");
|
|
1550
|
-
const { existsSync:
|
|
1551
|
-
const { join:
|
|
1589
|
+
const { existsSync: existsSync14, mkdirSync: mkdirSync6 } = require("fs");
|
|
1590
|
+
const { join: join14, dirname: dirname7 } = require("path");
|
|
1552
1591
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
1553
|
-
const xdgData = process.env.XDG_DATA_HOME ||
|
|
1554
|
-
const defaultPath =
|
|
1592
|
+
const xdgData = process.env.XDG_DATA_HOME || join14(home, ".local", "share");
|
|
1593
|
+
const defaultPath = join14(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
1555
1594
|
const path11 = dbPath || defaultPath;
|
|
1556
1595
|
const dir2 = dirname7(path11);
|
|
1557
|
-
if (!
|
|
1596
|
+
if (!existsSync14(dir2)) mkdirSync6(dir2, { recursive: true });
|
|
1558
1597
|
rawDb = new Database(path11);
|
|
1559
1598
|
rawDb.pragma("journal_mode = WAL");
|
|
1560
1599
|
return rawDb;
|
|
@@ -1738,8 +1777,28 @@ function logDegraded(notes) {
|
|
|
1738
1777
|
function resetDegradedThrottleForTests() {
|
|
1739
1778
|
DEGRADED_LAST_LOGGED.clear();
|
|
1740
1779
|
}
|
|
1780
|
+
function resolveLocalMossPort(url) {
|
|
1781
|
+
try {
|
|
1782
|
+
const m = url.match(/^(https?):\/\/([^/:]+|\[[^\]]+\])(?::(\d+))?(\/.*)?$/i);
|
|
1783
|
+
if (!m) return url;
|
|
1784
|
+
const [, scheme, host, portStr, rest] = m;
|
|
1785
|
+
if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(host)) return url;
|
|
1786
|
+
const configured = Number(portStr) || (scheme.toLowerCase() === "https" ? 443 : 80);
|
|
1787
|
+
const root = process.env.AGENT_MOSS_DATA_DIR || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".config", "agentmoss");
|
|
1788
|
+
const pf = (0, import_node_path2.join)(root, "agent_moss_server.port.json");
|
|
1789
|
+
if (!(0, import_node_fs2.existsSync)(pf)) return url;
|
|
1790
|
+
const port = Number(JSON.parse((0, import_node_fs2.readFileSync)(pf, "utf-8")).port || 0);
|
|
1791
|
+
if (!port || port === configured) return url;
|
|
1792
|
+
console.warn(
|
|
1793
|
+
`[AgentGate] AgentMoss \u7AEF\u53E3\u6587\u4EF6\u663E\u793A\u5B9E\u9645\u7AEF\u53E3 ${port}\uFF08\u914D\u7F6E ${configured}\uFF09\uFF0C\u91C7\u7528\u5B9E\u9645\u7AEF\u53E3`
|
|
1794
|
+
);
|
|
1795
|
+
return `${scheme}://${host}:${port}${rest || ""}`;
|
|
1796
|
+
} catch {
|
|
1797
|
+
return url;
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1741
1800
|
function setMossUrl(url) {
|
|
1742
|
-
mossUrl = url;
|
|
1801
|
+
mossUrl = resolveLocalMossPort(url);
|
|
1743
1802
|
}
|
|
1744
1803
|
async function callAgentMoss(request3) {
|
|
1745
1804
|
try {
|
|
@@ -1829,18 +1888,23 @@ function failClosedResponse(reason, riskType = "service_unavailable") {
|
|
|
1829
1888
|
confidence: 100
|
|
1830
1889
|
};
|
|
1831
1890
|
}
|
|
1832
|
-
var import_node_fetch, DEFAULT_MOSS_URL, DEGRADED_LAST_LOGGED, DEGRADED_LOG_INTERVAL_MS, mossUrl;
|
|
1891
|
+
var import_node_fetch, import_node_fs2, import_node_os2, import_node_path2, DEFAULT_MOSS_URL, DEGRADED_LAST_LOGGED, DEGRADED_LOG_INTERVAL_MS, mossUrl;
|
|
1833
1892
|
var init_moss_client = __esm({
|
|
1834
1893
|
"src/shared/moss-client.ts"() {
|
|
1835
1894
|
"use strict";
|
|
1836
1895
|
init_cjs_shims();
|
|
1837
1896
|
import_node_fetch = __toESM(require("node-fetch"));
|
|
1897
|
+
import_node_fs2 = require("fs");
|
|
1898
|
+
import_node_os2 = require("os");
|
|
1899
|
+
import_node_path2 = require("path");
|
|
1838
1900
|
init_multi_session();
|
|
1839
1901
|
init_security();
|
|
1840
1902
|
DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
|
|
1841
1903
|
DEGRADED_LAST_LOGGED = /* @__PURE__ */ new Map();
|
|
1842
1904
|
DEGRADED_LOG_INTERVAL_MS = 3e5;
|
|
1843
|
-
mossUrl =
|
|
1905
|
+
mossUrl = resolveLocalMossPort(
|
|
1906
|
+
process.env.AGENT_MOSS_URL || process.env.MOSS_URL || DEFAULT_MOSS_URL
|
|
1907
|
+
);
|
|
1844
1908
|
}
|
|
1845
1909
|
});
|
|
1846
1910
|
|
|
@@ -2166,6 +2230,9 @@ function getStorageStats() {
|
|
|
2166
2230
|
function clearToolCalls() {
|
|
2167
2231
|
return store().clearToolCalls();
|
|
2168
2232
|
}
|
|
2233
|
+
function deleteToolCalls(ids) {
|
|
2234
|
+
return store().deleteToolCalls(ids);
|
|
2235
|
+
}
|
|
2169
2236
|
function getAgentsList(agentType) {
|
|
2170
2237
|
return store().getAgentsList(agentType);
|
|
2171
2238
|
}
|
|
@@ -2810,7 +2877,9 @@ async function healthRoute(c) {
|
|
|
2810
2877
|
// 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
|
|
2811
2878
|
// 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
|
|
2812
2879
|
// /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
|
|
2813
|
-
instance: process.env.AGENT_GATE_INSTANCE || ""
|
|
2880
|
+
instance: process.env.AGENT_GATE_INSTANCE || "",
|
|
2881
|
+
// 实际监听端口(端口被占用自动漂移后,调用方从这里得知新端口)。
|
|
2882
|
+
port: parseInt(process.env.AGENT_GATE_ACTUAL_PORT || "0", 10) || 0
|
|
2814
2883
|
});
|
|
2815
2884
|
}
|
|
2816
2885
|
function storageOversizeInfo() {
|
|
@@ -2992,16 +3061,28 @@ function storageStatsRoute(c) {
|
|
|
2992
3061
|
const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
|
|
2993
3062
|
return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
|
|
2994
3063
|
}
|
|
2995
|
-
function deleteToolCallsRoute(c) {
|
|
3064
|
+
async function deleteToolCallsRoute(c) {
|
|
2996
3065
|
if (boundAgentOf(c.get("principal") || "")) {
|
|
2997
3066
|
return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u6E05\u7406\u8BB0\u5F55" }, 403);
|
|
2998
3067
|
}
|
|
2999
|
-
|
|
3000
|
-
|
|
3068
|
+
let ids;
|
|
3069
|
+
try {
|
|
3070
|
+
const body = await c.req.json();
|
|
3071
|
+
ids = body?.ids;
|
|
3072
|
+
} catch {
|
|
3073
|
+
}
|
|
3074
|
+
if (ids === void 0) {
|
|
3075
|
+
return c.json({ deleted: clearToolCalls() });
|
|
3076
|
+
}
|
|
3077
|
+
if (!Array.isArray(ids)) {
|
|
3078
|
+
return c.json({ detail: "ids must be an array" }, 400);
|
|
3079
|
+
}
|
|
3080
|
+
const numeric = ids.map((v) => Number(v)).filter((n) => Number.isInteger(n) && n > 0);
|
|
3081
|
+
return c.json({ deleted: deleteToolCalls(numeric) });
|
|
3001
3082
|
}
|
|
3002
3083
|
async function sessionLogsRoute(c) {
|
|
3003
3084
|
const { readdirSync: readdirSync11, statSync: statSync10 } = await import("fs");
|
|
3004
|
-
const { join:
|
|
3085
|
+
const { join: join14 } = await import("path");
|
|
3005
3086
|
const { load: load2, summarize: summarize2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
3006
3087
|
const dir2 = DEFAULT_LOG_DIR2;
|
|
3007
3088
|
let files = [];
|
|
@@ -3011,7 +3092,7 @@ async function sessionLogsRoute(c) {
|
|
|
3011
3092
|
files = [];
|
|
3012
3093
|
}
|
|
3013
3094
|
const logs = files.map((f) => {
|
|
3014
|
-
const full =
|
|
3095
|
+
const full = join14(dir2, f);
|
|
3015
3096
|
let mtime = 0;
|
|
3016
3097
|
try {
|
|
3017
3098
|
mtime = statSync10(full).mtimeMs;
|
|
@@ -3030,8 +3111,8 @@ async function sessionLogsRoute(c) {
|
|
|
3030
3111
|
return c.json({ total: logs.length, logs });
|
|
3031
3112
|
}
|
|
3032
3113
|
async function sessionLogDetailRoute(c) {
|
|
3033
|
-
const { existsSync:
|
|
3034
|
-
const { join:
|
|
3114
|
+
const { existsSync: existsSync14 } = await import("fs");
|
|
3115
|
+
const { join: join14 } = await import("path");
|
|
3035
3116
|
const { load: load2, summarize: summarize2, buildTrajectory: buildTrajectory2, DEFAULT_LOG_DIR: DEFAULT_LOG_DIR2 } = await Promise.resolve().then(() => (init_sessionlog(), sessionlog_exports));
|
|
3036
3117
|
const sessionId = c.req.param("id") || "";
|
|
3037
3118
|
const principal = c.get("principal") || "ip:unknown";
|
|
@@ -3042,8 +3123,8 @@ async function sessionLogDetailRoute(c) {
|
|
|
3042
3123
|
}
|
|
3043
3124
|
console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u8DE8\u4F1A\u8BDD\u626B\u63CF: key=${principal} \u7A97\u53E3\u5185\u8BBF\u95EE\u4E86 ${n} \u4E2A\u4E0D\u540C session`);
|
|
3044
3125
|
}
|
|
3045
|
-
const path11 =
|
|
3046
|
-
if (!
|
|
3126
|
+
const path11 = join14(DEFAULT_LOG_DIR2, `${sessionId}.jsonl`);
|
|
3127
|
+
if (!existsSync14(path11)) {
|
|
3047
3128
|
return c.json({ detail: `no session log for ${sessionId}` }, 404);
|
|
3048
3129
|
}
|
|
3049
3130
|
const log2 = load2(path11, sessionId);
|
|
@@ -3212,7 +3293,7 @@ async function dashboardRoute(c) {
|
|
|
3212
3293
|
return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
|
|
3213
3294
|
}
|
|
3214
3295
|
}
|
|
3215
|
-
const { readFileSync:
|
|
3296
|
+
const { readFileSync: readFileSync16, existsSync: existsSync14 } = await import("fs");
|
|
3216
3297
|
const { resolve: resolve4, dirname: dirname7 } = await import("path");
|
|
3217
3298
|
const { fileURLToPath } = await import("url");
|
|
3218
3299
|
const __dirname2 = dirname7(fileURLToPath(importMetaUrl));
|
|
@@ -3221,8 +3302,8 @@ async function dashboardRoute(c) {
|
|
|
3221
3302
|
resolve4(__dirname2, "../dashboard.html"),
|
|
3222
3303
|
resolve4(__dirname2, "../src/v1/dashboard.html")
|
|
3223
3304
|
];
|
|
3224
|
-
const htmlPath = paths.find((p) =>
|
|
3225
|
-
const html =
|
|
3305
|
+
const htmlPath = paths.find((p) => existsSync14(p)) || paths[0];
|
|
3306
|
+
const html = readFileSync16(htmlPath, "utf-8");
|
|
3226
3307
|
return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
|
|
3227
3308
|
}
|
|
3228
3309
|
var import_hono, import_cors, import_logger, import_cookie, PUBLIC_PAGE_PATHS, UNAUTHORIZED_HTML, AGENT_FORBIDDEN_HTML;
|
|
@@ -29606,12 +29687,12 @@ var trigger_exports = {};
|
|
|
29606
29687
|
__export(trigger_exports, {
|
|
29607
29688
|
TriggerEngine: () => TriggerEngine
|
|
29608
29689
|
});
|
|
29609
|
-
var
|
|
29690
|
+
var import_node_fs3, import_yaml, TriggerEngine;
|
|
29610
29691
|
var init_trigger = __esm({
|
|
29611
29692
|
"src/v3/proxy/trigger.ts"() {
|
|
29612
29693
|
"use strict";
|
|
29613
29694
|
init_cjs_shims();
|
|
29614
|
-
|
|
29695
|
+
import_node_fs3 = require("fs");
|
|
29615
29696
|
import_yaml = require("yaml");
|
|
29616
29697
|
TriggerEngine = class {
|
|
29617
29698
|
_rules = [];
|
|
@@ -29619,7 +29700,7 @@ var init_trigger = __esm({
|
|
|
29619
29700
|
_rateLimitSeconds = 5;
|
|
29620
29701
|
constructor(rulesPath) {
|
|
29621
29702
|
const path11 = rulesPath || "config/trigger_rules.yaml";
|
|
29622
|
-
if (!(0,
|
|
29703
|
+
if (!(0, import_node_fs3.existsSync)(path11)) {
|
|
29623
29704
|
console.error(
|
|
29624
29705
|
`[AgentGate] \u672A\u627E\u5230\u89E6\u53D1\u89C4\u5219\u6587\u4EF6 ${path11} \u2014\u2014 \u4F7F\u7528\u7A7A\u89C4\u5219\u96C6\uFF0C\u6240\u6709\u89E6\u53D1\u89C4\u5219\u90FD\u4E0D\u4F1A\u547D\u4E2D\uFF01\uFF08\u8BF7\u68C0\u67E5\u542F\u52A8\u76EE\u5F55\u6216\u663E\u5F0F\u4F20\u5165 rulesPath\uFF09`
|
|
29625
29706
|
);
|
|
@@ -29635,7 +29716,7 @@ var init_trigger = __esm({
|
|
|
29635
29716
|
return this._rules;
|
|
29636
29717
|
}
|
|
29637
29718
|
_loadRules(path11) {
|
|
29638
|
-
const content = (0,
|
|
29719
|
+
const content = (0, import_node_fs3.readFileSync)(path11, "utf-8");
|
|
29639
29720
|
const data = (0, import_yaml.parse)(content) || {};
|
|
29640
29721
|
const rulesData = data.rules || [];
|
|
29641
29722
|
this._rules = rulesData.map((r) => {
|
|
@@ -29779,7 +29860,7 @@ function timingSafeEqualStr(a, b) {
|
|
|
29779
29860
|
if (ba.length !== bb.length) return false;
|
|
29780
29861
|
return (0, import_node_crypto5.timingSafeEqual)(ba, bb);
|
|
29781
29862
|
}
|
|
29782
|
-
var import_node_http, import_node_crypto5, import_node_url,
|
|
29863
|
+
var import_node_http, import_node_crypto5, import_node_url, import_node_path3, import_node_fs4, import_node_stream, import_http_mitm_proxy, DASHBOARD_COOKIE2, DASHBOARD_HTML, ProxyServer;
|
|
29783
29864
|
var init_server2 = __esm({
|
|
29784
29865
|
"src/v3/proxy/server.ts"() {
|
|
29785
29866
|
"use strict";
|
|
@@ -29787,8 +29868,8 @@ var init_server2 = __esm({
|
|
|
29787
29868
|
import_node_http = __toESM(require("http"));
|
|
29788
29869
|
import_node_crypto5 = require("crypto");
|
|
29789
29870
|
import_node_url = require("url");
|
|
29790
|
-
|
|
29791
|
-
|
|
29871
|
+
import_node_path3 = __toESM(require("path"));
|
|
29872
|
+
import_node_fs4 = __toESM(require("fs"));
|
|
29792
29873
|
import_node_stream = require("stream");
|
|
29793
29874
|
import_http_mitm_proxy = __toESM(require_dist());
|
|
29794
29875
|
init_interceptor();
|
|
@@ -29871,9 +29952,9 @@ load();setInterval(load,5000);
|
|
|
29871
29952
|
this._interceptor = new LLMInterceptor(config, this._sessionAgg, this._triggerEngine, options.coordinator);
|
|
29872
29953
|
}
|
|
29873
29954
|
start() {
|
|
29874
|
-
const caDir = this._options.sslCaDir ||
|
|
29875
|
-
if (!
|
|
29876
|
-
|
|
29955
|
+
const caDir = this._options.sslCaDir || import_node_path3.default.join(process.cwd(), ".agentgate-ssl");
|
|
29956
|
+
if (!import_node_fs4.default.existsSync(caDir)) {
|
|
29957
|
+
import_node_fs4.default.mkdirSync(caDir, { recursive: true });
|
|
29877
29958
|
}
|
|
29878
29959
|
this._mitmProxy = new import_http_mitm_proxy.Proxy();
|
|
29879
29960
|
this._mitmProxy.onError((_ctx, err) => {
|
|
@@ -31121,21 +31202,21 @@ var whitelist_exports = {};
|
|
|
31121
31202
|
__export(whitelist_exports, {
|
|
31122
31203
|
WhitelistEngine: () => WhitelistEngine
|
|
31123
31204
|
});
|
|
31124
|
-
var
|
|
31205
|
+
var import_node_fs5, import_yaml2, WhitelistEngine;
|
|
31125
31206
|
var init_whitelist = __esm({
|
|
31126
31207
|
"src/v3/proxy/whitelist.ts"() {
|
|
31127
31208
|
"use strict";
|
|
31128
31209
|
init_cjs_shims();
|
|
31129
|
-
|
|
31210
|
+
import_node_fs5 = require("fs");
|
|
31130
31211
|
import_yaml2 = require("yaml");
|
|
31131
31212
|
WhitelistEngine = class {
|
|
31132
31213
|
_rules = [];
|
|
31133
31214
|
constructor(rulesPath) {
|
|
31134
31215
|
const path11 = rulesPath || "config/trigger_rules.yaml";
|
|
31135
|
-
if ((0,
|
|
31216
|
+
if ((0, import_node_fs5.existsSync)(path11)) this._loadRules(path11);
|
|
31136
31217
|
}
|
|
31137
31218
|
_loadRules(path11) {
|
|
31138
|
-
const content = (0,
|
|
31219
|
+
const content = (0, import_node_fs5.readFileSync)(path11, "utf-8");
|
|
31139
31220
|
const data = (0, import_yaml2.parse)(content) || {};
|
|
31140
31221
|
const rulesData = data.rules || [];
|
|
31141
31222
|
this._rules = rulesData.filter((r) => r.action === "allow").map((r) => {
|
|
@@ -34625,7 +34706,7 @@ var init_loader = __esm({
|
|
|
34625
34706
|
|
|
34626
34707
|
// src/v3/cli.ts
|
|
34627
34708
|
init_cjs_shims();
|
|
34628
|
-
var
|
|
34709
|
+
var import_node_fs6 = require("fs");
|
|
34629
34710
|
var path10 = __toESM(require("path"));
|
|
34630
34711
|
var import_yaml3 = require("yaml");
|
|
34631
34712
|
init_version();
|
|
@@ -34639,7 +34720,7 @@ function resolveRulesPath(explicit) {
|
|
|
34639
34720
|
candidates.push(path10.resolve(__dirname, "..", "..", "..", "config", "trigger_rules.yaml"));
|
|
34640
34721
|
candidates.push(path10.resolve(process.cwd(), "config", "trigger_rules.yaml"));
|
|
34641
34722
|
for (const p of candidates) {
|
|
34642
|
-
if ((0,
|
|
34723
|
+
if ((0, import_node_fs6.existsSync)(p)) return p;
|
|
34643
34724
|
}
|
|
34644
34725
|
return candidates[0];
|
|
34645
34726
|
}
|
|
@@ -34859,12 +34940,12 @@ Run options:
|
|
|
34859
34940
|
if (envLevel && !args.includes("--level")) level = parseInt(envLevel, 10);
|
|
34860
34941
|
const envDeny = process.env.AGENT_GATE_DENY_ACTION;
|
|
34861
34942
|
if (envDeny && !args.includes("--deny-action")) denyAction = envDeny;
|
|
34862
|
-
if (!(0,
|
|
34943
|
+
if (!(0, import_node_fs6.existsSync)(configPath)) {
|
|
34863
34944
|
console.error(`Config file not found: ${configPath}`);
|
|
34864
34945
|
console.error("Create it with model_routes or use --config <path>");
|
|
34865
34946
|
process.exit(1);
|
|
34866
34947
|
}
|
|
34867
|
-
const yamlContent = (0,
|
|
34948
|
+
const yamlContent = (0, import_node_fs6.readFileSync)(configPath, "utf-8");
|
|
34868
34949
|
const config = (0, import_yaml3.parse)(yamlContent);
|
|
34869
34950
|
const gatewayCfg = config.gateway ?? {};
|
|
34870
34951
|
const modelRoutes = gatewayCfg.model_routes ?? [];
|
|
@@ -35006,7 +35087,7 @@ Run options:
|
|
|
35006
35087
|
const jsonOut = args.includes("--json");
|
|
35007
35088
|
let files = [];
|
|
35008
35089
|
try {
|
|
35009
|
-
files = (0,
|
|
35090
|
+
files = (0, import_node_fs6.readdirSync)(dir2).filter((f) => f.endsWith(".jsonl")).map((f) => path10.join(dir2, f)).sort((a, b) => (0, import_node_fs6.statSync)(b).mtimeMs - (0, import_node_fs6.statSync)(a).mtimeMs);
|
|
35010
35091
|
} catch {
|
|
35011
35092
|
}
|
|
35012
35093
|
if (files.length === 0) {
|