@leeruu/agentguard 0.0.0-stage → 0.1.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.
@@ -0,0 +1,174 @@
1
+ /**
2
+ * 审计写入:一行一次判定,JSONL 追加。
3
+ *
4
+ * 三条约束:
5
+ * 1. **不阻塞转发**:写走 WriteStream(异步),调用方只往队列里塞一行就返回。
6
+ * 2. **参数要截断**:文件内容动辄几 MB,原样落盘一天就能把磁盘吃满。默认 200 字符,
7
+ * 深度截断长字符串 / 超长数组 / 超多键的对象,实在压不下去再退化成 preview。
8
+ * 3. **按天切分 + 保留期**:文件名就是日期,清理只需要按文件名比大小,不读内容。
9
+ *
10
+ * 记录字段与方案第 6 章一致,另加两个可选字段:
11
+ * raw —— dry_run 或 ask 时保留「本来是什么判定」,否则观察模式下看不到真相
12
+ * truncated —— args 被裁剪过
13
+ */
14
+ import { createWriteStream, mkdirSync, readdirSync, unlinkSync, } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { logger } from '../logger.js';
17
+ export const DEFAULT_ARGS_LIMIT = 200;
18
+ export const DEFAULT_KEEP_DAYS = 30;
19
+ const DAY_FILE = /^(\d{4})-(\d{2})-(\d{2})\.jsonl$/;
20
+ const STRING_CAP = 120;
21
+ const ARRAY_CAP = 10;
22
+ const OBJECT_KEYS_CAP = 20;
23
+ export function dayKey(date = new Date()) {
24
+ const y = date.getFullYear();
25
+ const m = String(date.getMonth() + 1).padStart(2, '0');
26
+ const d = String(date.getDate()).padStart(2, '0');
27
+ return `${y}-${m}-${d}`;
28
+ }
29
+ /** 深度裁剪:保住结构,砍掉体积 */
30
+ function clipValue(value) {
31
+ if (typeof value === 'string') {
32
+ return value.length > STRING_CAP ? `${value.slice(0, STRING_CAP)}…` : value;
33
+ }
34
+ if (Array.isArray(value)) {
35
+ const head = value.slice(0, ARRAY_CAP).map(clipValue);
36
+ return value.length > ARRAY_CAP ? [...head, `…(${value.length - ARRAY_CAP} more)`] : head;
37
+ }
38
+ if (typeof value === 'object' && value !== null) {
39
+ const entries = Object.entries(value);
40
+ const kept = entries.slice(0, OBJECT_KEYS_CAP).map(([key, item]) => [key, clipValue(item)]);
41
+ const result = Object.fromEntries(kept);
42
+ if (entries.length > OBJECT_KEYS_CAP) {
43
+ result['…'] = `${entries.length - OBJECT_KEYS_CAP} more keys`;
44
+ }
45
+ return result;
46
+ }
47
+ return value;
48
+ }
49
+ /** 把 args 压到 limit 个字符以内;返回 null 表示无需裁剪 */
50
+ export function clipArgs(args, limit = DEFAULT_ARGS_LIMIT) {
51
+ let serialized;
52
+ try {
53
+ serialized = JSON.stringify(args ?? null);
54
+ }
55
+ catch {
56
+ return { __unserializable: true };
57
+ }
58
+ if (serialized.length <= limit)
59
+ return args;
60
+ const clipped = clipValue(args);
61
+ let clippedSerialized;
62
+ try {
63
+ clippedSerialized = JSON.stringify(clipped);
64
+ }
65
+ catch {
66
+ clippedSerialized = 'null';
67
+ }
68
+ if (clippedSerialized.length <= limit)
69
+ return clipped;
70
+ return {
71
+ __truncated: true,
72
+ size: serialized.length,
73
+ preview: serialized.slice(0, limit),
74
+ };
75
+ }
76
+ export class AuditWriter {
77
+ #dir;
78
+ #argsLimit;
79
+ #stream = null;
80
+ #day = null;
81
+ #broken = false;
82
+ constructor(dir, options = {}) {
83
+ this.#dir = dir;
84
+ this.#argsLimit = options.argsLimit ?? DEFAULT_ARGS_LIMIT;
85
+ mkdirSync(this.#dir, { recursive: true });
86
+ }
87
+ get directory() {
88
+ return this.#dir;
89
+ }
90
+ write(record) {
91
+ if (this.#broken)
92
+ return;
93
+ try {
94
+ const day = dayKey(new Date(record.ts));
95
+ if (this.#stream === null || this.#day !== day)
96
+ this.#open(day);
97
+ const clipped = clipArgs(record.args, this.#argsLimit);
98
+ const payload = { ...record, args: clipped };
99
+ if (clipped !== record.args)
100
+ payload.truncated = true;
101
+ this.#stream?.write(JSON.stringify(payload) + '\n');
102
+ }
103
+ catch (err) {
104
+ // 审计写不进去不阻断转发(否则一个只读的家目录就能让整个网关停摆),
105
+ // 但必须大声报错 —— 静默丢审计比拦错更糟。
106
+ logger.error('审计写入失败,后续记录将被丢弃', { error: err.message });
107
+ this.#broken = true;
108
+ }
109
+ }
110
+ /** 把已入队的数据刷到内核;退出前必须调用 */
111
+ flush() {
112
+ const stream = this.#stream;
113
+ if (stream === null || this.#broken)
114
+ return Promise.resolve();
115
+ return new Promise((resolve) => {
116
+ stream.write('', () => resolve());
117
+ });
118
+ }
119
+ async close() {
120
+ const stream = this.#stream;
121
+ this.#stream = null;
122
+ this.#day = null;
123
+ if (stream === null)
124
+ return;
125
+ await new Promise((resolve) => {
126
+ stream.end(() => resolve());
127
+ });
128
+ }
129
+ #open(day) {
130
+ const previous = this.#stream;
131
+ if (previous !== null)
132
+ previous.end();
133
+ mkdirSync(this.#dir, { recursive: true });
134
+ const stream = createWriteStream(join(this.#dir, `${day}.jsonl`), { flags: 'a' });
135
+ stream.on('error', (err) => {
136
+ logger.error('审计流错误,后续记录将被丢弃', { error: err.message });
137
+ this.#broken = true;
138
+ });
139
+ this.#stream = stream;
140
+ this.#day = day;
141
+ }
142
+ }
143
+ /**
144
+ * 按文件名删掉超过 keepDays 的审计文件。
145
+ * 只比较 `YYYY-MM-DD` 字符串,不读文件内容,代价与文件体积无关。
146
+ */
147
+ export function pruneAudit(dir, keepDays = DEFAULT_KEEP_DAYS, now = Date.now()) {
148
+ if (keepDays <= 0)
149
+ return [];
150
+ const cutoff = dayKey(new Date(now - keepDays * 86_400_000));
151
+ const removed = [];
152
+ let names;
153
+ try {
154
+ names = readdirSync(dir);
155
+ }
156
+ catch {
157
+ return removed;
158
+ }
159
+ for (const name of names) {
160
+ const match = DAY_FILE.exec(name);
161
+ if (match === null)
162
+ continue;
163
+ if (name.slice(0, 10) >= cutoff)
164
+ continue;
165
+ try {
166
+ unlinkSync(join(dir, name));
167
+ removed.push(name);
168
+ }
169
+ catch (err) {
170
+ logger.warn('清理过期审计文件失败', { file: name, error: err.message });
171
+ }
172
+ }
173
+ return removed;
174
+ }