memgate 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.
- package/LICENSE +12 -0
- package/README.md +52 -2
- package/VERSIONS.json +17 -0
- package/dist/index.js +726 -0
- package/index.ts +25 -0
- package/openclaw.plugin.json +53 -0
- package/package.json +37 -3
- package/src/admission.py +208 -0
- package/src/bridge.ts +205 -0
- package/src/bridge_cli.py +600 -0
- package/src/context-engine.ts +373 -0
- package/src/hebbian_link.py +34 -0
- package/src/kernel/activity_telemetry.py +51 -0
- package/src/kernel/admission.py +208 -0
- package/src/kernel/calldecay/__init__.py +24 -0
- package/src/kernel/calldecay/__main__.py +7 -0
- package/src/kernel/calldecay/_kernel.py +32 -0
- package/src/kernel/calldecay/adapter.py +126 -0
- package/src/kernel/calldecay/cli.py +80 -0
- package/src/kernel/calldecay/gate.py +93 -0
- package/src/kernel/calldecay/landing.py +1298 -0
- package/src/kernel/calldecay/metrics.py +37 -0
- package/src/kernel/calldecay/mock.py +68 -0
- package/src/kernel/calldecay/pipeline.py +85 -0
- package/src/kernel/calldecay/proxy.py +220 -0
- package/src/kernel/calldecay/summarize.py +401 -0
- package/src/kernel/core/LICENSE +228 -0
- package/src/kernel/core/__init__.py +0 -0
- package/src/kernel/core/accept_contract.py +67 -0
- package/src/kernel/core/chain_probe_world.py +133 -0
- package/src/kernel/core/concept_ontology.py +2401 -0
- package/src/kernel/core/concept_opposition.py +291 -0
- package/src/kernel/core/concept_phase.py +1342 -0
- package/src/kernel/core/concept_principle.py +2481 -0
- package/src/kernel/core/concept_pyramid.py +287 -0
- package/src/kernel/core/concept_space.py +45 -0
- package/src/kernel/core/concept_space_mixin.py +941 -0
- package/src/kernel/core/concept_state.py +2748 -0
- package/src/kernel/core/decision_symbolic.py +245 -0
- package/src/kernel/core/eco_math_world.py +489 -0
- package/src/kernel/core/emergence.py +362 -0
- package/src/kernel/core/events.py +93 -0
- package/src/kernel/core/hebbian.py +117 -0
- package/src/kernel/core/llm_arm.py +551 -0
- package/src/kernel/core/memory_shadow.py +158 -0
- package/src/kernel/core/mes_layer_base.py +309 -0
- package/src/kernel/core/mes_vnext.py +540 -0
- package/src/kernel/core/ontology_core.py +168 -0
- package/src/kernel/core/phase_field.py +187 -0
- package/src/kernel/core/reasoning.py +185 -0
- package/src/kernel/core/rhythm_vnext.py +777 -0
- package/src/kernel/dashboard_render.py +196 -0
- package/src/kernel/depscan_probe.py +96 -0
- package/src/kernel/health_probe.py +186 -0
- package/src/kernel/hebbian_link.py +34 -0
- package/src/kernel/knowledge_distiller/README.md +9 -0
- package/src/kernel/knowledge_distiller/__init__.py +1 -0
- package/src/kernel/knowledge_distiller/knowledge_distiller.py +196 -0
- package/src/kernel/m3_judge.py +215 -0
- package/src/kernel/mechanism_advisor.py +203 -0
- package/src/kernel/mechanism_learner.py +193 -0
- package/src/kernel/memory_core.py +81 -0
- package/src/kernel/quality_gate/README.md +9 -0
- package/src/kernel/quality_gate/__init__.py +1 -0
- package/src/kernel/quality_gate/quality_gate.py +7 -0
- package/src/kernel/registry_gate.py +57 -0
- package/src/kernel/semantic_recall.py +635 -0
- package/src/kernel/tiered_decay/README.md +9 -0
- package/src/kernel/tiered_decay/__init__.py +1 -0
- package/src/kernel/tiered_decay/tiered_decay.py +17 -0
- package/src/kernel/tokenizer/README.md +9 -0
- package/src/kernel/tokenizer/__init__.py +2 -0
- package/src/kernel/tokenizer/tokenizer.py +14 -0
- package/src/kernel/version_binding.py +131 -0
- package/src/knowledge_distiller.py +196 -0
- package/src/m3_collector.py +247 -0
- package/src/m3_judge.py +215 -0
- package/src/memory-capability.ts +44 -0
- package/src/semantic_recall.py +635 -0
- package/src/thinking_stub.ts +141 -0
- package/src/toolface_hook.ts +69 -0
- package/src/tools.ts +98 -0
- package/src/vendor/calldecay-sdk/calldecay/__init__.py +24 -0
- package/src/vendor/calldecay-sdk/calldecay/__main__.py +7 -0
- package/src/vendor/calldecay-sdk/calldecay/_kernel.py +32 -0
- package/src/vendor/calldecay-sdk/calldecay/adapter.py +126 -0
- package/src/vendor/calldecay-sdk/calldecay/cli.py +80 -0
- package/src/vendor/calldecay-sdk/calldecay/gate.py +93 -0
- package/src/vendor/calldecay-sdk/calldecay/landing.py +1298 -0
- package/src/vendor/calldecay-sdk/calldecay/metrics.py +37 -0
- package/src/vendor/calldecay-sdk/calldecay/mock.py +68 -0
- package/src/vendor/calldecay-sdk/calldecay/pipeline.py +85 -0
- package/src/vendor/calldecay-sdk/calldecay/proxy.py +220 -0
- package/src/vendor/calldecay-sdk/calldecay/summarize.py +401 -0
- package/src/vendor/core/LICENSE +228 -0
- package/src/vendor/core/__init__.py +0 -0
- package/src/vendor/core/accept_contract.py +67 -0
- package/src/vendor/core/chain_probe_world.py +133 -0
- package/src/vendor/core/concept_ontology.py +2401 -0
- package/src/vendor/core/concept_opposition.py +291 -0
- package/src/vendor/core/concept_phase.py +1342 -0
- package/src/vendor/core/concept_principle.py +2481 -0
- package/src/vendor/core/concept_pyramid.py +287 -0
- package/src/vendor/core/concept_space.py +45 -0
- package/src/vendor/core/concept_space_mixin.py +941 -0
- package/src/vendor/core/concept_state.py +2748 -0
- package/src/vendor/core/decision_symbolic.py +245 -0
- package/src/vendor/core/eco_math_world.py +489 -0
- package/src/vendor/core/emergence.py +362 -0
- package/src/vendor/core/events.py +93 -0
- package/src/vendor/core/hebbian.py +117 -0
- package/src/vendor/core/llm_arm.py +551 -0
- package/src/vendor/core/memory_shadow.py +158 -0
- package/src/vendor/core/mes_layer_base.py +309 -0
- package/src/vendor/core/mes_vnext.py +540 -0
- package/src/vendor/core/ontology_core.py +168 -0
- package/src/vendor/core/phase_field.py +187 -0
- package/src/vendor/core/reasoning.py +185 -0
- package/src/vendor/core/rhythm_vnext.py +777 -0
- package/src/vendor/pvs-sdk/pvs/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/adapters/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/adapters/llm_backends.py +69 -0
- package/src/vendor/pvs-sdk/pvs/core/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/core/budget.py +84 -0
- package/src/vendor/pvs-sdk/pvs/core/llm_gate.py +149 -0
- package/src/vendor/pvs-sdk/pvs/core/memory.py +143 -0
- package/src/vendor/pvs-sdk/pvs/core/pvs.py +175 -0
- package/src/vendor/pvs-sdk/pvs/core/verifier.py +77 -0
- package/src/vendor/pvs-sdk/pvs/eval/__init__.py +3 -0
- package/src/vendor/pvs-sdk/pvs/eval/coverage.py +82 -0
- package/src/vendor/pvs-sdk/pvs/gate/__init__.py +5 -0
- package/src/vendor/pvs-sdk/pvs/gate/__main__.py +3 -0
- package/src/vendor/pvs-sdk/pvs/gate/boot.py +68 -0
- package/src/vendor/pvs-sdk/pvs/gate/ledger.py +157 -0
- package/src/vendor/pvs-sdk/pvs/gate/preflight.py +342 -0
- package/src/vendor/pvs-sdk/pvs/harness/__init__.py +0 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
// index.ts
|
|
2
|
+
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
3
|
+
|
|
4
|
+
// src/tools.ts
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
|
|
7
|
+
// src/bridge.ts
|
|
8
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
9
|
+
import { readFileSync } from "node:fs";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
var DEFAULT_BRIDGE = fileURLToPath(new URL("./bridge_cli.py", import.meta.url));
|
|
12
|
+
function flagTail(cfg, args) {
|
|
13
|
+
const tail = [];
|
|
14
|
+
if (cfg.landingPath) tail.push("--landing", cfg.landingPath);
|
|
15
|
+
if (cfg.workspaceRoot) tail.push("--ws", cfg.workspaceRoot);
|
|
16
|
+
return tail.concat(args.map(String));
|
|
17
|
+
}
|
|
18
|
+
function bridgeCall(cfg, sub, args = []) {
|
|
19
|
+
const bin = cfg.pythonBin ?? "python3";
|
|
20
|
+
const bridge = cfg.bridgePath ?? DEFAULT_BRIDGE;
|
|
21
|
+
const out = execFileSync(bin, [bridge, "--oneshot"], {
|
|
22
|
+
input: JSON.stringify({ sub, args: flagTail(cfg, args) }),
|
|
23
|
+
encoding: "utf-8",
|
|
24
|
+
timeout: 5e3,
|
|
25
|
+
// 同步面仅 promptBuilder(实测 warm 10–20ms ⇒ 250×余量);python 挂死最坏卡事件循环 5s 而非 30s,保登录页可用
|
|
26
|
+
maxBuffer: 8 * 1024 * 1024
|
|
27
|
+
});
|
|
28
|
+
return JSON.parse(out);
|
|
29
|
+
}
|
|
30
|
+
var BridgeWorker = class {
|
|
31
|
+
constructor(cfg) {
|
|
32
|
+
this.cfg = cfg;
|
|
33
|
+
}
|
|
34
|
+
cfg;
|
|
35
|
+
proc = null;
|
|
36
|
+
nextId = 1;
|
|
37
|
+
pending = /* @__PURE__ */ new Map();
|
|
38
|
+
buf = "";
|
|
39
|
+
ensure() {
|
|
40
|
+
if (this.proc && this.proc.exitCode === null) return this.proc;
|
|
41
|
+
const bin = this.cfg.pythonBin ?? "python3";
|
|
42
|
+
const bridge = this.cfg.bridgePath ?? DEFAULT_BRIDGE;
|
|
43
|
+
const proc = spawn(bin, [bridge, "--serve"], { stdio: ["pipe", "pipe", "pipe"] });
|
|
44
|
+
this.buf = "";
|
|
45
|
+
proc.stdout.on("data", (d) => this.onData(d));
|
|
46
|
+
proc.stderr.on("data", (d) => {
|
|
47
|
+
const s = d.toString().trim();
|
|
48
|
+
if (s) console.error("[memgate] worker stderr:", s.slice(0, 500));
|
|
49
|
+
});
|
|
50
|
+
proc.on("exit", () => this.onExit(proc));
|
|
51
|
+
proc.on("error", (err) => this.onError(proc, err));
|
|
52
|
+
this.proc = proc;
|
|
53
|
+
return proc;
|
|
54
|
+
}
|
|
55
|
+
onData(d) {
|
|
56
|
+
this.buf += d.toString("utf-8");
|
|
57
|
+
let nl;
|
|
58
|
+
while ((nl = this.buf.indexOf("\n")) >= 0) {
|
|
59
|
+
const line = this.buf.slice(0, nl).trim();
|
|
60
|
+
this.buf = this.buf.slice(nl + 1);
|
|
61
|
+
if (!line) continue;
|
|
62
|
+
let msg;
|
|
63
|
+
try {
|
|
64
|
+
msg = JSON.parse(line);
|
|
65
|
+
} catch {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const p = this.pending.get(msg.id);
|
|
69
|
+
if (!p) continue;
|
|
70
|
+
this.pending.delete(msg.id);
|
|
71
|
+
clearTimeout(p.timer);
|
|
72
|
+
if (msg.ok) p.resolve(msg.result);
|
|
73
|
+
else p.reject(new Error(String(msg.error ?? "bridge worker error")));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
onExit(proc) {
|
|
77
|
+
if (this.proc === proc) this.proc = null;
|
|
78
|
+
for (const [, p] of this.pending) {
|
|
79
|
+
clearTimeout(p.timer);
|
|
80
|
+
p.reject(new Error("bridge worker exited"));
|
|
81
|
+
}
|
|
82
|
+
this.pending.clear();
|
|
83
|
+
}
|
|
84
|
+
onError(proc, err) {
|
|
85
|
+
if (this.proc === proc) this.proc = null;
|
|
86
|
+
for (const [, p] of this.pending) {
|
|
87
|
+
clearTimeout(p.timer);
|
|
88
|
+
p.reject(new Error(`bridge worker spawn: ${err.message}`));
|
|
89
|
+
}
|
|
90
|
+
this.pending.clear();
|
|
91
|
+
}
|
|
92
|
+
call(sub, tail) {
|
|
93
|
+
return new Promise((resolve, reject) => {
|
|
94
|
+
const proc = this.ensure();
|
|
95
|
+
const id = this.nextId++;
|
|
96
|
+
const timer = setTimeout(() => {
|
|
97
|
+
this.pending.delete(id);
|
|
98
|
+
this.dispose();
|
|
99
|
+
reject(new Error(`bridge worker timeout: ${sub}`));
|
|
100
|
+
}, 3e4);
|
|
101
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
102
|
+
proc.stdin.write(JSON.stringify({ id, sub, args: tail }) + "\n", (err) => {
|
|
103
|
+
if (!err) return;
|
|
104
|
+
const p = this.pending.get(id);
|
|
105
|
+
if (p) {
|
|
106
|
+
this.pending.delete(id);
|
|
107
|
+
clearTimeout(p.timer);
|
|
108
|
+
this.dispose();
|
|
109
|
+
p.reject(new Error(`bridge worker write: ${err.message}`));
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
dispose() {
|
|
115
|
+
const proc = this.proc;
|
|
116
|
+
this.proc = null;
|
|
117
|
+
for (const [, p] of this.pending) {
|
|
118
|
+
clearTimeout(p.timer);
|
|
119
|
+
p.reject(new Error("bridge worker disposed"));
|
|
120
|
+
}
|
|
121
|
+
this.pending.clear();
|
|
122
|
+
if (proc && proc.exitCode === null) proc.kill("SIGTERM");
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
var GATE_CFG = fileURLToPath(new URL("../config/daemon_forward.json", import.meta.url));
|
|
126
|
+
function remoteFor(cfg) {
|
|
127
|
+
if (cfg.remoteBridge === false) return null;
|
|
128
|
+
if (cfg.remoteEndpoint) return cfg.remoteEndpoint;
|
|
129
|
+
try {
|
|
130
|
+
const g = JSON.parse(readFileSync(GATE_CFG, "utf-8"));
|
|
131
|
+
if (g && g.bridgeRemote && typeof g.endpoint === "string") return g.endpoint;
|
|
132
|
+
} catch {
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
async function remoteCall(endpoint, sub, tail) {
|
|
137
|
+
const ac = new AbortController();
|
|
138
|
+
const timer = setTimeout(() => ac.abort(), 25e3);
|
|
139
|
+
try {
|
|
140
|
+
const res = await fetch(endpoint.replace(/\/$/, "") + "/bridge", {
|
|
141
|
+
method: "POST",
|
|
142
|
+
headers: { "content-type": "application/json" },
|
|
143
|
+
body: JSON.stringify({ sub, args: tail }),
|
|
144
|
+
signal: ac.signal
|
|
145
|
+
});
|
|
146
|
+
const body = await res.json();
|
|
147
|
+
if (!res.ok || body && body.ok === false && body.error) {
|
|
148
|
+
throw new Error(String(body?.error ?? `HTTP ${res.status}`));
|
|
149
|
+
}
|
|
150
|
+
return body && typeof body === "object" && body.ok === true && "result" in body ? body.result : body;
|
|
151
|
+
} finally {
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
var workers = /* @__PURE__ */ new Map();
|
|
156
|
+
function workerFor(cfg) {
|
|
157
|
+
const key = `${cfg.pythonBin ?? "python3"}|${cfg.bridgePath ?? DEFAULT_BRIDGE}`;
|
|
158
|
+
let w = workers.get(key);
|
|
159
|
+
if (!w) {
|
|
160
|
+
w = new BridgeWorker(cfg);
|
|
161
|
+
workers.set(key, w);
|
|
162
|
+
}
|
|
163
|
+
return w;
|
|
164
|
+
}
|
|
165
|
+
function bridgeCallAsync(cfg, sub, args = []) {
|
|
166
|
+
const tail = flagTail(cfg, args);
|
|
167
|
+
const ep = remoteFor(cfg);
|
|
168
|
+
if (ep) return remoteCall(ep, sub, tail).catch(() => workerFor(cfg).call(sub, tail));
|
|
169
|
+
return workerFor(cfg).call(sub, tail);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// src/tools.ts
|
|
173
|
+
function registerGovernanceTools(api, cfg) {
|
|
174
|
+
api.registerTool({
|
|
175
|
+
name: "governance_preflight",
|
|
176
|
+
description: "\u8FD0\u884C\u6CBB\u7406\u95E8\u7981\uFF08pvs.gate \u5F00\u673A\u95F8\uFF09\uFF1A13 \u6761\u6559\u8BAD\u65AD\u8A00 + \u8BB0\u5FC6\u5207\u7247 + \u771F\u76F8\u6458\u8981 + \u4F9D\u8D56\u94FE\u5DE1\u68C0\uFF08deps_targets.json \u5B58\u5728\u65F6\u9010\u6761\u771F\u8DD1\uFF0C\u6B7B\u94FE\u5165\u8D26\uFF09\u3002\u5F00\u5DE5\u524D\u6216\u7528\u6237\u8981\u95E8\u7981\u8BFB\u6570\u65F6\u8C03\u7528\u3002",
|
|
177
|
+
parameters: Type.Object({}),
|
|
178
|
+
outputSchema: Type.Object(
|
|
179
|
+
{
|
|
180
|
+
ok: Type.Boolean(),
|
|
181
|
+
n_fail: Type.Number(),
|
|
182
|
+
n_decl: Type.Number(),
|
|
183
|
+
rendered: Type.String()
|
|
184
|
+
},
|
|
185
|
+
{ additionalProperties: true }
|
|
186
|
+
),
|
|
187
|
+
async execute(_id, _params) {
|
|
188
|
+
const r = await bridgeCallAsync(cfg, "preflight");
|
|
189
|
+
return {
|
|
190
|
+
content: [{ type: "text", text: String(r.rendered ?? JSON.stringify(r)) }],
|
|
191
|
+
details: r
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
api.registerTool({
|
|
196
|
+
name: "governance_ledger",
|
|
197
|
+
description: "\u67E5\u8BE2\u5DE5\u7A0B\u6559\u8BAD\u53F0\u8D26\uFF08pvs.gate\uFF09\uFF1A\u4E0D\u5E26 id \u5217\u51FA\u5168\u90E8\uFF1B\u5E26 id \u53D6\u5355\u6761\u516D\u5B57\u6BB5\uFF08\u75C7\u72B6/\u6839\u56E0/\u65AD\u8A00/\u6559\u8BAD/\u9002\u7528\u9762/\u9A8C\u8BC1\uFF09\u3002",
|
|
198
|
+
parameters: Type.Object({ id: Type.Optional(Type.String()) }),
|
|
199
|
+
outputSchema: Type.Object({}, { additionalProperties: true }),
|
|
200
|
+
async execute(_id, params) {
|
|
201
|
+
const args = params?.id ? ["--id", String(params.id)] : [];
|
|
202
|
+
const r = await bridgeCallAsync(cfg, "ledger", args);
|
|
203
|
+
return {
|
|
204
|
+
content: [{ type: "text", text: JSON.stringify(r, null, 1) }],
|
|
205
|
+
details: r
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
api.registerTool({
|
|
210
|
+
name: "governance_deposit",
|
|
211
|
+
description: "\u51B3\u7B56\u5165\u8D26\uFF08\u8BB0\u5FC6\u751F\u6B7B\u5C42\uFF09\uFF1A\u63D0\u8BAE\u5E26\u7406\u7531\u3001\u51B3\u8BAE\u5E26\u56E0\u679C\u5165\u8D26\uFF0C\u5165\u8D26\u5373\u539F\u5B50\u843D\u76D8\uFF08\u8FDB\u7A0B\u6B7B\u8BB0\u5FC6\u4E0D\u6B7B\uFF09\u3002\u53EA\u8BB0\u62CD\u677F\u4E0E\u5DF2\u9A8C\u8BC1\u7ED3\u8BBA\uFF0C\u4E0D\u8BB0\u8FC7\u7A0B\u6D41\u6C34\u3002",
|
|
212
|
+
parameters: Type.Object({
|
|
213
|
+
obj: Type.String({ description: "\u5BF9\u8C61/\u4E3B\u9898" }),
|
|
214
|
+
act: Type.String({ description: "\u52A8\u4F5C/\u51B3\u8BAE" }),
|
|
215
|
+
actual: Type.Optional(Type.String({ description: "\u5B9E\u9645\u7ED3\u679C/\u8BC1\u636E" })),
|
|
216
|
+
cur: Type.Optional(Type.String({ description: "\u5F53\u524D\u72B6\u6001/\u53E3\u5F84" }))
|
|
217
|
+
}),
|
|
218
|
+
outputSchema: Type.Object({}, { additionalProperties: true }),
|
|
219
|
+
async execute(_id, params) {
|
|
220
|
+
const args = [
|
|
221
|
+
"--obj",
|
|
222
|
+
String(params.obj),
|
|
223
|
+
"--act",
|
|
224
|
+
String(params.act),
|
|
225
|
+
"--actual",
|
|
226
|
+
String(params.actual ?? ""),
|
|
227
|
+
"--cur",
|
|
228
|
+
String(params.cur ?? "")
|
|
229
|
+
];
|
|
230
|
+
const r = await bridgeCallAsync(cfg, "deposit", args);
|
|
231
|
+
return {
|
|
232
|
+
content: [{ type: "text", text: `\u5DF2\u5165\u8D26: ${r?.entry?.id ?? "?"}` }],
|
|
233
|
+
details: r
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
api.registerTool({
|
|
238
|
+
name: "governance_recall",
|
|
239
|
+
description: "\u7B7E\u540D\u95E8\u63A7\u53EC\u56DE\uFF1Amax(Jaccard, \u67E5\u8BE2\u8986\u76D6\u7387) \u22650.3 \u624D\u51FA\u8D26\uFF0C\u4E2D\u6587\u652F\u6301 bigram \u90E8\u5206\u5339\u914D\uFF0C\u88AB\u53EC\u56DE\u5373\u4FDD\u6D3B\u3002\u627E\u300C\u4E0A\u6B21\u4E3A\u4EC0\u4E48\u8FD9\u4E48\u5B9A\u300D\u7528\u5B83\uFF0C\u522B\u7FFB\u6587\u4EF6\u3002",
|
|
240
|
+
parameters: Type.Object({
|
|
241
|
+
signature: Type.String({ description: "\u67E5\u8BE2\u7B7E\u540D\uFF08\u7A7A\u683C\u5206\u9694\u7684\u8BCD\uFF09" }),
|
|
242
|
+
k: Type.Optional(Type.Number({ description: "\u8FD4\u56DE\u4E0A\u9650\uFF0C\u9ED8\u8BA4 8" }))
|
|
243
|
+
}),
|
|
244
|
+
outputSchema: Type.Object({}, { additionalProperties: true }),
|
|
245
|
+
async execute(_id, params) {
|
|
246
|
+
const args = ["--signature", String(params.signature)];
|
|
247
|
+
if (params.k) args.push("--k", String(Math.floor(Number(params.k))));
|
|
248
|
+
const r = await bridgeCallAsync(cfg, "recall", args);
|
|
249
|
+
return {
|
|
250
|
+
content: [{ type: "text", text: JSON.stringify(r, null, 1) }],
|
|
251
|
+
details: r
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/context-engine.ts
|
|
258
|
+
import { delegateCompactionToRuntime } from "openclaw/plugin-sdk/core";
|
|
259
|
+
import { readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
|
|
260
|
+
|
|
261
|
+
// src/thinking_stub.ts
|
|
262
|
+
import { appendFileSync, mkdirSync, readFileSync as readFileSync2, statSync } from "node:fs";
|
|
263
|
+
import { join } from "node:path";
|
|
264
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
265
|
+
var STUB_TEXT = "\uFF08\u5386\u53F2\u601D\u8003\u5DF2\u7701\u7565\uFF09";
|
|
266
|
+
var GATE_FILE = fileURLToPath2(new URL("../config/thinking_stub.json", import.meta.url));
|
|
267
|
+
var DEFAULT_LOG_DIR = fileURLToPath2(new URL("../../\u8BB0\u5FC6\u4F53/shadow/logs/", import.meta.url));
|
|
268
|
+
var __cache = /* @__PURE__ */ new Map();
|
|
269
|
+
function stubGate() {
|
|
270
|
+
try {
|
|
271
|
+
const st = statSync(GATE_FILE);
|
|
272
|
+
const hit = __cache.get(GATE_FILE);
|
|
273
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.gate;
|
|
274
|
+
const g = JSON.parse(readFileSync2(GATE_FILE, "utf8"));
|
|
275
|
+
const mode = g?.mode === "shadow" || g?.mode === "on" ? g.mode : "off";
|
|
276
|
+
const gate = {
|
|
277
|
+
mode,
|
|
278
|
+
stubText: typeof g?.stubText === "string" && g.stubText ? g.stubText : STUB_TEXT,
|
|
279
|
+
logDir: typeof g?.logDir === "string" && g.logDir ? g.logDir : DEFAULT_LOG_DIR
|
|
280
|
+
};
|
|
281
|
+
__cache.set(GATE_FILE, { mtimeMs: st.mtimeMs, size: st.size, gate });
|
|
282
|
+
return gate;
|
|
283
|
+
} catch {
|
|
284
|
+
return { mode: "off", stubText: STUB_TEXT, logDir: DEFAULT_LOG_DIR };
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function scanMessage(m, stubText) {
|
|
288
|
+
if (String(m?.role ?? "") !== "assistant") return { chars: 0, hit: 0, redacted: 0 };
|
|
289
|
+
const content = m?.content;
|
|
290
|
+
let chars = 0;
|
|
291
|
+
let redacted = 0;
|
|
292
|
+
let sawThinkingBlock = false;
|
|
293
|
+
if (Array.isArray(content)) {
|
|
294
|
+
for (const b of content) {
|
|
295
|
+
if (!b || typeof b !== "object") continue;
|
|
296
|
+
if (b.type === "thinking") {
|
|
297
|
+
sawThinkingBlock = true;
|
|
298
|
+
const t = String(b.thinking ?? "");
|
|
299
|
+
if (t && t !== stubText) chars += t.length;
|
|
300
|
+
} else if (b.type === "redacted_thinking") {
|
|
301
|
+
sawThinkingBlock = true;
|
|
302
|
+
redacted += 1;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (!sawThinkingBlock) {
|
|
307
|
+
const rc = m?.reasoning_content;
|
|
308
|
+
if (typeof rc === "string" && rc && rc !== stubText) chars += rc.length;
|
|
309
|
+
}
|
|
310
|
+
return { chars, hit: chars > 0 ? 1 : 0, redacted };
|
|
311
|
+
}
|
|
312
|
+
function scanMessages(messages, stubText) {
|
|
313
|
+
let hitTurns = 0;
|
|
314
|
+
let thinkChars = 0;
|
|
315
|
+
let redactedSkipped = 0;
|
|
316
|
+
for (const m of messages ?? []) {
|
|
317
|
+
const s = scanMessage(m, stubText);
|
|
318
|
+
hitTurns += s.hit;
|
|
319
|
+
thinkChars += s.chars;
|
|
320
|
+
redactedSkipped += s.redacted;
|
|
321
|
+
}
|
|
322
|
+
return { hitTurns, thinkChars, redactedSkipped };
|
|
323
|
+
}
|
|
324
|
+
function applyStub(messages, stubText) {
|
|
325
|
+
return (messages ?? []).map((m) => {
|
|
326
|
+
if (String(m?.role ?? "") !== "assistant") return m;
|
|
327
|
+
const content = m?.content;
|
|
328
|
+
if (Array.isArray(content)) {
|
|
329
|
+
let touched = false;
|
|
330
|
+
const next = content.map((b) => {
|
|
331
|
+
if (b && typeof b === "object" && b.type === "thinking") {
|
|
332
|
+
const t = String(b.thinking ?? "");
|
|
333
|
+
if (t && t !== stubText) {
|
|
334
|
+
touched = true;
|
|
335
|
+
return { ...b, thinking: stubText };
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return b;
|
|
339
|
+
});
|
|
340
|
+
return touched ? { ...m, content: next } : m;
|
|
341
|
+
}
|
|
342
|
+
const rc = m?.reasoning_content;
|
|
343
|
+
if (typeof rc === "string" && rc && rc !== stubText) {
|
|
344
|
+
return { ...m, reasoning_content: stubText };
|
|
345
|
+
}
|
|
346
|
+
return m;
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
function shadowLog(gate, sessionKey, scan) {
|
|
350
|
+
if (scan.hitTurns === 0 && scan.thinkChars === 0) return;
|
|
351
|
+
try {
|
|
352
|
+
mkdirSync(gate.logDir, { recursive: true });
|
|
353
|
+
const tok = scan.thinkChars / 3;
|
|
354
|
+
const rec = {
|
|
355
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
356
|
+
session: String(sessionKey ?? ""),
|
|
357
|
+
hit_turns: scan.hitTurns,
|
|
358
|
+
think_chars: scan.thinkChars,
|
|
359
|
+
redacted_skipped: scan.redactedSkipped,
|
|
360
|
+
proj_tok: Math.round(tok),
|
|
361
|
+
proj_yuan_miss: +(tok / 1e6 * 3).toFixed(4),
|
|
362
|
+
// 未命中价口径(上界)
|
|
363
|
+
proj_yuan_cache: +(tok / 1e6 * 0.025).toFixed(4)
|
|
364
|
+
// 缓存命中价口径(下界)
|
|
365
|
+
};
|
|
366
|
+
appendFileSync(join(gate.logDir, "thinking_stub_shadow.jsonl"), JSON.stringify(rec) + "\n");
|
|
367
|
+
} catch {
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// src/context-engine.ts
|
|
372
|
+
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
373
|
+
var __gateCache = /* @__PURE__ */ new Map();
|
|
374
|
+
function __gateFileFor(cfg) {
|
|
375
|
+
if (cfg && typeof cfg.daemonForwardFile === "string" && cfg.daemonForwardFile) {
|
|
376
|
+
return cfg.daemonForwardFile;
|
|
377
|
+
}
|
|
378
|
+
return fileURLToPath3(new URL("../config/daemon_forward.json", import.meta.url));
|
|
379
|
+
}
|
|
380
|
+
function __loadGate(cfg) {
|
|
381
|
+
const path = __gateFileFor(cfg);
|
|
382
|
+
try {
|
|
383
|
+
const st = statSync2(path);
|
|
384
|
+
const hit = __gateCache.get(path);
|
|
385
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.gate;
|
|
386
|
+
const gate = JSON.parse(readFileSync3(path, "utf8"));
|
|
387
|
+
__gateCache.set(path, { mtimeMs: st.mtimeMs, size: st.size, gate });
|
|
388
|
+
return gate;
|
|
389
|
+
} catch {
|
|
390
|
+
return null;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function __forwardEndpoint(gate, sessionKey) {
|
|
394
|
+
if (!gate || !gate.enabled) return null;
|
|
395
|
+
for (const p of gate.sessions ?? []) {
|
|
396
|
+
if (p === "*" || p && sessionKey.startsWith(p)) {
|
|
397
|
+
return (gate.endpoint ?? "http://127.0.0.1:8877").replace(/\/$/, "");
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
function estimateTokensForContent(content) {
|
|
403
|
+
if (content == null) return 0;
|
|
404
|
+
const str = typeof content === "string" ? content : JSON.stringify(content);
|
|
405
|
+
let tokens = 0;
|
|
406
|
+
for (let i = 0; i < str.length; i++) {
|
|
407
|
+
const ch = str[i];
|
|
408
|
+
if (ch >= "\u4E00" && ch <= "\u9FFF" || // 中文
|
|
409
|
+
ch >= "\u3040" && ch <= "\u309F" || // 日文平假名
|
|
410
|
+
ch >= "\u30A0" && ch <= "\u30FF" || // 日文片假名
|
|
411
|
+
ch >= "\uAC00" && ch <= "\uD7AF" || // 韩文
|
|
412
|
+
ch >= "\u3400" && ch <= "\u4DBF" || // 中文扩展A
|
|
413
|
+
ch >= "\u20000" && ch <= "\u2A6Df") {
|
|
414
|
+
tokens += 0.8;
|
|
415
|
+
} else {
|
|
416
|
+
tokens += 0.18;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return Math.ceil(tokens);
|
|
420
|
+
}
|
|
421
|
+
function sigOf(messages) {
|
|
422
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
423
|
+
const m = messages[i];
|
|
424
|
+
if (m?.role === "user") {
|
|
425
|
+
let t;
|
|
426
|
+
if (typeof m.content === "string") {
|
|
427
|
+
t = m.content;
|
|
428
|
+
} else if (Array.isArray(m.content)) {
|
|
429
|
+
t = m.content.map((blk) => typeof blk === "string" ? blk : blk?.thinking ?? blk?.text ?? blk?.content ?? "").filter(Boolean).join(" ");
|
|
430
|
+
} else {
|
|
431
|
+
t = JSON.stringify(m.content ?? "");
|
|
432
|
+
}
|
|
433
|
+
return t.slice(0, 300);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return "";
|
|
437
|
+
}
|
|
438
|
+
var constraintsCache = null;
|
|
439
|
+
async function __constraintsFor(cfg) {
|
|
440
|
+
if (constraintsCache !== null) return constraintsCache || void 0;
|
|
441
|
+
try {
|
|
442
|
+
const r = await bridgeCallAsync(cfg, "constraints");
|
|
443
|
+
const lines = r?.lines ?? [];
|
|
444
|
+
constraintsCache = lines.length ? "## \u6CBB\u7406\u6CBB\u7406\u7EAA\u5F8B\u9762\uFF08\u4E8B\u524D\u7EA6\u675F\xB7\u6559\u8BAD\u65AD\u8A00\u5E38\u9A7B\uFF09\n" + lines.map((l) => `- ${l}`).join("\n") : "";
|
|
445
|
+
return constraintsCache || void 0;
|
|
446
|
+
} catch (e) {
|
|
447
|
+
console.error("[memgate] \u6CBB\u7406\u7EAA\u5F8B\u9762\u83B7\u53D6\u5931\u8D25\uFF08fail-soft \u96F6\u6CE8\u5165\uFF09:", e);
|
|
448
|
+
return void 0;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
var __ingestedWm = /* @__PURE__ */ new Map();
|
|
452
|
+
function __msgKeyOf(m) {
|
|
453
|
+
const role = String(m?.role ?? "?");
|
|
454
|
+
const text = typeof m?.content === "string" ? m.content : JSON.stringify(m?.content ?? "");
|
|
455
|
+
return role + "\0" + text;
|
|
456
|
+
}
|
|
457
|
+
function __wmFor(sessionId) {
|
|
458
|
+
const key = String(sessionId ?? "_");
|
|
459
|
+
let wm = __ingestedWm.get(key);
|
|
460
|
+
if (!wm) {
|
|
461
|
+
wm = /* @__PURE__ */ new Map();
|
|
462
|
+
__ingestedWm.set(key, wm);
|
|
463
|
+
if (__ingestedWm.size > 200) {
|
|
464
|
+
const first = __ingestedWm.keys().next().value;
|
|
465
|
+
if (first !== void 0) __ingestedWm.delete(first);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return wm;
|
|
469
|
+
}
|
|
470
|
+
async function __ingestMessage(cfg, message, wm) {
|
|
471
|
+
const role = String(message?.role ?? "?");
|
|
472
|
+
let text;
|
|
473
|
+
if (typeof message?.content === "string") {
|
|
474
|
+
text = message.content;
|
|
475
|
+
} else if (Array.isArray(message?.content)) {
|
|
476
|
+
text = message.content.map((blk) => {
|
|
477
|
+
if (typeof blk === "string") return blk;
|
|
478
|
+
return blk?.thinking ?? blk?.text ?? blk?.content ?? "";
|
|
479
|
+
}).filter(Boolean).join(" ");
|
|
480
|
+
} else {
|
|
481
|
+
text = JSON.stringify(message?.content ?? "");
|
|
482
|
+
}
|
|
483
|
+
await bridgeCallAsync(cfg, "ingest", ["--role", role, "--text", text.slice(0, 2e3)]);
|
|
484
|
+
if (wm) {
|
|
485
|
+
wm.set(__msgKeyOf(message), true);
|
|
486
|
+
while (wm.size > 6e3) {
|
|
487
|
+
const k = wm.keys().next().value;
|
|
488
|
+
if (k === void 0) break;
|
|
489
|
+
wm.delete(k);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
var __SUPPLY_BURST = 200;
|
|
494
|
+
async function __supplementIngest(cfg, sessionId, messages) {
|
|
495
|
+
const wm = __wmFor(sessionId);
|
|
496
|
+
let n = 0;
|
|
497
|
+
for (const m of messages) {
|
|
498
|
+
if (n >= __SUPPLY_BURST) break;
|
|
499
|
+
const k = __msgKeyOf(m);
|
|
500
|
+
if (wm.has(k)) continue;
|
|
501
|
+
await __ingestMessage(cfg, m, wm);
|
|
502
|
+
n++;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
function registerGovernanceContextEngine(api, cfg) {
|
|
506
|
+
api.registerContextEngine("memgate", () => {
|
|
507
|
+
const hotN = cfg.hotWindowMessages ?? 12;
|
|
508
|
+
return {
|
|
509
|
+
info: {
|
|
510
|
+
id: "memgate",
|
|
511
|
+
name: "Governance Middleware Context Engine",
|
|
512
|
+
ownsCompaction: false,
|
|
513
|
+
// 委托模式:压缩零丢失判据通过前不接管
|
|
514
|
+
acceptedHostParams: ["sessionKey", "runtimeContext"],
|
|
515
|
+
transcriptSemantics: {
|
|
516
|
+
currentTurnFence: "before-current-turn-entry-v1",
|
|
517
|
+
turnAdvancementIdempotency: "atomic-idempotent-v1"
|
|
518
|
+
}
|
|
519
|
+
},
|
|
520
|
+
async ingest({ sessionId, message }) {
|
|
521
|
+
await __ingestMessage(cfg, message, __wmFor(sessionId));
|
|
522
|
+
return { ingested: true };
|
|
523
|
+
},
|
|
524
|
+
async assemble({ sessionId, sessionKey, messages, tokenBudget }) {
|
|
525
|
+
await __supplementIngest(cfg, sessionId, messages ?? []);
|
|
526
|
+
const hot = (messages ?? []).slice(-hotN);
|
|
527
|
+
const estimatedTokens = estimateTokensForContent(hot);
|
|
528
|
+
const parts = [];
|
|
529
|
+
const ban = await __constraintsFor(cfg);
|
|
530
|
+
if (ban) parts.push(ban);
|
|
531
|
+
try {
|
|
532
|
+
const ess = await bridgeCallAsync(cfg, "recall", [
|
|
533
|
+
"--signature",
|
|
534
|
+
"\u6559\u8BAD|\u94C1\u5F8B|\u4E8B\u6545|\u6839\u56E0|\u7981\u6B62|\u62CD\u677F",
|
|
535
|
+
"--k",
|
|
536
|
+
"8"
|
|
537
|
+
]);
|
|
538
|
+
const essHits = ess?.hits ?? [];
|
|
539
|
+
if (essHits.length > 0) {
|
|
540
|
+
parts.push(
|
|
541
|
+
"## \u5386\u53F2\u6559\u8BAD\u63D0\u9192\uFF08\u6559\u8BAD\u4F18\u5148\xB7\u81EA\u52A8\u6CE8\u5165\uFF09\n" + essHits.map((h, i) => `${i + 1}. ${h.entry?.signature ?? "?"}`).join("\n")
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
} catch {
|
|
545
|
+
}
|
|
546
|
+
const sk = String(sessionKey ?? sessionId ?? "");
|
|
547
|
+
const fwd = __forwardEndpoint(__loadGate(cfg), sk);
|
|
548
|
+
let decided = false;
|
|
549
|
+
if (fwd) {
|
|
550
|
+
try {
|
|
551
|
+
const gate = __loadGate(cfg);
|
|
552
|
+
const resp = await fetch(fwd + "/decision", {
|
|
553
|
+
method: "POST",
|
|
554
|
+
headers: { "content-type": "application/json" },
|
|
555
|
+
body: JSON.stringify({
|
|
556
|
+
session: sk,
|
|
557
|
+
signature: sigOf(messages ?? []),
|
|
558
|
+
k: 6,
|
|
559
|
+
messages: (messages ?? []).slice(-200),
|
|
560
|
+
total_messages: (messages ?? []).length
|
|
561
|
+
}),
|
|
562
|
+
signal: AbortSignal.timeout(gate?.timeoutMs ?? 2500)
|
|
563
|
+
});
|
|
564
|
+
const rd = await resp.json();
|
|
565
|
+
if (!rd?.ok || !Array.isArray(rd.hits)) {
|
|
566
|
+
throw new Error(`daemon decision bad payload: ${resp.status}`);
|
|
567
|
+
}
|
|
568
|
+
const hits = rd.hits;
|
|
569
|
+
if (hits.length) {
|
|
570
|
+
parts.push(
|
|
571
|
+
"## \u51B3\u7B56\u8BB0\u5FC6\u53EC\u56DE\uFF08\u6E29\u5C42\xB7\u7B7E\u540D\u95E8\u63A7\uFF09\n" + hits.map((h) => `- ${h.entry?.signature ?? "?"}\uFF08\u76F8\u4F3C\u5EA6 ${h.score}\uFF09`).join("\n")
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
decided = true;
|
|
575
|
+
} catch (e) {
|
|
576
|
+
console.error("[memgate] \u8F6C\u63A5\u5931\u8D25\uFF08fail-soft \u56DE\u9000\u539F\u8DEF\u5F84\uFF09:", e);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
if (!decided) {
|
|
580
|
+
try {
|
|
581
|
+
const r = await bridgeCallAsync(cfg, "recall", [
|
|
582
|
+
"--signature",
|
|
583
|
+
sigOf(messages ?? []),
|
|
584
|
+
"--k",
|
|
585
|
+
"6"
|
|
586
|
+
]);
|
|
587
|
+
const hits = r?.hits ?? [];
|
|
588
|
+
if (hits.length) {
|
|
589
|
+
parts.push(
|
|
590
|
+
"## \u51B3\u7B56\u8BB0\u5FC6\u53EC\u56DE\uFF08\u6E29\u5C42\xB7\u7B7E\u540D\u95E8\u63A7\uFF09\n" + hits.map((h) => `- ${h.entry?.signature ?? "?"}\uFF08\u76F8\u4F3C\u5EA6 ${h.score}\uFF09`).join("\n")
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
} catch (e) {
|
|
594
|
+
console.error("[memgate] \u6E29\u5C42\u53EC\u56DE\u5931\u8D25\uFF08fail-soft \u96F6\u6CE8\u5165\uFF09:", e);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
void tokenBudget;
|
|
598
|
+
const stub = stubGate();
|
|
599
|
+
let outMsgs = hot;
|
|
600
|
+
if (stub.mode !== "off") {
|
|
601
|
+
const scan = scanMessages(hot, stub.stubText);
|
|
602
|
+
shadowLog(stub, String(sessionKey ?? sessionId ?? ""), scan);
|
|
603
|
+
if (stub.mode === "on") outMsgs = applyStub(hot, stub.stubText);
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
messages: outMsgs,
|
|
607
|
+
estimatedTokens: outMsgs === hot ? estimatedTokens : estimateTokensForContent(outMsgs),
|
|
608
|
+
systemPromptAddition: parts.length ? parts.join("\n\n") : void 0
|
|
609
|
+
};
|
|
610
|
+
},
|
|
611
|
+
async compact(params) {
|
|
612
|
+
return await delegateCompactionToRuntime(params);
|
|
613
|
+
},
|
|
614
|
+
async commitTurn({ advancementKey, messages }) {
|
|
615
|
+
const payload = JSON.stringify(messages ?? []).slice(0, 200);
|
|
616
|
+
const r = await bridgeCallAsync(cfg, "commit", [
|
|
617
|
+
"--key",
|
|
618
|
+
String(advancementKey),
|
|
619
|
+
"--payload",
|
|
620
|
+
payload
|
|
621
|
+
]);
|
|
622
|
+
return { status: r.status === "duplicate" ? "duplicate" : "committed" };
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/memory-capability.ts
|
|
629
|
+
function registerGovernanceMemory(api, cfg) {
|
|
630
|
+
api.registerMemoryCapability({
|
|
631
|
+
// 确定性召回工具由本插件的 governance_recall 提供(provider 直查的落点)
|
|
632
|
+
deterministicRecallToolName: "governance_recall",
|
|
633
|
+
promptBuilder: (params) => {
|
|
634
|
+
void params;
|
|
635
|
+
try {
|
|
636
|
+
const r = bridgeCall(cfg, "digest", ["--k", "8"]);
|
|
637
|
+
const top = r?.top ?? [];
|
|
638
|
+
if (!top.length) return [];
|
|
639
|
+
const lines = top.map(
|
|
640
|
+
(e) => `- ${e.signature ?? "?"}\uFF08hits=${e.hits}\uFF0C${e.ts ?? "?"}\uFF09`
|
|
641
|
+
);
|
|
642
|
+
return [
|
|
643
|
+
"## \u51B3\u7B56\u8BB0\u5FC6\uFF08\u6E29\u5C42\xB7\u8D26\u672C\u6458\u8981\uFF09\n" + lines.join("\n") + "\n\uFF08\u68C0\u7D22\uFF1Agovernance_recall \u5DE5\u5177\uFF1B\u5165\u8D26\uFF1Agovernance_deposit\uFF09"
|
|
644
|
+
];
|
|
645
|
+
} catch (e) {
|
|
646
|
+
console.error("[memgate] \u8BB0\u5FC6\u6458\u8981\u5931\u8D25\uFF08fail-soft \u96F6\u6CE8\u5165\uFF09:", e);
|
|
647
|
+
return [];
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// src/toolface_hook.ts
|
|
654
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
655
|
+
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
656
|
+
var GATE_CFG2 = fileURLToPath4(new URL("../config/daemon_forward.json", import.meta.url));
|
|
657
|
+
var faceCache = /* @__PURE__ */ new Map();
|
|
658
|
+
function gateState() {
|
|
659
|
+
try {
|
|
660
|
+
const g = JSON.parse(readFileSync4(GATE_CFG2, "utf-8"));
|
|
661
|
+
return {
|
|
662
|
+
on: !!g.toolfaceHook,
|
|
663
|
+
endpoint: typeof g.endpoint === "string" ? g.endpoint : "http://127.0.0.1:8877"
|
|
664
|
+
};
|
|
665
|
+
} catch {
|
|
666
|
+
return { on: false, endpoint: "http://127.0.0.1:8877" };
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
function jaccard(a, b) {
|
|
670
|
+
const ta = new Set(a.split(/\s+/).filter(Boolean));
|
|
671
|
+
const tb = new Set(b.split(/\s+/).filter(Boolean));
|
|
672
|
+
if (!ta.size || !tb.size) return 0;
|
|
673
|
+
let inter = 0;
|
|
674
|
+
for (const t of ta) if (tb.has(t)) inter++;
|
|
675
|
+
return inter / (ta.size + tb.size - inter);
|
|
676
|
+
}
|
|
677
|
+
function registerToolfaceHook(api, _cfg) {
|
|
678
|
+
api.on(
|
|
679
|
+
"before_prompt_build",
|
|
680
|
+
async (event, ctx) => {
|
|
681
|
+
const gate = gateState();
|
|
682
|
+
if (!gate.on) return;
|
|
683
|
+
const sig = String(event?.prompt ?? "").slice(0, 4e3);
|
|
684
|
+
const sid = String(ctx?.sessionId ?? ctx?.sessionKey ?? "default");
|
|
685
|
+
const cached = faceCache.get(sid);
|
|
686
|
+
if (cached && jaccard(sig, cached.sig) >= 0.3) return { toolsAllow: cached.face };
|
|
687
|
+
const ac = new AbortController();
|
|
688
|
+
const timer = setTimeout(() => ac.abort(), 400);
|
|
689
|
+
try {
|
|
690
|
+
const res = await fetch(gate.endpoint.replace(/\/$/, "") + "/toolface", {
|
|
691
|
+
method: "POST",
|
|
692
|
+
headers: { "content-type": "application/json" },
|
|
693
|
+
body: JSON.stringify({ signature: sig }),
|
|
694
|
+
signal: ac.signal
|
|
695
|
+
});
|
|
696
|
+
const body = await res.json();
|
|
697
|
+
const face = body?.projected;
|
|
698
|
+
if (!res.ok || !Array.isArray(face) || face.length === 0) return;
|
|
699
|
+
if (faceCache.size > 200) faceCache.clear();
|
|
700
|
+
faceCache.set(sid, { face, sig });
|
|
701
|
+
return { toolsAllow: face };
|
|
702
|
+
} catch {
|
|
703
|
+
return;
|
|
704
|
+
} finally {
|
|
705
|
+
clearTimeout(timer);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// index.ts
|
|
712
|
+
var index_default = definePluginEntry({
|
|
713
|
+
id: "memgate",
|
|
714
|
+
name: "MemGate",
|
|
715
|
+
description: "Three-layer memory (hot/warm/cold) + governance gate tools, bridged to the Python single-source.",
|
|
716
|
+
register(api) {
|
|
717
|
+
const cfg = api.pluginConfig ?? {};
|
|
718
|
+
registerGovernanceTools(api, cfg);
|
|
719
|
+
registerGovernanceContextEngine(api, cfg);
|
|
720
|
+
registerGovernanceMemory(api, cfg);
|
|
721
|
+
registerToolfaceHook(api, cfg);
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
export {
|
|
725
|
+
index_default as default
|
|
726
|
+
};
|