-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.ts
More file actions
1645 lines (1417 loc) · 64.2 KB
/
Copy pathindex.ts
File metadata and controls
1645 lines (1417 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @sonicbotman/lobster-press — Cognitive Memory System for AI Agents
*
* DAG-based conversation summarization with Ebbinghaus forgetting curve,
* semantic notes, contradiction detection.
*
* Phase 1 IPC Refactor (Issue #115):
* - Ready handshake from Python
* - Request ID routing for concurrent requests
* - Clean failure on child process exit
*/
import { spawn, type ChildProcess } from "node:child_process";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { readFileSync, appendFileSync, writeFileSync, existsSync } from "node:fs";
import { Type } from "@sinclair/typebox";
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
// Minimal AgentMessage type matching OpenClaw SDK contract
type LobsterMessage = {
role: string;
content?: unknown;
};
// v4.0.19: 修复 __dirname 作用域问题(Issue #155 Bug #1)
// __dirname 必须在模块顶层定义,ensureMcpServer 需要使用它
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
let LOBSTERPRESS_VERSION = "unknown";
try {
const packageJson = JSON.parse(readFileSync(join(__dirname, "package.json"), "utf-8"));
LOBSTERPRESS_VERSION = packageJson.version ?? "unknown";
} catch {
// 打包环境下路径可能变化,降级为 unknown
}
// ─── IPC Types ───────────────────────────────────────────────────────────────
type McpEnvelope = {
type?: string;
requestId?: string;
status?: string;
result?: unknown;
error?: unknown;
[key: string]: unknown;
};
// ─── Global State ────────────────────────────────────────────────────────────
let mcpProcess: ChildProcess | null = null;
let mcpReady = false;
let bootPromise: Promise<ChildProcess> | null = null;
// v4.0.14: 移除全局 stdoutBuffer,改为闭包变量(Issue #152 Bug #2)
// let stdoutBuffer = ""; // ← 移除
// v4.0.17: 改为 per-session 锁,避免跨会话误阻塞(Issue #153 Bug #2)
const compressingSessions = new Set<string>();
const pendingRequests = new Map<
string,
{
resolve: (value: McpEnvelope) => void;
reject: (reason: Error) => void;
timer: NodeJS.Timeout;
}
>();
// ─── Process Lifecycle Cleanup (v5.0.0: OpenClaw v2026.4.2 compatibility) ────
// Clean up Python subprocess on SIGINT/SIGTERM to prevent orphaned processes
function cleanupMcpProcess(signal: string): void {
if (mcpProcess) {
try {
// Fail all pending requests before killing
for (const [, pending] of pendingRequests) {
clearTimeout(pending.timer);
pending.reject(new Error(`lobster-press MCP killed by ${signal}`));
}
pendingRequests.clear();
// Kill the Python subprocess
mcpProcess.kill("SIGTERM");
mcpProcess = null;
mcpReady = false;
bootPromise = null;
} catch {
// Ignore errors during cleanup
}
}
}
// Register cleanup handlers (v5.0.1: OpenClaw v2026.5.28 compat)
// DO NOT use removeAllListeners — that breaks other plugins and the host process.
// DO NOT call process.exit() — the host owns shutdown.
process.on("SIGINT", () => { cleanupMcpProcess("SIGINT"); });
process.on("SIGTERM", () => { cleanupMcpProcess("SIGTERM"); });
// ─── IPC Helpers ─────────────────────────────────────────────────────────────
function generateRequestId(): string {
return `lobster-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
// v4.0.17: 根据 LLM provider 获取 token 估算系数(Issue #153 Bug #5)
function getTokenEstimationCoefficients(provider?: string): { chinese: number; other: number } {
switch (provider?.toLowerCase()) {
case "deepseek":
case "zhipu":
case "glm":
case "wenxin":
case "qwen":
// 中文优化模型:中文字符约 1-1.2 tokens
return { chinese: 1.2, other: 4 };
case "claude":
case "anthropic":
// Claude: 中文字符约 2 tokens
return { chinese: 2.0, other: 4 };
case "gemini":
case "google":
// Gemini: 中文字符约 1-1.5 tokens
return { chinese: 1.5, other: 4 };
case "openai":
case "gpt":
case "mistral":
default:
// GPT/默认: 中文字符约 1.5 tokens
return { chinese: 1.5, other: 4 };
}
}
function handleStdoutLine(line: string): void {
let msg: McpEnvelope;
try {
msg = JSON.parse(line);
} catch {
return;
}
// Ready handshake from Python
if (msg.type === "lobster-press/ready") {
mcpReady = true;
return;
}
// Route response by requestId
const requestId = msg.requestId;
if (!requestId) return;
const pending = pendingRequests.get(requestId);
if (!pending) return;
clearTimeout(pending.timer);
pendingRequests.delete(requestId);
if (msg.status === "error") {
pending.reject(
new Error(typeof msg.error === "string" ? msg.error : JSON.stringify(msg.error))
);
} else {
pending.resolve(msg);
}
}
function attachStdoutDispatcher(proc: ChildProcess): void {
if (!proc.stdout) return;
if ((proc.stdout as { __lobsterDispatcherAttached?: boolean }).__lobsterDispatcherAttached) return;
(proc.stdout as { __lobsterDispatcherAttached?: boolean }).__lobsterDispatcherAttached = true;
// v4.0.14: 改为闭包变量,避免多进程/多会话数据串流(Issue #152 Bug #2)
let localBuffer = "";
proc.stdout.on("data", (chunk: Buffer) => {
localBuffer += chunk.toString("utf8");
const lines = localBuffer.split("\n");
localBuffer = lines.pop() ?? "";
for (const raw of lines) {
const line = raw.trim();
if (!line) continue;
handleStdoutLine(line);
}
});
proc.on("exit", (code) => {
mcpProcess = null;
mcpReady = false;
bootPromise = null;
// Fail all pending requests
for (const [, pending] of pendingRequests) {
clearTimeout(pending.timer);
pending.reject(new Error(`lobster-press MCP exited: code=${code ?? "unknown"}`));
}
pendingRequests.clear();
});
}
async function ensureMcpServer(config: Record<string, unknown>): Promise<ChildProcess> {
if (mcpProcess && mcpReady) return mcpProcess;
if (bootPromise) return bootPromise;
bootPromise = new Promise((resolve, reject) => {
const dbPath =
(config.dbPath as string) ||
join(process.env.HOME ?? "~", ".openclaw/lobster.db");
const pythonCmd = process.env.LOBSTER_PYTHON ?? "python3";
const proc = spawn(
pythonCmd,
[
"-m",
"mcp_server.lobster_mcp_server",
"--db",
dbPath,
"--provider",
(config.llmProvider as string) || "",
"--model",
(config.llmModel as string) || "",
"--namespace", // v3.6.0 新增(Issue #127 模块四)
(config.namespace as string) || "default",
],
{
cwd: join(__dirname, ".."), // v4.0.53: 修复 cwd 路径错误 - dist/index.js 的 __dirname 指向 dist/,需要回到包根目录
env: {
...process.env,
LOBSTER_LLM_API_KEY:
(config.llmApiKey as string) ||
process.env.LOBSTER_LLM_API_KEY ||
"",
},
stdio: ["pipe", "pipe", "inherit"],
}
);
mcpProcess = proc;
mcpReady = false;
attachStdoutDispatcher(proc);
const startedAt = Date.now();
const poll = setInterval(() => {
if (mcpReady) {
clearInterval(poll);
resolve(proc);
} else if (Date.now() - startedAt > 10_000) {
clearInterval(poll);
bootPromise = null;
reject(new Error("lobster-press MCP did not become ready within 10s"));
}
}, 50);
proc.once("error", (err) => {
clearInterval(poll);
bootPromise = null;
reject(err);
});
proc.once("exit", (code) => {
if (!mcpReady) {
clearInterval(poll);
bootPromise = null;
reject(new Error(`lobster-press MCP exited before ready: code=${code ?? "unknown"}`));
}
});
});
try {
return await bootPromise;
} finally {
// v4.0.26: 修复竞态条件,只有当前进程成功启动才清除(Issue #167 Bug #1)
// 避免并发请求时启动多个 Python 子进程
if (mcpProcess && mcpReady) {
bootPromise = null;
}
}
}
async function callMcp(
config: Record<string, unknown>,
toolName: string,
args: Record<string, unknown>
): Promise<{ content: Array<{ type: "text"; text: string }>; details: unknown }> {
const proc = await ensureMcpServer(config);
const requestId = generateRequestId();
const response = await new Promise<McpEnvelope>((resolve, reject) => {
const timer = setTimeout(() => {
pendingRequests.delete(requestId);
reject(new Error(`lobster-press MCP tool call timed out after 30s: ${toolName}`));
}, 30_000);
pendingRequests.set(requestId, { resolve, reject, timer });
const request =
JSON.stringify({
method: "tools/call",
requestId,
params: { name: toolName, arguments: args },
}) + "\n";
proc.stdin?.write(request);
});
return {
content: [
{
type: "text",
text: JSON.stringify(response.result ?? response, null, 2),
},
],
details: response,
};
}
// ─── Tool Schemas ─────────────────────────────────────────────────────────────
const LobsterGrepSchema = Type.Object({
query: Type.String({ description: "搜索关键词或短语" }),
conversation_id: Type.Optional(Type.String({ description: "限定搜索范围的会话 ID" })),
limit: Type.Optional(Type.Number({ description: "最多返回条数,默认 5", default: 5 })),
});
const LobsterDescribeSchema = Type.Object({
conversation_id: Type.Optional(Type.String({ description: "会话 ID(留空查全局)" })),
});
const LobsterExpandSchema = Type.Object({
summary_id: Type.String({ description: "要展开的摘要节点 ID" }),
max_depth: Type.Optional(Type.Number({ description: "最大展开层数,默认 2", default: 2 })),
});
// v4.0.6: 手动上下文检查工具(Issue #141 降级方案)
const LobsterCheckContextSchema = Type.Object({
conversation_id: Type.Optional(Type.String({ description: "会话 ID" })),
force_compress: Type.Optional(Type.Boolean({ description: "是否强制压缩", default: false })),
});
// ─── Plugin Definition ────────────────────────────────────────────────────────
const lobsterPlugin = {
id: "lobster-press",
name: "LobsterPress Memory Engine",
description:
"Cognitive memory system for AI Agents: DAG compression, Ebbinghaus forgetting curve, semantic notes, contradiction detection",
configSchema: {
parse(value: unknown) {
const raw =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
// v4.0.17: 添加字段校验(Issue #153 Bug #6)
const validated: Record<string, unknown> = {};
// dbPath: 必须是字符串
if (typeof raw.dbPath === "string") {
validated.dbPath = raw.dbPath;
}
// contextThreshold: 必须是数字,且在 0-1 之间
if (typeof raw.contextThreshold === "number" &&
raw.contextThreshold >= 0 && raw.contextThreshold <= 1) {
validated.contextThreshold = raw.contextThreshold;
} else if (typeof raw.contextThreshold === "string") {
// 尝试解析字符串
const parsed = parseFloat(raw.contextThreshold);
if (!isNaN(parsed) && parsed >= 0 && parsed <= 1) {
validated.contextThreshold = parsed;
}
}
// llmProvider: 必须是字符串
if (typeof raw.llmProvider === "string") {
validated.llmProvider = raw.llmProvider;
}
// llmModel: 必须是字符串
if (typeof raw.llmModel === "string") {
validated.llmModel = raw.llmModel;
}
// llmApiKey: 必须是字符串
if (typeof raw.llmApiKey === "string") {
validated.llmApiKey = raw.llmApiKey;
}
// namespace: 必须是字符串
if (typeof raw.namespace === "string") {
validated.namespace = raw.namespace;
}
// freshTailCount: 必须是正整数
if (typeof raw.freshTailCount === "number" &&
Number.isInteger(raw.freshTailCount) && raw.freshTailCount > 0) {
validated.freshTailCount = raw.freshTailCount;
}
// maxContextTokens: 必须是正整数(v4.0.20: Issue #156 Bug #3)
// v4.0.27: 添加默认值 40000(Issue #166 P1-1)
if (typeof raw.maxContextTokens === "number" &&
Number.isInteger(raw.maxContextTokens) && raw.maxContextTokens > 0) {
validated.maxContextTokens = raw.maxContextTokens;
} else if (typeof raw.maxContextTokens === "string") {
const parsed = parseInt(raw.maxContextTokens, 10);
if (!isNaN(parsed) && parsed > 0) {
validated.maxContextTokens = parsed;
}
} else {
// 用户未设置时使用默认值
validated.maxContextTokens = 40000;
}
// registerAsDefault: 必须是布尔值(v4.0.17: Issue #153 Bug #4)
if (typeof raw.registerAsDefault === "boolean") {
validated.registerAsDefault = raw.registerAsDefault;
}
// Only pass through keys that were NOT processed above
// (excludes keys that failed validation, like out-of-range numbers)
const processedKeys = new Set([
'dbPath', 'contextThreshold', 'llmProvider', 'llmModel',
'llmApiKey', 'namespace', 'freshTailCount', 'maxContextTokens', 'registerAsDefault',
]);
for (const key of Object.keys(raw)) {
if (!processedKeys.has(key)) {
validated[key] = raw[key];
}
}
return validated;
},
},
register(api: OpenClawPluginApi) {
const pluginConfig =
api.pluginConfig && typeof api.pluginConfig === "object"
? (api.pluginConfig as Record<string, unknown>)
: {};
// v4.0.48: Debug logging - write to file to bypass all loggers (ESM compatible)
const debugLog = (msg: string) => {
if (process.env.LOBSTER_DEBUG !== "1") return;
const logLine = `[${new Date().toISOString()}] [lobster-press] DEBUG: ${msg}\n`;
try { appendFileSync('/tmp/lobster-debug.log', logLine); } catch {}
};
debugLog('register() called');
debugLog(`pluginConfig=${JSON.stringify({
dbPath: pluginConfig.dbPath,
llmProvider: pluginConfig.llmProvider,
lifecycleEnabled: pluginConfig.lifecycleEnabled,
contextThreshold: pluginConfig.contextThreshold,
maxContextTokens: pluginConfig.maxContextTokens,
})}`);
debugLog(`api object methods: ${Object.keys(api).join(', ')}`);
// ── lobster_grep ───────────────────────────────────────────────────────
api.registerTool({
name: "lobster_grep",
label: "Lobster Grep",
description:
"在 LobsterPress 记忆库中全文搜索历史对话(FTS5 + TF-IDF 重排序)。" +
"当你需要回忆某个决策、技术细节或历史错误时调用此工具。",
parameters: LobsterGrepSchema,
execute: async (_toolCallId: string, params: Record<string, unknown>) => {
return callMcp(pluginConfig, "lobster_grep", params);
},
});
// ── lobster_describe ────────────────────────────────────────────────────
api.registerTool({
name: "lobster_describe",
label: "Lobster Describe",
description:
"查看 LobsterPress 的 DAG 摘要层级结构:共有多少层摘要、多少条原始消息已被压缩。",
parameters: LobsterDescribeSchema,
execute: async (_toolCallId: string, params: Record<string, unknown>) => {
return callMcp(pluginConfig, "lobster_describe", params);
},
});
// ── lobster_expand ──────────────────────────────────────────────────────
api.registerTool({
name: "lobster_expand",
label: "Lobster Expand",
description:
"将 DAG 摘要节点展开,还原其对应的原始消息(无损检索)。" +
"当摘要不够详细、需要原始对话时调用。",
parameters: LobsterExpandSchema,
execute: async (_toolCallId: string, params: Record<string, unknown>) => {
return callMcp(pluginConfig, "lobster_expand", params);
},
});
// ── lobster_check_context (v4.0.6) ───────────────────────────────────────
// Issue #141 降级方案:手动检查上下文并触发压缩
api.registerTool({
name: "lobster_check_context",
label: "Lobster Check Context",
description:
"手动检查上下文使用率并触发压缩(降级方案)。" +
"当 OpenClaw Gateway 不支持 ContextEngine.afterTurn 钩子时使用。" +
"建议每隔几轮对话调用一次。",
parameters: LobsterCheckContextSchema,
execute: async (_toolCallId: string, params: Record<string, unknown>) => {
// 获取当前上下文状态
const describeResult = await callMcp(pluginConfig, "lobster_describe", {
conversation_id: params.conversation_id,
});
// v4.0.18: 修复解析路径(Issue #154 Bug #3)
const text = describeResult.content?.[0]?.text;
const stats = text ? JSON.parse(text) : {};
const messageCount = stats?.message_count ?? 0;
const summaryCount = stats?.summary_count ?? 0;
// 如果消息数太少,不需要压缩
if (messageCount < 10) {
return {
content: [
{
type: "text",
text: `📊 上下文检查:${messageCount} 条消息,无需压缩(< 10 条)`,
},
],
details: { message_count: messageCount, action: "none" },
};
}
// 如果强制压缩或消息数较多,触发压缩
if (params.force_compress || messageCount > 50) {
api.logger.info(`[lobster-press] Manual context check: ${messageCount} messages, triggering compress`);
const compressResult = await callMcp(pluginConfig, "lobster_compress", {
conversation_id: params.conversation_id,
force: true,
});
// v4.0.22: 提取实际压缩结果,不透传 McpEnvelope 内部字段(Issue #158 Bug #1)
const compressText = compressResult.content?.[0]?.text;
const compressData = compressText ? JSON.parse(compressText) : {};
return {
content: [
{
type: "text",
text: `✅ 上下文检查:${messageCount} 条消息,已触发压缩\n\n${JSON.stringify(compressData, null, 2)}`,
},
],
details: { message_count: messageCount, action: "compressed", compress_result: compressData },
};
}
// 否则只返回状态
return {
content: [
{
type: "text",
text: `📊 上下文检查:${messageCount} 条消息,${summaryCount} 条摘要\n\n` +
`建议:当消息数超过 50 条时,可设置 force_compress=true 触发压缩`,
},
],
details: { message_count: messageCount, summary_count: summaryCount, action: "none" },
};
},
});
// ── lobster_configure (v4.0.91) ───────────────────────────────────────────
// 交互式配置向导,帮助用户配置 LobsterPress
api.registerTool({
name: "lobster_configure",
label: "Lobster Configure",
description:
"LobsterPress 配置向导。首次使用时,帮助用户配置 LLM Provider、API Key、自动功能等。" +
"如果用户询问如何配置 LobsterPress,或者首次使用时,调用此工具。",
parameters: Type.Object({
step: Type.Optional(Type.String({
description: "配置步骤:welcome/llm_choice/provider/apikey/features/complete,默认 welcome"
})),
llm_enabled: Type.Optional(Type.Boolean({
description: "是否启用 LLM 摘要生成(用户选择)"
})),
provider: Type.Optional(Type.String({
description: "LLM Provider:openai/anthropic/zhipu/deepseek/custom"
})),
api_key: Type.Optional(Type.String({
description: "LLM API Key"
})),
model: Type.Optional(Type.String({
description: "LLM Model 名称(可选)"
})),
}),
execute: async (_toolCallId: string, params: Record<string, unknown>) => {
const step = (params.step as string) || "welcome";
// 步骤 1:欢迎和 LLM 选择
if (step === "welcome") {
return {
content: [
{
type: "text",
text: `🦞 **LobsterPress v${LOBSTERPRESS_VERSION} 配置向导**
欢迎!LobsterPress 是一个认知记忆系统,可以帮助 AI 记住对话历史。
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 **配置选项 1/4:LLM 摘要生成**
LobsterPress 可以使用 LLM 生成高质量摘要,也可以使用 TF-IDF 提取式摘要。
✅ **使用 LLM 摘要(推荐)**
- 更准确的摘要质量
- 需要配置 LLM API Key
- 支持 OpenAI/Anthropic/智谱/DeepSeek 等
⚠️ **使用 TF-IDF 摘要(默认)**
- 无需 API Key
- 基于关键词提取
- 质量略低但免费
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**请询问用户**:是否使用 LLM 生成摘要?
**下一步**:设置 \`step="llm_choice"\` 和 \`llm_enabled=true/false\``,
},
],
details: { step: "welcome" },
};
}
// 步骤 2:LLM Provider 选择
if (step === "llm_choice" && params.llm_enabled === true) {
return {
content: [
{
type: "text",
text: `📋 **配置选项 2/4:LLM Provider**
请选择 LLM Provider:
1. **openai**(OpenAI GPT-4/GPT-3.5)
2. **anthropic**(Claude 3)
3. **zhipu**(智谱 GLM-4)
4. **deepseek**(DeepSeek)
5. **custom**(其他/自定义)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**请询问用户**:选择哪个 Provider?
**下一步**:设置 \`step="provider"\` 和 \`provider="选择的provider"\``,
},
],
details: { step: "llm_choice", llm_enabled: true },
};
}
// 步骤 3:API Key 配置
if (step === "provider" && params.provider) {
const providerName = {
openai: "OpenAI",
anthropic: "Anthropic",
zhipu: "智谱",
deepseek: "DeepSeek",
custom: "自定义",
}[params.provider as string] || params.provider;
return {
content: [
{
type: "text",
text: `📋 **配置选项 3/4:API Key**
**Provider**: ${providerName}
请输入您的 ${providerName} API Key。
⚠️ **安全提示**:
- API Key 将保存到配置文件 \`~/.openclaw/openclaw.json\`
- 请确保配置文件权限安全(仅当前用户可读)
- 不要在公开场合分享 API Key
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**请询问用户**:输入 API Key
**下一步**:设置 \`step="apikey"\` 和 \`api_key="您的API Key"\``,
},
],
details: { step: "provider", provider: params.provider },
};
}
// 步骤 4:功能确认
if (step === "apikey" || (step === "llm_choice" && params.llm_enabled === false)) {
const llmStatus = params.llm_enabled === false ? "⚠️ 禁用(使用 TF-IDF)" : "✅ 启用";
return {
content: [
{
type: "text",
text: `📋 **配置选项 4/4:自动功能确认**
**LLM 摘要**: ${llmStatus}
以下功能将自动启用:
✅ C-HLR+ 自适应遗忘曲线(每轮对话后自动标记衰减)
✅ Focus 主动压缩触发(定时 + 紧急 + 被动三策略)
✅ 记忆注入(按优先级:semantic > episodic > working)
以下功能需要手动触发:
⚠️ 三层压缩(可通过 \`lobster_compress\` 手动触发)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**配置参数**:
- 上下文阈值:80%(超过时触发压缩)
- 压缩间隔:12 轮(定时触发)
- 记忆保留:7 天(衰减后自动清理)
**请询问用户**:是否确认配置?
**下一步**:设置 \`step="complete"\``,
},
],
details: { step: "features", llm_enabled: params.llm_enabled },
};
}
// 步骤 5:完成
if (step === "complete") {
// v4.0.92: 配置保存验证 + API Key 测试 + 回滚机制
const configPath = join(process.env.HOME || "~", ".openclaw/openclaw.json");
try {
// 1. 读取旧配置(备份)
let oldConfig: any = {};
let configExists = false;
if (existsSync(configPath)) {
try {
const configContent = readFileSync(configPath, "utf-8");
oldConfig = JSON.parse(configContent);
configExists = true;
debugLog(`configure: backed up existing config`);
} catch (readErr) {
debugLog(`configure: failed to read existing config: ${readErr}`);
}
}
// 2. 构建新配置对象
const newConfig: Record<string, unknown> = {
lifecycleEnabled: true,
contextThreshold: 0.8,
maxContextTokens: 40000,
};
// 如果用户选择使用 LLM
if (params.llm_enabled === true && params.provider) {
newConfig.llmProvider = params.provider;
if (params.api_key) {
newConfig.llmApiKey = params.api_key;
}
if (params.model) {
newConfig.llmModel = params.model;
}
}
// 3. 保存新配置
const fullConfig = {
plugins: {
entries: {
"lobster-press": {
enabled: true,
config: newConfig,
},
},
},
};
// 合并旧配置(保留其他插件的配置)
if (configExists && oldConfig.plugins?.entries) {
fullConfig.plugins.entries = {
...oldConfig.plugins.entries,
"lobster-press": {
enabled: true,
config: newConfig,
},
};
}
// 写入配置文件
writeFileSync(configPath, JSON.stringify(fullConfig, null, 2), "utf-8");
debugLog(`configure: config saved to ${configPath}`);
// 4. 验证配置是否成功保存
let verifySuccess = false;
try {
const verifyContent = readFileSync(configPath, "utf-8");
const verifyConfig = JSON.parse(verifyContent);
verifySuccess = verifyConfig.plugins?.entries?.["lobster-press"]?.config?.lifecycleEnabled === true;
debugLog(`configure: verification ${verifySuccess ? "passed" : "failed"}`);
} catch (verifyErr) {
debugLog(`configure: verification failed: ${verifyErr}`);
}
if (!verifySuccess) {
// 验证失败,恢复旧配置
if (configExists) {
writeFileSync(configPath, JSON.stringify(oldConfig, null, 2), "utf-8");
debugLog(`configure: rolled back to old config`);
}
return {
content: [
{
type: "text",
text: `❌ **配置保存失败!**
配置文件验证失败,已回滚到旧配置。
**错误原因**:配置文件写入后验证失败
**建议操作**:
1. 检查配置文件权限:\`~/.openclaw/openclaw.json\`
2. 确保目录存在:\`mkdir -p ~/.openclaw\`
3. 重新运行配置向导
**如需帮助**:请查看日志文件或联系支持`,
},
],
details: { configured: false, error: "verification_failed" },
};
}
// 5. API Key 测试(如果提供了 API Key)
let apiKeyTestResult = "skipped";
if (params.llm_enabled === true && params.api_key && params.provider) {
debugLog(`configure: testing API key for provider ${params.provider}`);
// 简单的 API Key 格式验证
const apiKey = params.api_key as string;
const provider = params.provider as string;
// 基本格式检查
if (provider === "openai" && !apiKey.startsWith("sk-")) {
apiKeyTestResult = "invalid_format";
} else if (provider === "anthropic" && !apiKey.startsWith("sk-ant-")) {
apiKeyTestResult = "invalid_format";
} else if (provider === "zhipu" && apiKey.length < 20) {
apiKeyTestResult = "too_short";
} else if (provider === "deepseek" && !apiKey.startsWith("sk-")) {
apiKeyTestResult = "invalid_format";
} else {
// 格式正确,标记为待测试
apiKeyTestResult = "format_ok";
debugLog(`configure: API key format check passed`);
// TODO: 实际 API 调用测试(可选,需要网络请求)
// 为了安全起见,不在配置阶段进行实际 API 调用
// 用户可以在实际使用时验证
}
}
// 6. 返回成功结果
const apiKeyStatus = {
skipped: "⚠️ 未提供(使用 TF-IDF)",
format_ok: "✅ 格式正确(实际使用时验证)",
invalid_format: "❌ 格式错误(请检查)",
too_short: "❌ 长度不足(请检查)",
}[apiKeyTestResult] || "❓ 未知状态";
return {
content: [
{
type: "text",
text: `✅ **配置完成!**
**配置文件**:\`${configPath}\`
**验证状态**:✅ 已验证
**API Key 状态**:${apiKeyStatus}
\`\`\`json
${JSON.stringify(fullConfig, null, 2)}
\`\`\`
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📚 **快速开始**:
1. **正常与 AI 对话** - LobsterPress 会自动记住对话历史
2. **下次对话时** - AI 会回忆起之前的上下文
3. **搜索历史** - 使用 \`lobster_grep "关键词"\` 搜索记忆
🛠️ **可用工具**:
- \`lobster_grep\` - 搜索历史记忆
- \`lobster_describe\` - 查看记忆结构
- \`lobster_configure\` - 重新配置(本工具)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎉 **开始使用吧!**
**提示**:
- 配置已保存并验证
- ${apiKeyTestResult === "format_ok" ? "API Key 格式正确,将在首次使用时验证" : "如需修改配置,请重新运行本工具"}
- 备份配置已保存(如需回滚)`,
},
],
details: {
configured: true,
config: newConfig,
configPath,
verified: verifySuccess,
apiKeyTest: apiKeyTestResult,
},
};
} catch (error) {
debugLog(`configure: error during save: ${error}`);
return {
content: [
{
type: "text",
text: `❌ **配置保存失败!**
**错误信息**:${error}
**建议操作**:
1. 检查配置文件权限:\`~/.openclaw/openclaw.json\`
2. 确保目录存在:\`mkdir -p ~/.openclaw\`
3. 检查磁盘空间
4. 重新运行配置向导
**如需帮助**:请查看日志文件或联系支持`,
},
],
details: { configured: false, error: String(error) },
};
}
}
// 未知步骤
return {
content: [
{
type: "text",
text: `❌ 未知的配置步骤:${step}\n\n请使用以下步骤之一:welcome/llm_choice/provider/apikey/features/complete`,
},
],
details: { step, error: "unknown_step" },
};
},
});
// ── ContextEngine Registration (v3.3.0) ────────────────────────────────────
// 参考 lossless-claw 的实现,注册为 ContextEngine,实现自动压缩
// v4.0.7: 必须同时注册 "default",阻止 OpenClaw 内置压缩抢先运行(Issue #141 评论)
const lobsterEngine = {
info: {
id: "lobster-press",
name: "LobsterPress Memory Engine",
version: LOBSTERPRESS_VERSION, // v4.0.17: 从 package.json 读取(Issue #153 Bug #3)
ownsCompaction: true,
},
// 关键:每次 turn 后自动检查上下文使用率
// v4.0.0: Focus 主动压缩触发(定时 + 紧急 + 被动三策略)
// v4.0.23: 异常处理策略文档化(Issue #160 建议 #2)
// v4.0.30: 三种策略均捕获异常,不中断对话(Issue #169)
//
// ── 异常处理设计决策 ──
// 三种策略均捕获异常并记录日志,不向上冒泡:
// 压缩失败不应中断用户对话,由日志监控告警。
async afterTurn(params: {
sessionId: string;
sessionKey?: string;
sessionFile?: string;
messages?: any[];
prePromptMessageCount?: number;
tokenBudget?: number;
runtimeContext?: Record<string, unknown>;
isHeartbeat?: boolean;
}) {
// v4.0.6: 调试日志 - 确认 afterTurn 被调用(Issue #141 诊断)
api.logger.info(`[lobster-press] afterTurn called (sessionId=${params?.sessionId ?? "unknown"})`);
// v4.0.0: Focus 主动压缩触发常量
const FOCUS_COMPRESSION_INTERVAL = 12; // 论文建议 10-15,取 12
const FOCUS_URGENT_THRESHOLD = 0.85; // 上下文使用率超过 85% 时立即触发
// v4.0.14: 删除无用的 _getDb() 调用(Issue #152 Bug #5)
const threshold = (pluginConfig.contextThreshold as number) ?? 0.8;
// v4.0.26: 优先读取 pluginConfig.maxContextTokens(Issue #167 Bug #2)
const tokenBudget = (pluginConfig.maxContextTokens as number) ?? params.tokenBudget ?? 40000;
// v4.0.0: 获取轮次数