@jjh32456/longlive 2.1.0 → 2.2.0

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,356 @@
1
+ // 2.2.0 动作前回忆门(lane-C,默认 enforce)。
2
+ //
3
+ // 只在宿主 tools 服务的 guard 层工作:同步判定「这一次工具调用是不是高危动作命令」,
4
+ // 是则要求 gate-log 里存在同会话的动作类 procedure 卡回执;没有回执就返回拒绝串。
5
+ // 三条硬约束:
6
+ // 1. guard 必须是同步的(宿主 ToolGuard 类型不允许 Promise),且绝不能抛异常——
7
+ // 宿主 checkGuards 没有 try/catch,抛出去会把这一次工具调用变成工具错误。
8
+ // 2. 读 gate-log 只读尾部 64KB(mtime+size 缓存),读失败按「无回执」处理并 warn 一次;
9
+ // 写记录失败只 warn,不影响判定结果。
10
+ // 3. 宿主没有 ctx.tools.guard() 时不注册、不阻断、不伪造阻断;只有真实宿主
11
+ // (ctx.get 存在)才 warn 并往 gate-log 写一条 skip 留痕。
12
+ //
13
+ // 配置走 raw passthrough(settings schema 节点锁不变):{ enabled, mode },
14
+ // mode = enforce(默认,拒绝)/ shadow(只记不拦)/ off(不注册)。
15
+ // 归一化在 normalizeActionGateConfig,接线见 src/features.js。
16
+
17
+ import { closeSync, openSync, readSync, statSync } from 'node:fs';
18
+
19
+ import { appendGateLog, gateLogPaths } from '../recall/gate-log.mjs';
20
+
21
+ /** 默认配置:默认开启、默认强制。 */
22
+ export const ACTION_GATE_DEFAULTS = Object.freeze({ enabled: true, mode: 'enforce' });
23
+
24
+ const ACTION_GATE_MODES = Object.freeze(['enforce', 'shadow']);
25
+
26
+ /** 回执匹配词:动作类关键词(中文 + 英文,子串匹配、大小写不敏感)。 */
27
+ export const ACTION_KEYWORDS = Object.freeze([
28
+ '发布', '安装', '回滚', '删除',
29
+ 'publish', 'install', 'rollback', 'remove',
30
+ ]);
31
+
32
+ /** 动作类命令只在 shell 工具上判定;plugin_manager 单独按 action 参数判定。 */
33
+ export const SHELL_TOOL_NAMES = Object.freeze(['pwsh', 'bash', 'bash_local']);
34
+
35
+ const PLUGIN_MANAGER_TOOL = 'plugin_manager';
36
+
37
+ /** 回执尾部读取上限(字节)与无会话回执的时间窗(毫秒)。 */
38
+ const RECEIPT_TAIL_BYTES = 64 * 1024;
39
+ const RECEIPT_WINDOW_MS = 15 * 60 * 1000;
40
+
41
+ // 窄口径高危规则:只覆盖「发布 / 插件装卸 / 递归删除 / 回滚 / 硬重置」五类,
42
+ // 常规开发命令(npm install、npm test、git status 等)一律不命中。
43
+ const SHELL_RULES = Object.freeze([
44
+ { kind: 'publish', label: '发布', keywords: ['发布', 'publish'], re: /\b(?:npm|pnpm|yarn)\s+publish\b/i },
45
+ { kind: 'release', label: '发版', keywords: ['发布', 'publish'], re: /\bgh\s+release\b/i },
46
+ {
47
+ kind: 'plugin',
48
+ label: '插件装卸',
49
+ keywords: ['安装', 'install', 'remove'],
50
+ re: /\bplugin_manager\b[\s\S]{0,120}?\b(?:install|remove|add)\b/i,
51
+ },
52
+ {
53
+ kind: 'delete',
54
+ label: '递归删除',
55
+ keywords: ['删除', 'remove'],
56
+ re: /\bRemove-Item\b[\s\S]{0,240}?-Recurse\b/i,
57
+ },
58
+ {
59
+ kind: 'delete',
60
+ label: '递归删除',
61
+ keywords: ['删除', 'remove'],
62
+ re: /\brm\s+(?:-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\b/,
63
+ },
64
+ { kind: 'delete', label: '递归删除', keywords: ['删除', 'remove'], re: /\b(?:rd|rmdir)\s+\/s\b/i },
65
+ { kind: 'delete', label: '递归删除', keywords: ['删除', 'remove'], re: /\b(?:del|erase)\s+\/[a-z]*s[a-z]*\b/i },
66
+ { kind: 'rollback', label: '回滚', keywords: ['回滚', 'rollback'], re: /\brollback\b|回滚/i },
67
+ { kind: 'reset', label: '硬重置', keywords: ['回滚', 'reset'], re: /\bgit\s+reset\s+--hard\b/i },
68
+ ]);
69
+
70
+ /**
71
+ * 归一化 actionGate 配置。kill switch:DSH_LONGLIVE_DISABLE_ACTION_GATE=1 / true。
72
+ * - 显式 enabled:false 关闭;mode:'off' 也关闭(不注册)。
73
+ * - mode 非法值回落 'enforce'(默认强制)。
74
+ */
75
+ export function normalizeActionGateConfig(raw, env = process.env) {
76
+ const source = raw && typeof raw === 'object' ? raw : {};
77
+ const killed = Boolean(env) && (env.DSH_LONGLIVE_DISABLE_ACTION_GATE === '1' || env.DSH_LONGLIVE_DISABLE_ACTION_GATE === 'true');
78
+ const requestedOff = source.enabled === false || source.mode === 'off';
79
+ if (killed || requestedOff) return { enabled: false, mode: 'off' };
80
+ const mode = ACTION_GATE_MODES.includes(source.mode) ? source.mode : ACTION_GATE_DEFAULTS.mode;
81
+ return { enabled: true, mode };
82
+ }
83
+
84
+ /** 从工具参数里取出命令文本(只认 command / cmd 两个常见键)。 */
85
+ function commandTextOf(args) {
86
+ if (typeof args === 'string') return args;
87
+ if (!args || typeof args !== 'object') return '';
88
+ for (const key of ['command', 'cmd']) {
89
+ const value = args[key];
90
+ if (typeof value === 'string' && value.trim() !== '') return value;
91
+ }
92
+ return '';
93
+ }
94
+
95
+ /**
96
+ * 判定一次工具调用是否属于动作类高危命令。
97
+ * 返回 { action:false } 或 { action:true, kind, label, keywords }。
98
+ * 不执行命令、不读盘、无副作用。
99
+ */
100
+ export function classifyActionCall(toolName, args) {
101
+ const name = typeof toolName === 'string' ? toolName : '';
102
+ if (name === PLUGIN_MANAGER_TOOL) {
103
+ const action = args && typeof args === 'object' && typeof args.action === 'string' ? args.action : '';
104
+ if (/(?:install|remove|add)/i.test(action)) {
105
+ return { action: true, kind: 'plugin', label: '插件装卸', keywords: ['安装', 'install', 'remove'] };
106
+ }
107
+ return { action: false };
108
+ }
109
+ if (!SHELL_TOOL_NAMES.includes(name)) return { action: false };
110
+ const text = commandTextOf(args);
111
+ if (text === '') return { action: false };
112
+ for (const rule of SHELL_RULES) {
113
+ if (rule.re.test(text)) {
114
+ return { action: true, kind: rule.kind, label: rule.label, keywords: rule.keywords.slice() };
115
+ }
116
+ }
117
+ return { action: false };
118
+ }
119
+
120
+ /** 无回执时的拒绝串:给出下一步(先 memory_recall 取 procedure 卡)。 */
121
+ export function buildRefusal(verdict = {}) {
122
+ const label = typeof verdict.label === 'string' && verdict.label !== '' ? verdict.label : '高危';
123
+ const keyword = Array.isArray(verdict.keywords) && verdict.keywords.length > 0 ? verdict.keywords[0] : '回滚';
124
+ return `动作门拦截:该命令属于${label}类高危动作,执行前必须先回忆。下一步:先调用 memory_recall("${keyword}") `
125
+ + '取 procedure 卡(含步骤与失败模式),按卡执行后再重试本动作;若确认没有对应 procedure 卡,先向用户说明理由。';
126
+ }
127
+
128
+ /** 解析 execution 里的会话 id:宿主当前没有 sessionId 字段,用 agent.id(SessionId)。 */
129
+ export function resolveExecutionSessionId(execution) {
130
+ if (!execution || typeof execution !== 'object') return null;
131
+ if (typeof execution.sessionId === 'string' && execution.sessionId !== '') return execution.sessionId;
132
+ const agentId = execution.agent && typeof execution.agent === 'object' ? execution.agent.id : null;
133
+ return typeof agentId === 'string' && agentId !== '' ? agentId : null;
134
+ }
135
+
136
+ function parseRowTime(value) {
137
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
138
+ if (typeof value === 'string' && value !== '') {
139
+ const parsed = Date.parse(value);
140
+ return Number.isFinite(parsed) ? parsed : NaN;
141
+ }
142
+ return NaN;
143
+ }
144
+
145
+ function evidenceValue(evidence, key) {
146
+ const prefix = `${key}=`;
147
+ const found = [];
148
+ for (const item of evidence) {
149
+ if (typeof item !== 'string') continue;
150
+ const index = item.indexOf(prefix);
151
+ if (index !== 0 && index < 0) continue;
152
+ const start = index + prefix.length;
153
+ if (start <= 0) continue;
154
+ const value = item.slice(start);
155
+ if (value !== '') found.push(value);
156
+ }
157
+ return found.join(' ');
158
+ }
159
+
160
+ /** 单行判定:ok 行的 gate=action(显式回执)或 evidence 里 procedureNames/procedurePaths 命中关键词。 */
161
+ function rowIsActionReceipt(row, { sessionId, now, windowMs }) {
162
+ if (!row || typeof row !== 'object' || row.decision !== 'ok') return false;
163
+ const rowSessionId = typeof row.sessionId === 'string' && row.sessionId !== '' ? row.sessionId : null;
164
+ if (sessionId !== null) {
165
+ if (rowSessionId !== sessionId) return false;
166
+ } else {
167
+ const at = parseRowTime(row.at);
168
+ if (!Number.isFinite(at)) return false;
169
+ const delta = now - at;
170
+ if (delta > windowMs || delta < -windowMs) return false;
171
+ }
172
+ // lane-C 在 memory_recall 工具包装里写的显式动作回执行:本身就是回执。
173
+ if (row.gate === 'action') return true;
174
+ const evidence = Array.isArray(row.evidence) ? row.evidence : [];
175
+ const haystack = `${evidenceValue(evidence, 'procedureNames')} ${evidenceValue(evidence, 'procedurePaths')}`.toLowerCase();
176
+ if (haystack.trim() === '') return false;
177
+ return ACTION_KEYWORDS.some((keyword) => haystack.includes(keyword.toLowerCase()));
178
+ }
179
+
180
+ // gate-log 尾部行缓存:只按 logFile 的 mtime+size 失效,避免每个 shell 调用都读盘。
181
+ const tailCache = new Map();
182
+
183
+ /** 测试用:清空尾部行缓存(生产不需要调用)。 */
184
+ export function resetActionGateCache() {
185
+ tailCache.clear();
186
+ }
187
+
188
+ function readTailRows(memoryRoot) {
189
+ const { logFile } = gateLogPaths(memoryRoot);
190
+ let stat;
191
+ try {
192
+ stat = statSync(logFile);
193
+ } catch (error) {
194
+ if (error && error.code === 'ENOENT') return [];
195
+ throw error;
196
+ }
197
+ if (!stat.isFile()) {
198
+ const error = new Error('gate-log path is not a regular file');
199
+ error.code = 'E_GATE_LOG_NOT_FILE';
200
+ throw error;
201
+ }
202
+ const cached = tailCache.get(logFile);
203
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.rows;
204
+ const length = Math.min(stat.size, RECEIPT_TAIL_BYTES);
205
+ const start = Math.max(0, stat.size - length);
206
+ let buffer;
207
+ const fd = openSync(logFile, 'r');
208
+ try {
209
+ buffer = Buffer.alloc(length);
210
+ readSync(fd, buffer, 0, length, start);
211
+ } finally {
212
+ closeSync(fd);
213
+ }
214
+ let text = buffer.toString('utf8');
215
+ if (start > 0) {
216
+ // 尾部截断可能切在行中间:丢掉第一段残行。
217
+ const newline = text.indexOf('\n');
218
+ text = newline >= 0 ? text.slice(newline + 1) : '';
219
+ }
220
+ const rows = [];
221
+ for (const line of text.split('\n')) {
222
+ const trimmed = line.trim();
223
+ if (trimmed === '') continue;
224
+ try {
225
+ const row = JSON.parse(trimmed);
226
+ if (row && typeof row === 'object') rows.push(row);
227
+ } catch {
228
+ /* 坏行忽略:一条损坏记录不应让门失效 */
229
+ }
230
+ }
231
+ tailCache.set(logFile, { mtimeMs: stat.mtimeMs, size: stat.size, rows });
232
+ return rows;
233
+ }
234
+
235
+ /**
236
+ * 查回执:同会话(sessionId 有效时)或最近 15 分钟(无会话时)的 ok 行。
237
+ * 读失败按「无回执」返回 false,并只通过传入的 warn 报告一次(由调用方去重)。
238
+ */
239
+ export function hasActionReceipt({ memoryRoot, sessionId = null, now = Date.now(), windowMs = RECEIPT_WINDOW_MS, warn = null } = {}) {
240
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') return false;
241
+ let rows;
242
+ try {
243
+ rows = readTailRows(memoryRoot);
244
+ } catch (error) {
245
+ if (typeof warn === 'function') {
246
+ warn(`[longlive] action gate: gate-log 读取失败(${error?.code ?? error?.message ?? error})— 按无回执处理`);
247
+ }
248
+ return false;
249
+ }
250
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
251
+ if (rowIsActionReceipt(rows[index], { sessionId, now, windowMs })) return true;
252
+ }
253
+ return false;
254
+ }
255
+
256
+ function writeGateRowSafe(memoryRoot, entry, warn) {
257
+ try {
258
+ appendGateLog(memoryRoot, entry);
259
+ return true;
260
+ } catch (error) {
261
+ if (typeof warn === 'function') {
262
+ warn(`[longlive] action gate: gate-log 写入失败(${error?.code ?? error?.message ?? error})— 判定不受影响`);
263
+ }
264
+ return false;
265
+ }
266
+ }
267
+
268
+ function loggerOf(options) {
269
+ if (typeof options.warn === 'function') return options.warn;
270
+ const logger = options.logger;
271
+ if (logger && typeof logger.warn === 'function') return (message) => logger.warn(message);
272
+ return null;
273
+ }
274
+
275
+ /** 宿主是否像真实宿主:真实 Cordis ctx 有 ctx.get();单元测试的 fake ctx 一般没有。 */
276
+ function looksLikeHost(ctx) {
277
+ return Boolean(ctx) && (typeof ctx.get === 'function' || typeof ctx.tools?.execute === 'function');
278
+ }
279
+
280
+ /**
281
+ * 注册动作门(同步)。
282
+ * options: { config, memoryRoot, ownToolNames, warn|logger, env, now }
283
+ * 返回 { enabled, mode, registered, reason?, guard? }。
284
+ */
285
+ export function registerActionGate(ctx, options = {}) {
286
+ const normalized = normalizeActionGateConfig(options.config, options.env ?? process.env);
287
+ if (!normalized.enabled) return { enabled: false, mode: 'off', registered: false, reason: 'off' };
288
+ const mode = normalized.mode;
289
+ const warn = loggerOf(options);
290
+ const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot !== '' ? options.memoryRoot : null;
291
+ const ownToolNames = options.ownToolNames instanceof Set
292
+ ? options.ownToolNames
293
+ : (Array.isArray(options.ownToolNames) ? new Set(options.ownToolNames) : null);
294
+ const nowFn = typeof options.now === 'function' ? options.now : Date.now;
295
+ const service = ctx && ctx.tools;
296
+
297
+ if (!service || typeof service.guard !== 'function') {
298
+ // 降级:不阻断、不伪造。真实宿主缺 API 才 warn + gate-log 留痕。
299
+ if (looksLikeHost(ctx)) {
300
+ const message = '[longlive] action gate: 宿主未提供 ctx.tools.guard(),动作门无法注册(降级:不阻断,仅留痕)';
301
+ if (warn) warn(message);
302
+ else console.warn?.(message);
303
+ if (memoryRoot) {
304
+ writeGateRowSafe(memoryRoot, {
305
+ gate: 'action',
306
+ decision: 'skip',
307
+ reason: 'host-guard-absent',
308
+ evidence: [`mode=${mode}`],
309
+ }, null);
310
+ }
311
+ }
312
+ return { enabled: true, mode, registered: false, reason: 'no-host-guard' };
313
+ }
314
+ if (!memoryRoot) return { enabled: true, mode, registered: false, reason: 'no-memory-root' };
315
+
316
+ let warned = false;
317
+ const warnOnce = (message) => {
318
+ if (warned) return;
319
+ warned = true;
320
+ if (warn) warn(message);
321
+ else console.warn?.(message);
322
+ };
323
+
324
+ const guard = (execution) => {
325
+ try {
326
+ const name = typeof execution?.name === 'string' ? execution.name : '';
327
+ if (name === '') return undefined;
328
+ if (ownToolNames && ownToolNames.has(name)) return undefined;
329
+ const verdict = classifyActionCall(name, execution?.arguments);
330
+ if (!verdict.action) return undefined;
331
+ const sessionId = resolveExecutionSessionId(execution);
332
+ if (hasActionReceipt({ memoryRoot, sessionId, now: nowFn(), warn: warnOnce })) return undefined;
333
+ const evidence = [`tool=${name}`, `actionKind=${verdict.kind}`, `mode=${mode}`];
334
+ const decision = mode === 'shadow' ? 'warn' : 'fail';
335
+ writeGateRowSafe(memoryRoot, {
336
+ gate: 'action',
337
+ decision,
338
+ reason: mode === 'shadow' ? 'shadow' : 'no-receipt',
339
+ evidence,
340
+ }, warnOnce);
341
+ if (mode === 'shadow') return undefined;
342
+ return buildRefusal(verdict);
343
+ } catch (error) {
344
+ warnOnce(`[longlive] action gate: 判定异常(${error?.code ?? error?.message ?? error})— 已 fail-open 放行`);
345
+ return undefined;
346
+ }
347
+ };
348
+
349
+ try {
350
+ service.guard(guard);
351
+ } catch (error) {
352
+ warnOnce(`[longlive] action gate: 注册失败(${error?.code ?? error?.message ?? error})— 降级不阻断`);
353
+ return { enabled: true, mode, registered: false, reason: 'register-failed' };
354
+ }
355
+ return { enabled: true, mode, registered: true, guard };
356
+ }