openclaw-lark-multi-agent 1.8.4 → 1.8.6

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,152 @@
1
+ /**
2
+ * lma-core :: toolTrim compaction (Phase 2)
3
+ * ------------------------------------------
4
+ * User spec (2026-10-10):
5
+ * - keep the most recent 10 tool calls visible (with results)
6
+ * - everything older: keep text, drop tool payload
7
+ * - manual trigger only (/compact tooltrim); auto-compaction keeps the
8
+ * built-in LLM summarizer
9
+ * - no per-tool whitelist
10
+ *
11
+ * Implementation: a registered CompactionProvider whose summarize() does NOT
12
+ * call an LLM — it filters/serializes the batch into structured text. The
13
+ * gateway handles all storage mechanics (checkpoints, successor transcript).
14
+ *
15
+ * Orchestration: the `lma.core.compact.tooltrim` gateway method performs the
16
+ * provider config toggle -> sessions.compact -> restore dance so the bridge
17
+ * calls exactly one method.
18
+ */
19
+ const TOOLTRIM_PROVIDER_ID = "lma-tooltrim";
20
+ const CONFIG_PATH = "agents.defaults.compaction.provider";
21
+ /** Truncation for a KEPT tool result body (they can be enormous). */
22
+ const KEPT_RESULT_MAX = 2000;
23
+ /** Truncation for a kept text message (rarely needed; texts are small). */
24
+ const TEXT_MAX = 8000;
25
+ function clamp(text, max) {
26
+ return text.length <= max ? text : `${text.slice(0, max)}…[截断,原 ${text.length} 字符]`;
27
+ }
28
+ /** Extract visible text from an unknown message content shape. */
29
+ function messageText(content) {
30
+ if (typeof content === "string")
31
+ return content;
32
+ if (!Array.isArray(content))
33
+ return "";
34
+ return content
35
+ .filter((p) => p && typeof p === "object" && p.type === "text" && typeof p.text === "string")
36
+ .map((p) => p.text)
37
+ .join("\n");
38
+ }
39
+ /** Collect tool-call descriptors (name + id) in order of appearance. */
40
+ function toolCallsOf(content) {
41
+ if (!Array.isArray(content))
42
+ return [];
43
+ return content
44
+ .filter((p) => p && typeof p === "object" && (p.type === "toolCall" || p.type === "tool_use"))
45
+ .map((p) => ({ toolName: String(p.name ?? p.toolName ?? "tool") }));
46
+ }
47
+ function isToolResultMessage(msg) {
48
+ if (msg?.role === "toolResult" || msg?.role === "tool")
49
+ return true;
50
+ return Array.isArray(msg?.content) && msg.content.some((p) => p?.type === "toolResult" || p?.type === "tool_result");
51
+ }
52
+ function toolResultText(msg) {
53
+ if (typeof msg?.content === "string")
54
+ return msg.content;
55
+ if (!Array.isArray(msg?.content))
56
+ return "";
57
+ return msg.content
58
+ .filter((p) => p && (p.type === "toolResult" || p.type === "tool_result"))
59
+ .map((p) => typeof p.content === "string" ? p.content : messageText(p.content ?? p))
60
+ .join("\n");
61
+ }
62
+ export function toolTrimProvider() {
63
+ return {
64
+ id: TOOLTRIM_PROVIDER_ID,
65
+ label: "LMA ToolTrim (keep text; keep only the 10 most recent tool calls)",
66
+ async summarize(params) {
67
+ const messages = Array.isArray(params.messages) ? params.messages : [];
68
+ // Pass 1: count tool calls to decide which ones are in the "last 10" set.
69
+ // Tool calls appear as parts on assistant messages; their results as
70
+ // standalone toolResult messages right after. We count tool-call
71
+ // occurrences from the END.
72
+ let totalToolCalls = 0;
73
+ for (const m of messages) {
74
+ totalToolCalls += toolCallsOf(m?.content).length;
75
+ }
76
+ const firstKeptIndex = Math.max(1, totalToolCalls - 10 + 1); // 1-based ordinal of first kept call
77
+ let ordinal = 0;
78
+ const lines = [];
79
+ if (params.previousSummary) {
80
+ lines.push("【先前压缩摘要】");
81
+ lines.push(clamp(params.previousSummary, TEXT_MAX));
82
+ lines.push("");
83
+ }
84
+ lines.push("【ToolTrim 压缩记录】以下为历史对话的结构化保留:文本消息完整保留;工具调用仅保留最近 10 条(含结果),更早的工具调用仅保留名称标记。");
85
+ lines.push("");
86
+ for (const m of messages) {
87
+ const role = String(m?.role ?? "");
88
+ const content = m?.content;
89
+ if (isToolResultMessage(m)) {
90
+ ordinal += 1;
91
+ if (ordinal >= firstKeptIndex) {
92
+ lines.push(`[工具结果 #${ordinal}] ${clamp(toolResultText(m), KEPT_RESULT_MAX)}`);
93
+ }
94
+ else {
95
+ lines.push(`[工具结果 #${ordinal} 已过滤]`);
96
+ }
97
+ continue;
98
+ }
99
+ const calls = toolCallsOf(content);
100
+ const text = messageText(content).trim();
101
+ if (calls.length > 0) {
102
+ for (const c of calls) {
103
+ ordinal += 1;
104
+ lines.push(ordinal >= firstKeptIndex
105
+ ? `[工具调用 #${ordinal} 保留] ${c.toolName}`
106
+ : `[工具调用 #${ordinal} 已过滤] ${c.toolName}`);
107
+ }
108
+ if (text)
109
+ lines.push(`${role === "assistant" ? "助手" : role || "消息"}: ${clamp(text, TEXT_MAX)}`);
110
+ continue;
111
+ }
112
+ if (text) {
113
+ const who = role === "user" ? "用户" : role === "assistant" ? "助手" : role || "消息";
114
+ lines.push(`${who}: ${clamp(text, TEXT_MAX)}`);
115
+ }
116
+ }
117
+ return lines.join("\n");
118
+ },
119
+ };
120
+ }
121
+ /**
122
+ * Orchestration note: plugins cannot call gateway RPCs (trusted-only), so
123
+ * the BRIDGE performs the validated toggle dance (config.set {raw, baseHash}
124
+ * -> sessions.compact -> restore). This method only reports provider status.
125
+ */
126
+ export function registerToolTrim(api) {
127
+ if (typeof api?.registerCompactionProvider !== "function") {
128
+ // Older gateways (e.g. 2026.9.6) may lack this API — degrade gracefully so
129
+ // steer/go modules of this plugin still register and run.
130
+ console.warn(`[lma-core] tooltrim: registerCompactionProvider unavailable on this gateway — provider not registered (steer/go unaffected)`);
131
+ api.registerGatewayMethod("lma.core.compact.tooltrim", ({ respond }) => {
132
+ respond(true, {
133
+ provider: TOOLTRIM_PROVIDER_ID,
134
+ registered: false,
135
+ reason: "gateway lacks registerCompactionProvider (upgrade gateway to use tooltrim)",
136
+ orchestration: "bridge",
137
+ keepRecentToolCalls: 10,
138
+ });
139
+ }, { scope: "operator.read" });
140
+ return;
141
+ }
142
+ api.registerCompactionProvider(toolTrimProvider());
143
+ api.registerGatewayMethod("lma.core.compact.tooltrim", ({ respond }) => {
144
+ respond(true, {
145
+ provider: TOOLTRIM_PROVIDER_ID,
146
+ registered: true,
147
+ orchestration: "bridge",
148
+ usage: "LMA bridge /compact tooltrim performs: config.set(provider) -> sessions.compact -> config restore",
149
+ keepRecentToolCalls: 10,
150
+ });
151
+ }, { scope: "operator.read" });
152
+ }
@@ -0,0 +1,45 @@
1
+ {
2
+ "id": "lma-core",
3
+ "name": "LMA Core",
4
+ "description": "Consolidated LMA plugin: mid-run steer injection, Go checker tool enforcement, custom compaction R&D.",
5
+ "version": "0.2.0",
6
+ "activation": {
7
+ "onStartup": true
8
+ },
9
+ "configSchema": {
10
+ "type": "object",
11
+ "additionalProperties": false,
12
+ "properties": {
13
+ "bindings": {
14
+ "type": "array",
15
+ "items": {
16
+ "type": "object",
17
+ "additionalProperties": false,
18
+ "required": [
19
+ "checkerSessionKey",
20
+ "checkerSessionId",
21
+ "executorSessionKey",
22
+ "executorSessionId"
23
+ ],
24
+ "properties": {
25
+ "checkerSessionKey": {
26
+ "type": "string"
27
+ },
28
+ "checkerSessionId": {
29
+ "type": "string"
30
+ },
31
+ "executorSessionKey": {
32
+ "type": "string"
33
+ },
34
+ "executorSessionId": {
35
+ "type": "string"
36
+ },
37
+ "goalId": {
38
+ "type": "string"
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }
44
+ }
45
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "@hackerphysics/lma-core",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "private": true,
6
+ "description": "Consolidated LMA gateway plugin: steer injection, Go checker tool enforcement, custom compaction R&D.",
7
+ "openclaw": {
8
+ "extensions": [
9
+ "./dist/index.js"
10
+ ],
11
+ "compat": {
12
+ "pluginApi": ">=2026.3.0"
13
+ }
14
+ }
15
+ }
@@ -1,3 +1,10 @@
1
+ > **Legacy standalone plugin (retired from the 1.8.5 install path).**
2
+ > Use the consolidated lma-core 0.2.0 callback/attempt journal protocol. The CLI
3
+ > `lma install-steer-plugin` is now a compatibility alias for `install-core-plugin`.
4
+ > Do not activate this legacy boolean-only plugin alongside lma-core. Its source
5
+ > is retained for old-package history, not as the current receipt implementation.
6
+ > Historical consumption/replay wording below describes the old version only.
7
+
1
8
  # lma-steer
2
9
 
3
10
  `lma-steer` provides observable mid-run insertion for
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ // Default is a genuinely read-only preview (no schema migration, no transport).
3
+ import Database from 'better-sqlite3';
4
+ import {MessageStore} from '../dist/message-store.js';
5
+ const args=process.argv.slice(2);
6
+ const value=flag=>{const i=args.indexOf(flag);return i<0?undefined:args[i+1];};
7
+ const path=value('--db'),bot=value('--bot');
8
+ if(!path || !bot) throw new Error('Usage: --db <explicit LMA messages.db> --bot <name> [--limit 100] [--register --outbox <id> --chat <id> --verified-message-id <actual id> ...]');
9
+ if(args.includes('--register')) {
10
+ const id=Number(value('--outbox')),chat=value('--chat');
11
+ const ids=args.flatMap((x,i)=>x==='--verified-message-id'?[args[i+1]]:[]);
12
+ if(!Number.isSafeInteger(id)||id<=0||!chat||!ids.length||ids.some(x=>!x))throw new Error('Registration requires exact bot/chat/outbox and independently verified actual platform message IDs. It never sends.');
13
+ // Refuse a wrong/non-LMA database BEFORE constructing a writable store or
14
+ // running any migration. Registration is for an existing exact delivered row.
15
+ const check=new Database(path,{readonly:true,fileMustExist:true});
16
+ try {
17
+ const identity=check.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='lma_database_identity'").get();
18
+ if(!identity || check.prepare('SELECT owner FROM lma_database_identity WHERE id=1').get()?.owner!=='openclaw-lark-multi-agent:messages:v1')throw new Error('Not an owned LMA messages database; refusing all writes');
19
+ const required={
20
+ messages:['id','chat_id','message_id','sender_type','sender_name','content','timestamp'],
21
+ delivery_outbox:['id','session_key','bot_name','chat_id','delivery_key','source_type','source_id','content_hash','content','attachments_json','delivery_meta_json','text_delivered','attachment_cursor','status','attempts','created_at','updated_at'],
22
+ delivery_operations:['outbox_id','operation_key','state','record_json'],
23
+ delivery_context:['outbox_id','stage','message_row_id'],
24
+ delivery_receipt_custody:['outbox_id','operation_key','record_json'],
25
+ platform_message_aliases:['message_id','message_row_id'],
26
+ };
27
+ for(const [table,columns] of Object.entries(required)) {
28
+ const schema=check.prepare(`PRAGMA table_info(${table})`).all();
29
+ if(columns.some(column=>!schema.some(c=>c.name===column)) || !schema.some(c=>c.pk>0))throw new Error('Incomplete LMA schema; refusing all writes');
30
+ }
31
+ const row=check.prepare("SELECT id FROM delivery_outbox WHERE id=? AND bot_name=? AND chat_id=? AND (status='delivered' OR EXISTS(SELECT 1 FROM delivery_operations o WHERE o.outbox_id=delivery_outbox.id AND o.state IN ('attempted','unknown')))").get(id,bot,chat);
32
+ if(!row)throw new Error('Exact LMA bot/chat/outbox custody not found; refusing all writes');
33
+ }finally{check.close();}
34
+ const store=new MessageStore(path,{existingOnly:true});
35
+ try {store.registerHistoricalDeliveryContext(id,bot,chat,ids);console.log(JSON.stringify({registered:true,outboxId:id,bot,chat,receipts:ids.length,resent:false}));}finally{store.close();}
36
+ } else {
37
+ const db=new Database(path,{readonly:true,fileMustExist:true});
38
+ try {
39
+ const hasContext=!!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='delivery_context'").get();
40
+ const hasOperations=!!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='delivery_operations'").get();
41
+ const limit=Math.min(1000,Math.max(1,Number(value('--limit')||100)));
42
+ // Preview must work before upgrading a legacy LMA database. Never create or
43
+ // migrate a missing journal merely to list already-delivered historical rows.
44
+ const unknownOperations=hasOperations ? "EXISTS(SELECT 1 FROM delivery_operations o WHERE o.outbox_id=d.id AND o.state IN ('attempted','unknown'))" : '0';
45
+ const rows=db.prepare(`SELECT d.id,d.chat_id,d.delivery_key,d.source_type,d.text_delivered,d.attachment_cursor FROM delivery_outbox d
46
+ WHERE bot_name=? AND (status='delivered' ${hasContext?"AND NOT EXISTS(SELECT 1 FROM delivery_context c WHERE c.outbox_id=d.id)":''} OR ${unknownOperations}) ORDER BY d.id LIMIT ?`).all(bot,limit);
47
+ console.log(JSON.stringify({dryRun:true,registered:false,resent:false,requiresIndependentReceiptVerification:true,rows},null,2));
48
+ } finally{db.close();}
49
+ }