pi-mega-compact 0.9.2 → 0.10.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/README.md +3 -2
- package/dist/extensions/dashboard-server/api-contracts/endpoints.js +95 -47
- package/dist/extensions/dashboard-server/api-contracts/index.js +1 -1
- package/dist/extensions/dashboard-server/api-contracts/turns.js +10 -0
- package/dist/extensions/dashboard-server/api-contracts.test.js +3 -2
- package/dist/extensions/dashboard-server/routes-topics.js +87 -0
- package/dist/extensions/dashboard-server/routes-turns.js +251 -0
- package/dist/extensions/dashboard-server/routes.js +3 -1
- package/dist/extensions/dashboard-server/server.js +6 -2
- package/dist/extensions/mega-compact.js +10 -6
- package/dist/extensions/mega-config.js +4 -0
- package/dist/extensions/mega-events/agent-handlers.js +62 -49
- package/dist/extensions/mega-events/context-handler.js +48 -2
- package/dist/extensions/mega-events/session-handlers.js +24 -0
- package/dist/extensions/mega-metrics-cmds.js +90 -0
- package/dist/extensions/mega-pipeline/recall.js +47 -17
- package/dist/extensions/mega-topics-cmds.js +111 -0
- package/dist/extensions/mega-turn-store.js +110 -0
- package/dist/extensions/mega-turn-store.test.js +68 -0
- package/dist/src/config/turns.js +48 -0
- package/dist/src/fork.js +33 -0
- package/dist/src/fork.test.js +81 -0
- package/dist/src/intent.js +51 -0
- package/dist/src/intent.test.js +78 -0
- package/dist/src/metrics/index.js +4 -0
- package/dist/src/metrics/turns.js +118 -0
- package/dist/src/metrics/turns.test.js +152 -0
- package/dist/src/store/sqlite/raw-transcript.js +5 -3
- package/dist/src/store/sqlite.dbmirror.test.js +9 -0
- package/dist/src/store/turns/connection.js +123 -0
- package/dist/src/store/turns/contract-compliance.test.js +428 -0
- package/dist/src/store/turns/index.js +31 -0
- package/dist/src/store/turns/memory-store.js +357 -0
- package/dist/src/store/turns/memory-store.test.js +9 -0
- package/dist/src/store/turns/migrations.js +178 -0
- package/dist/src/store/turns/migrations.test.js +138 -0
- package/dist/src/store/turns/schema.js +115 -0
- package/dist/src/store/turns/sqlite-store.js +455 -0
- package/dist/src/store/turns/sqlite-store.test.js +144 -0
- package/dist/src/store/turns/types.js +16 -0
- package/dist/src/topics/cluster.js +141 -0
- package/dist/src/topics/cluster.test.js +150 -0
- package/dist/src/topics/index.js +6 -0
- package/dist/src/topics/kselection.js +142 -0
- package/dist/src/topics/labels.js +56 -0
- package/dist/src/topics/store.js +119 -0
- package/dist/src/topics/store.test.js +117 -0
- package/dist/src/topics/types.js +8 -0
- package/dist/src/wiki.js +133 -0
- package/dist/src/wiki.test.js +171 -0
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-QPo46Pwg.js → AchievementTiles-DUulvXUY.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-QPo46Pwg.js.map → AchievementTiles-DUulvXUY.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{AchievementsTab-BDJxRXRY.js → AchievementsTab-Dx0YtCNf.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AchievementsTab-BDJxRXRY.js.map → AchievementsTab-Dx0YtCNf.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{CacheTab-CUMqXQjd.js → CacheTab-DtkaUo1v.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{CacheTab-CUMqXQjd.js.map → CacheTab-DtkaUo1v.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{ConfigTab-j1dRzurG.js → ConfigTab-CLa4KfiZ.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ConfigTab-j1dRzurG.js.map → ConfigTab-CLa4KfiZ.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{EventsTab-CMglXK4p.js → EventsTab-Q6tEIBBi.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-CMglXK4p.js.map → EventsTab-Q6tEIBBi.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{GameTab-fpaDoyxi.js → GameTab-Hq7GNWSY.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{GameTab-fpaDoyxi.js.map → GameTab-Hq7GNWSY.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MetricsTab-CWG2crG_.js → MetricsTab-BtmBV6lU.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-CWG2crG_.js.map → MetricsTab-BtmBV6lU.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{OverviewTab-BaV2D2nf.js → OverviewTab-CL10PwVU.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{OverviewTab-BaV2D2nf.js.map → OverviewTab-CL10PwVU.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{ReposTab-C-0kuZ_0.js → ReposTab-DAwANwbI.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ReposTab-C-0kuZ_0.js.map → ReposTab-DAwANwbI.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{SessionsTab-CSYhddCA.js → SessionsTab-Ec08TZRQ.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-CSYhddCA.js.map → SessionsTab-Ec08TZRQ.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dy4KRjSM.js → TimeSavedCard-COb8dpTy.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dy4KRjSM.js.map → TimeSavedCard-COb8dpTy.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/TopicsTab-kvX3F3dY.js +2 -0
- package/extensions/dashboard-client/dist/assets/TopicsTab-kvX3F3dY.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/TurnsTab-CCUE73Aa.js +2 -0
- package/extensions/dashboard-client/dist/assets/TurnsTab-CCUE73Aa.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{index-D_WtU2TV.js → index-UMrussFX.js} +10 -10
- package/extensions/dashboard-client/dist/assets/index-UMrussFX.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{index-og3ghxyY.css → index-gn66lYD2.css} +1 -1
- package/extensions/dashboard-client/dist/assets/{useSSE-C9yVJlGP.js → useSSE-BDHZ7CeS.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-C9yVJlGP.js.map → useSSE-BDHZ7CeS.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +2 -2
- package/extensions/dashboard-client/src/App.tsx +10 -2
- package/extensions/dashboard-client/src/api/client.ts +84 -1
- package/extensions/dashboard-client/src/main.tsx +1 -0
- package/extensions/dashboard-client/src/styles/turns.css +142 -0
- package/extensions/dashboard-client/src/tabs/TopicsTab.tsx +185 -0
- package/extensions/dashboard-client/src/tabs/TurnsTab.tsx +326 -0
- package/extensions/dashboard-server/api-contracts/endpoints.ts +389 -291
- package/extensions/dashboard-server/api-contracts/game-types.ts +141 -88
- package/extensions/dashboard-server/api-contracts/index.ts +153 -133
- package/extensions/dashboard-server/api-contracts/turns.ts +114 -0
- package/extensions/dashboard-server/api-contracts.test.ts +920 -919
- package/extensions/dashboard-server/routes-topics.ts +119 -0
- package/extensions/dashboard-server/routes-turns.ts +282 -0
- package/extensions/dashboard-server/routes.ts +8 -1
- package/extensions/dashboard-server/server.ts +6 -2
- package/extensions/mega-compact.ts +75 -59
- package/extensions/mega-config.ts +232 -220
- package/extensions/mega-events/agent-handlers.ts +194 -151
- package/extensions/mega-events/context-handler.ts +50 -1
- package/extensions/mega-events/session-handlers.ts +23 -0
- package/extensions/mega-metrics-cmds.ts +114 -0
- package/extensions/mega-pipeline/recall.ts +215 -152
- package/extensions/mega-topics-cmds.ts +151 -0
- package/extensions/mega-turn-store.test.ts +108 -0
- package/extensions/mega-turn-store.ts +169 -0
- package/package.json +3 -1
- package/src/config/turns.ts +69 -0
- package/src/fork.test.ts +94 -0
- package/src/fork.ts +78 -0
- package/src/intent.test.ts +87 -0
- package/src/intent.ts +115 -0
- package/src/metrics/index.ts +9 -0
- package/src/metrics/turns.test.ts +165 -0
- package/src/metrics/turns.ts +201 -0
- package/src/store/sqlite/raw-transcript.ts +9 -3
- package/src/store/sqlite.dbmirror.test.ts +10 -0
- package/src/store/turns/connection.ts +137 -0
- package/src/store/turns/contract-compliance.test.ts +562 -0
- package/src/store/turns/index.ts +65 -0
- package/src/store/turns/memory-store.test.ts +15 -0
- package/src/store/turns/memory-store.ts +469 -0
- package/src/store/turns/migrations.test.ts +161 -0
- package/src/store/turns/migrations.ts +203 -0
- package/src/store/turns/schema.ts +158 -0
- package/src/store/turns/sqlite-store.test.ts +161 -0
- package/src/store/turns/sqlite-store.ts +656 -0
- package/src/store/turns/types.ts +181 -0
- package/src/topics/cluster.test.ts +176 -0
- package/src/topics/cluster.ts +191 -0
- package/src/topics/index.ts +18 -0
- package/src/topics/kselection.ts +182 -0
- package/src/topics/labels.ts +67 -0
- package/src/topics/store.test.ts +132 -0
- package/src/topics/store.ts +208 -0
- package/src/topics/types.ts +64 -0
- package/src/wiki.test.ts +217 -0
- package/src/wiki.ts +198 -0
- package/dist/extensions/openclaw-mega-compact.js +0 -291
- package/dist/src/minilm.js +0 -92
- package/dist/src/wordpiece.js +0 -129
- package/extensions/dashboard-client/dist/assets/index-D_WtU2TV.js.map +0 -1
|
@@ -1,291 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* openclaw-mega-compact — OpenClaw plugin adapter for the pi-mega-compact engine.
|
|
3
|
-
*
|
|
4
|
-
* Wires the pi-agnostic Trident engine (src/) into OpenClaw's plugin lifecycle:
|
|
5
|
-
* - Registers a CompactionProvider that replaces the built-in summarizeInStages.
|
|
6
|
-
* - Exposes `mega_status` and `mega_recall` tools for on-demand inspection.
|
|
7
|
-
* - Hooks into `before_compaction` / `after_compaction` for diagnostics.
|
|
8
|
-
*
|
|
9
|
-
* Design constraints:
|
|
10
|
-
* - NO imports from `@earendil-works/pi-coding-agent` or pi-agent-core.
|
|
11
|
-
* - The engine core (src/) is pi-agnostic; this file is the sole OpenClaw boundary.
|
|
12
|
-
* - No network at runtime — everything is local (stores + extractive summarizer).
|
|
13
|
-
*/
|
|
14
|
-
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
15
|
-
import { compactSession, setDefaultStore, } from "../src/engine.js";
|
|
16
|
-
import { recallAndInline } from "../src/recall.js";
|
|
17
|
-
import { VectorStore } from "../src/vectorStore.js";
|
|
18
|
-
// ---------------------------------------------------------------------------
|
|
19
|
-
// Constants
|
|
20
|
-
// ---------------------------------------------------------------------------
|
|
21
|
-
const PLUGIN_ID = "mega-compact";
|
|
22
|
-
const PLUGIN_LABEL = "Mega Compact (Trident)";
|
|
23
|
-
/** Default state directory for vector store persistence. */
|
|
24
|
-
const STATE_DIR = process.env.MEGA_COMPACT_STATE_DIR ?? undefined;
|
|
25
|
-
/** Minimum messages before we bother compacting. */
|
|
26
|
-
const MIN_MESSAGES_FOR_COMPACT = 6;
|
|
27
|
-
// ---------------------------------------------------------------------------
|
|
28
|
-
// Message conversion — OpenClaw unknown[] → EngineMessage[]
|
|
29
|
-
// ---------------------------------------------------------------------------
|
|
30
|
-
/**
|
|
31
|
-
* Best-effort conversion from OpenClaw's opaque message array to our
|
|
32
|
-
* EngineMessage shape. OpenClaw messages are typed as `unknown[]` so we
|
|
33
|
-
* handle whatever shape comes through gracefully.
|
|
34
|
-
*/
|
|
35
|
-
function toEngineMessages(messages) {
|
|
36
|
-
return messages.map((msg) => {
|
|
37
|
-
if (!msg || typeof msg !== "object") {
|
|
38
|
-
// Primitive fallback — treat as custom text.
|
|
39
|
-
return {
|
|
40
|
-
role: "custom",
|
|
41
|
-
text: String(msg ?? ""),
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
const m = msg;
|
|
45
|
-
const role = typeof m.role === "string" ? m.role : "custom";
|
|
46
|
-
// Normalize role to one of our four engine roles.
|
|
47
|
-
let engineRole;
|
|
48
|
-
switch (role) {
|
|
49
|
-
case "user":
|
|
50
|
-
engineRole = "user";
|
|
51
|
-
break;
|
|
52
|
-
case "assistant":
|
|
53
|
-
engineRole = "assistant";
|
|
54
|
-
break;
|
|
55
|
-
case "tool":
|
|
56
|
-
case "function":
|
|
57
|
-
engineRole = "tool";
|
|
58
|
-
break;
|
|
59
|
-
default:
|
|
60
|
-
engineRole = "custom";
|
|
61
|
-
break;
|
|
62
|
-
}
|
|
63
|
-
// Extract text content from common message shapes.
|
|
64
|
-
const text = typeof m.content === "string"
|
|
65
|
-
? m.content
|
|
66
|
-
: typeof m.text === "string"
|
|
67
|
-
? m.text
|
|
68
|
-
: Array.isArray(m.content)
|
|
69
|
-
? m.content
|
|
70
|
-
.filter((part) => part.type === "text" && typeof part.text === "string")
|
|
71
|
-
.map((part) => part.text)
|
|
72
|
-
.join("\n")
|
|
73
|
-
: "";
|
|
74
|
-
// Preserve tool metadata when present.
|
|
75
|
-
const toolName = typeof m.name === "string"
|
|
76
|
-
? m.name
|
|
77
|
-
: typeof m.toolName === "string"
|
|
78
|
-
? m.toolName
|
|
79
|
-
: undefined;
|
|
80
|
-
const input = typeof m.input === "string"
|
|
81
|
-
? m.input
|
|
82
|
-
: typeof m.arguments === "string"
|
|
83
|
-
? m.arguments
|
|
84
|
-
: m.arguments !== undefined
|
|
85
|
-
? JSON.stringify(m.arguments)
|
|
86
|
-
: undefined;
|
|
87
|
-
const output = typeof m.output === "string"
|
|
88
|
-
? m.output
|
|
89
|
-
: engineRole === "tool" && typeof m.content === "string"
|
|
90
|
-
? m.content
|
|
91
|
-
: undefined;
|
|
92
|
-
return { role: engineRole, text, toolName, input, output };
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
// ---------------------------------------------------------------------------
|
|
96
|
-
// Compaction provider
|
|
97
|
-
// ---------------------------------------------------------------------------
|
|
98
|
-
function createCompactionProvider(store) {
|
|
99
|
-
return {
|
|
100
|
-
id: PLUGIN_ID,
|
|
101
|
-
label: PLUGIN_LABEL,
|
|
102
|
-
async summarize({ messages, signal, compressionRatio, }) {
|
|
103
|
-
// Abort check — bail early if the caller cancelled.
|
|
104
|
-
if (signal?.aborted) {
|
|
105
|
-
throw new DOMException("Aborted", "AbortError");
|
|
106
|
-
}
|
|
107
|
-
const engineMessages = toEngineMessages(messages);
|
|
108
|
-
// Nothing meaningful to compact.
|
|
109
|
-
if (engineMessages.length < MIN_MESSAGES_FOR_COMPACT) {
|
|
110
|
-
return "";
|
|
111
|
-
}
|
|
112
|
-
// Map compression ratio → keepFrom boundary.
|
|
113
|
-
// compressionRatio=0.5 means "compact the oldest 50%".
|
|
114
|
-
// Default to compacting the oldest half if not specified.
|
|
115
|
-
const ratio = compressionRatio ?? 0.5;
|
|
116
|
-
const keepFrom = Math.max(MIN_MESSAGES_FOR_COMPACT, Math.floor(engineMessages.length * (1 - ratio)));
|
|
117
|
-
// Abort check after conversion (conversion is cheap but check anyway).
|
|
118
|
-
if (signal?.aborted) {
|
|
119
|
-
throw new DOMException("Aborted", "AbortError");
|
|
120
|
-
}
|
|
121
|
-
const sessionId = `openclaw-${Date.now()}`;
|
|
122
|
-
const input = {
|
|
123
|
-
sessionId,
|
|
124
|
-
messages: engineMessages,
|
|
125
|
-
keepFrom,
|
|
126
|
-
};
|
|
127
|
-
const result = compactSession(input, store);
|
|
128
|
-
if (result.skipped) {
|
|
129
|
-
return "";
|
|
130
|
-
}
|
|
131
|
-
return result.summary;
|
|
132
|
-
},
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
// ---------------------------------------------------------------------------
|
|
136
|
-
// Plugin entry
|
|
137
|
-
// ---------------------------------------------------------------------------
|
|
138
|
-
export default definePluginEntry({
|
|
139
|
-
id: PLUGIN_ID,
|
|
140
|
-
name: "Mega Compact",
|
|
141
|
-
description: "Layered, local, vector-backed context compressor (Trident engine) for OpenClaw compaction.",
|
|
142
|
-
register(api) {
|
|
143
|
-
const logger = api.logger;
|
|
144
|
-
// Resolve state directory — prefer plugin config override.
|
|
145
|
-
const pluginCfg = (api.pluginConfig ?? {});
|
|
146
|
-
const stateDir = typeof pluginCfg.stateDir === "string" && pluginCfg.stateDir.length > 0
|
|
147
|
-
? pluginCfg.stateDir
|
|
148
|
-
: STATE_DIR;
|
|
149
|
-
// Initialize vector store.
|
|
150
|
-
let store;
|
|
151
|
-
try {
|
|
152
|
-
store = new VectorStore({ stateDir });
|
|
153
|
-
setDefaultStore(store);
|
|
154
|
-
logger.info?.(`${PLUGIN_ID}: vector store initialized (stateDir=${stateDir ?? "default"})`);
|
|
155
|
-
}
|
|
156
|
-
catch (err) {
|
|
157
|
-
logger.error?.(`${PLUGIN_ID}: failed to init vector store:`, err);
|
|
158
|
-
return; // Hard bail — no point registering if store is broken.
|
|
159
|
-
}
|
|
160
|
-
// -----------------------------------------------------------------------
|
|
161
|
-
// Register compaction provider
|
|
162
|
-
// -----------------------------------------------------------------------
|
|
163
|
-
const provider = createCompactionProvider(store);
|
|
164
|
-
api.registerCompactionProvider(provider);
|
|
165
|
-
logger.info?.(`${PLUGIN_ID}: registered compaction provider "${provider.id}"`);
|
|
166
|
-
// -----------------------------------------------------------------------
|
|
167
|
-
// Hooks — before / after compaction diagnostics
|
|
168
|
-
// -----------------------------------------------------------------------
|
|
169
|
-
api.registerHook({
|
|
170
|
-
event: "before_compaction",
|
|
171
|
-
handler: async (ctx) => {
|
|
172
|
-
const msgCount = Array.isArray(ctx?.messages) ? ctx.messages.length : 0;
|
|
173
|
-
logger.info?.(`${PLUGIN_ID}: before_compaction — ${msgCount} messages in scope`);
|
|
174
|
-
},
|
|
175
|
-
});
|
|
176
|
-
api.registerHook({
|
|
177
|
-
event: "after_compaction",
|
|
178
|
-
handler: async (ctx) => {
|
|
179
|
-
const summaryLen = typeof ctx?.summary === "string" ? ctx.summary.length : 0;
|
|
180
|
-
logger.info?.(`${PLUGIN_ID}: after_compaction — summary ${summaryLen} chars`);
|
|
181
|
-
},
|
|
182
|
-
});
|
|
183
|
-
// -----------------------------------------------------------------------
|
|
184
|
-
// Tool: mega_status
|
|
185
|
-
// -----------------------------------------------------------------------
|
|
186
|
-
api.registerTool({
|
|
187
|
-
name: "mega_status",
|
|
188
|
-
description: "Show the current status of the mega-compact engine: vector store stats, checkpoint count, and recent compaction activity.",
|
|
189
|
-
parameters: {
|
|
190
|
-
type: "object",
|
|
191
|
-
properties: {
|
|
192
|
-
sessionId: {
|
|
193
|
-
type: "string",
|
|
194
|
-
description: "Optional session ID to scope stats to.",
|
|
195
|
-
},
|
|
196
|
-
},
|
|
197
|
-
additionalProperties: false,
|
|
198
|
-
},
|
|
199
|
-
handler: async (args) => {
|
|
200
|
-
const sessionId = args?.sessionId ?? "global";
|
|
201
|
-
try {
|
|
202
|
-
const stats = store.stats(sessionId);
|
|
203
|
-
const parts = [
|
|
204
|
-
`**Mega Compact Status**`,
|
|
205
|
-
`Session: ${sessionId}`,
|
|
206
|
-
`Checkpoints: ${stats.checkpointCount}`,
|
|
207
|
-
`Total tokens saved: ${stats.totalTokenEstimate}`,
|
|
208
|
-
`Last checkpoint: ${stats.lastCheckpointId ?? "—"}`,
|
|
209
|
-
`Injected count: ${stats.injectedCount}`,
|
|
210
|
-
`Dedup hit rate: ${(stats.dedupHitRate * 100).toFixed(0)}%`,
|
|
211
|
-
];
|
|
212
|
-
if (stats.lastSummary) {
|
|
213
|
-
parts.push(`\nLast summary (truncated):\n ${stats.lastSummary.slice(0, 120).replace(/\n/g, " ")}…`);
|
|
214
|
-
}
|
|
215
|
-
return { content: [{ type: "text", text: parts.join("\n") }] };
|
|
216
|
-
}
|
|
217
|
-
catch (err) {
|
|
218
|
-
return {
|
|
219
|
-
content: [{ type: "text", text: `Error reading mega-compact status: ${err}` }],
|
|
220
|
-
isError: true,
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
},
|
|
224
|
-
});
|
|
225
|
-
// -----------------------------------------------------------------------
|
|
226
|
-
// Tool: mega_recall
|
|
227
|
-
// -----------------------------------------------------------------------
|
|
228
|
-
api.registerTool({
|
|
229
|
-
name: "mega_recall",
|
|
230
|
-
description: "Recall and inline relevant context from the mega-compact vector store for the current session.",
|
|
231
|
-
parameters: {
|
|
232
|
-
type: "object",
|
|
233
|
-
properties: {
|
|
234
|
-
sessionId: {
|
|
235
|
-
type: "string",
|
|
236
|
-
description: "Session ID to recall context for.",
|
|
237
|
-
},
|
|
238
|
-
query: {
|
|
239
|
-
type: "string",
|
|
240
|
-
description: "Natural language query for relevant context.",
|
|
241
|
-
},
|
|
242
|
-
limit: {
|
|
243
|
-
type: "number",
|
|
244
|
-
description: "Max checkpoints to recall (default 3).",
|
|
245
|
-
},
|
|
246
|
-
},
|
|
247
|
-
required: ["sessionId", "query"],
|
|
248
|
-
additionalProperties: false,
|
|
249
|
-
},
|
|
250
|
-
handler: async (args) => {
|
|
251
|
-
const { sessionId, query, limit } = args;
|
|
252
|
-
if (!sessionId || !query) {
|
|
253
|
-
return {
|
|
254
|
-
content: [{ type: "text", text: "Both `sessionId` and `query` are required." }],
|
|
255
|
-
isError: true,
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
try {
|
|
259
|
-
const result = recallAndInline({ sessionId, query, limit: limit ?? 3, source: "command", skipInjected: false }, store);
|
|
260
|
-
if (result.toInject.length === 0) {
|
|
261
|
-
return {
|
|
262
|
-
content: [{ type: "text", text: "No relevant context found in the mega-compact store." }],
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
const parts = [
|
|
266
|
-
`**Recalled ${result.toInject.length} checkpoint(s):**`,
|
|
267
|
-
...result.report,
|
|
268
|
-
"",
|
|
269
|
-
"---",
|
|
270
|
-
result.block,
|
|
271
|
-
];
|
|
272
|
-
return { content: [{ type: "text", text: parts.join("\n") }] };
|
|
273
|
-
}
|
|
274
|
-
catch (err) {
|
|
275
|
-
return {
|
|
276
|
-
content: [{ type: "text", text: `Error during mega-recall: ${err}` }],
|
|
277
|
-
isError: true,
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
},
|
|
281
|
-
});
|
|
282
|
-
// -----------------------------------------------------------------------
|
|
283
|
-
// Cleanup on shutdown
|
|
284
|
-
// -----------------------------------------------------------------------
|
|
285
|
-
api.on("shutdown", () => {
|
|
286
|
-
logger.info?.(`${PLUGIN_ID}: shutting down — clearing default store`);
|
|
287
|
-
setDefaultStore(undefined);
|
|
288
|
-
});
|
|
289
|
-
logger.info?.(`${PLUGIN_ID}: plugin registered (tools: mega_status, mega_recall)`);
|
|
290
|
-
},
|
|
291
|
-
});
|
package/dist/src/minilm.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* minilm.ts — local MiniLM (all-MiniLM-L6-v2) sentence embedder (Sprint 12).
|
|
3
|
-
*
|
|
4
|
-
* Implements the `Embedder` interface so it drops into the existing VectorStore
|
|
5
|
-
* dedup cascade and search with no call-site changes. Inference is 100% local:
|
|
6
|
-
* the ONNX model + WordPiece vocab are on-disk artifacts fetched once by
|
|
7
|
-
* scripts/setup-minilm.mjs. There is NO network call at runtime (PREVENT-PI-004).
|
|
8
|
-
*
|
|
9
|
-
* Inputs (dynamic): input_ids, attention_mask, token_type_ids (int64).
|
|
10
|
-
* Output: last_hidden_state (batch, seq, 384). We mean-pool over non-padded
|
|
11
|
-
* tokens (attention_mask == 1) and L2-normalize → 384-dim unit vector.
|
|
12
|
-
*
|
|
13
|
-
* The ONNX session + tokenizer are loaded LAZILY on first embed() so the default
|
|
14
|
-
* TrigramEmbedder path (and its zero native-init cost) is untouched unless
|
|
15
|
-
* MEGACOMPACT_EMBEDDER=minilm is selected.
|
|
16
|
-
*/
|
|
17
|
-
import { join } from "node:path";
|
|
18
|
-
import { homedir } from "node:os";
|
|
19
|
-
import { existsSync } from "node:fs";
|
|
20
|
-
import { l2Normalize, awaitSync } from "./embedder.js";
|
|
21
|
-
import { WordPieceTokenizer } from "./wordpiece.js";
|
|
22
|
-
export const MINILM_DIM = 384;
|
|
23
|
-
export const MINILM_MAX_LEN = 256;
|
|
24
|
-
/** Resolve the model directory: MEGACOMPACT_MINILM_DIR > ./models/minilm > ~/.pi … */
|
|
25
|
-
function resolveModelDir() {
|
|
26
|
-
if (process.env.MEGACOMPACT_MINILM_DIR)
|
|
27
|
-
return process.env.MEGACOMPACT_MINILM_DIR;
|
|
28
|
-
// Repo-local vendored path (gitignored).
|
|
29
|
-
const local = join(process.cwd(), "models", "minilm");
|
|
30
|
-
if (existsSync(local))
|
|
31
|
-
return local;
|
|
32
|
-
return join(homedir(), ".pi", "agent", "extensions", "mega-compact", "models", "minilm");
|
|
33
|
-
}
|
|
34
|
-
export class MiniLMEmbedder {
|
|
35
|
-
dim = MINILM_DIM;
|
|
36
|
-
session = null;
|
|
37
|
-
tokenizer = null;
|
|
38
|
-
modelDir;
|
|
39
|
-
loadPromise = null;
|
|
40
|
-
constructor(modelDir = resolveModelDir()) {
|
|
41
|
-
this.modelDir = modelDir;
|
|
42
|
-
}
|
|
43
|
-
async ensureLoaded() {
|
|
44
|
-
if (this.session && this.tokenizer)
|
|
45
|
-
return;
|
|
46
|
-
if (this.loadPromise)
|
|
47
|
-
return this.loadPromise;
|
|
48
|
-
this.loadPromise = (async () => {
|
|
49
|
-
const ort = await import("onnxruntime-node");
|
|
50
|
-
const modelPath = join(this.modelDir, "model_quantized.onnx");
|
|
51
|
-
const vocabPath = join(this.modelDir, "vocab.txt");
|
|
52
|
-
if (!existsSync(modelPath) || !existsSync(vocabPath)) {
|
|
53
|
-
throw new Error(`MiniLM artifacts missing in ${this.modelDir}. Run: node scripts/setup-minilm.mjs`);
|
|
54
|
-
}
|
|
55
|
-
// 1 thread is plenty for a single short-region embed and bounds CPU.
|
|
56
|
-
this.session = await ort.InferenceSession.create(modelPath, {
|
|
57
|
-
executionProviders: ["cpu"],
|
|
58
|
-
graphOptimizationLevel: "all",
|
|
59
|
-
});
|
|
60
|
-
this.tokenizer = WordPieceTokenizer.fromVocabFile(vocabPath);
|
|
61
|
-
})();
|
|
62
|
-
return this.loadPromise;
|
|
63
|
-
}
|
|
64
|
-
embed(text) {
|
|
65
|
-
awaitSync(this.ensureLoaded());
|
|
66
|
-
const enc = this.tokenizer.encode(text, MINILM_MAX_LEN);
|
|
67
|
-
const n = enc.inputIds.length;
|
|
68
|
-
const BigInt64 = (arr) => arr.map((x) => BigInt(x));
|
|
69
|
-
const ort = awaitSync(import("onnxruntime-node"));
|
|
70
|
-
const tensors = {
|
|
71
|
-
input_ids: new ort.Tensor("int64", BigInt64(enc.inputIds), [1, n]),
|
|
72
|
-
attention_mask: new ort.Tensor("int64", BigInt64(enc.attentionMask), [1, n]),
|
|
73
|
-
token_type_ids: new ort.Tensor("int64", BigInt64(enc.tokenTypeIds), [1, n]),
|
|
74
|
-
};
|
|
75
|
-
const out = awaitSync(this.session.run(tensors));
|
|
76
|
-
const hidden = out.last_hidden_state.data;
|
|
77
|
-
// hidden shape: [1, n, 384]. Mean-pool over non-padded positions.
|
|
78
|
-
const pooled = new Array(MINILM_DIM).fill(0);
|
|
79
|
-
let count = 0;
|
|
80
|
-
for (let i = 0; i < n; i++) {
|
|
81
|
-
if (enc.attentionMask[i] === 0)
|
|
82
|
-
continue;
|
|
83
|
-
const base = i * MINILM_DIM;
|
|
84
|
-
for (let d = 0; d < MINILM_DIM; d++)
|
|
85
|
-
pooled[d] += hidden[base + d];
|
|
86
|
-
count++;
|
|
87
|
-
}
|
|
88
|
-
if (count === 0)
|
|
89
|
-
return l2Normalize(new Array(MINILM_DIM).fill(0));
|
|
90
|
-
return l2Normalize(pooled.map((x) => x / count));
|
|
91
|
-
}
|
|
92
|
-
}
|
package/dist/src/wordpiece.js
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* wordpiece.ts — a self-contained WordPiece tokenizer for BERT/MiniLM.
|
|
3
|
-
*
|
|
4
|
-
* Loads the canonical `vocab.txt` (bert-base-uncased, ~30K tokens) from disk and
|
|
5
|
-
* implements the standard uncased BERT preprocessing + greedy longest-match
|
|
6
|
-
* WordPiece segmentation. No native dependency, no network — the vocab file is a
|
|
7
|
-
* local artifact fetched once by scripts/setup-minilm.mjs (PREVENT-PI-004).
|
|
8
|
-
*
|
|
9
|
-
* This mirrors HuggingFace `BertTokenizer` closely enough for sentence-embedding
|
|
10
|
-
* use: lowercase, strip accents, split on whitespace + punctuation, then
|
|
11
|
-
* WordPiece each token with the `##` continuation convention. Special tokens
|
|
12
|
-
* [CLS]/[SEP] are added by the caller's encode().
|
|
13
|
-
*/
|
|
14
|
-
import { readFileSync, existsSync } from "node:fs";
|
|
15
|
-
const UNK = "[UNK]";
|
|
16
|
-
const CLS = "[CLS]";
|
|
17
|
-
const SEP = "[SEP]";
|
|
18
|
-
const PAD = "[PAD]";
|
|
19
|
-
const MAX_INPUT_CHARS_PER_WORD = 200;
|
|
20
|
-
export class WordPieceTokenizer {
|
|
21
|
-
vocab;
|
|
22
|
-
clsId;
|
|
23
|
-
sepId;
|
|
24
|
-
padId;
|
|
25
|
-
unkId;
|
|
26
|
-
constructor(vocab) {
|
|
27
|
-
this.vocab = vocab;
|
|
28
|
-
this.clsId = vocab.get(CLS) ?? 101;
|
|
29
|
-
this.sepId = vocab.get(SEP) ?? 102;
|
|
30
|
-
this.padId = vocab.get(PAD) ?? 0;
|
|
31
|
-
this.unkId = vocab.get(UNK) ?? 100;
|
|
32
|
-
}
|
|
33
|
-
/** Build a tokenizer from a vocab.txt file (one token per line, index = line). */
|
|
34
|
-
static fromVocabFile(path) {
|
|
35
|
-
if (!existsSync(path)) {
|
|
36
|
-
throw new Error(`WordPiece vocab not found at ${path}. Run: node scripts/setup-minilm.mjs`);
|
|
37
|
-
}
|
|
38
|
-
const lines = readFileSync(path, "utf-8").split("\n");
|
|
39
|
-
const vocab = new Map();
|
|
40
|
-
for (let i = 0; i < lines.length; i++) {
|
|
41
|
-
const tok = lines[i].replace(/\r$/, "");
|
|
42
|
-
if (tok.length > 0 || i < lines.length - 1)
|
|
43
|
-
vocab.set(tok, i);
|
|
44
|
-
}
|
|
45
|
-
return new WordPieceTokenizer(vocab);
|
|
46
|
-
}
|
|
47
|
-
/** Uncased BERT basic tokenization: lowercase, strip accents, split on ws+punct. */
|
|
48
|
-
basicTokenize(text) {
|
|
49
|
-
// NFD + strip combining marks (accent removal), then lowercase.
|
|
50
|
-
const cleaned = text
|
|
51
|
-
.normalize("NFD")
|
|
52
|
-
.replace(/[̀-ͯ]/g, "")
|
|
53
|
-
.toLowerCase();
|
|
54
|
-
const tokens = [];
|
|
55
|
-
let buf = "";
|
|
56
|
-
const flush = () => {
|
|
57
|
-
if (buf.length > 0) {
|
|
58
|
-
tokens.push(buf);
|
|
59
|
-
buf = "";
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
for (const ch of cleaned) {
|
|
63
|
-
if (/\s/.test(ch)) {
|
|
64
|
-
flush();
|
|
65
|
-
}
|
|
66
|
-
else if (/[!-/:-@[-`{-~¡-¿]/.test(ch)) {
|
|
67
|
-
// Punctuation becomes its own token.
|
|
68
|
-
flush();
|
|
69
|
-
tokens.push(ch);
|
|
70
|
-
}
|
|
71
|
-
else {
|
|
72
|
-
buf += ch;
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
flush();
|
|
76
|
-
return tokens;
|
|
77
|
-
}
|
|
78
|
-
/** Greedy longest-match WordPiece for a single word. */
|
|
79
|
-
wordpiece(word) {
|
|
80
|
-
if (word.length > MAX_INPUT_CHARS_PER_WORD)
|
|
81
|
-
return [UNK];
|
|
82
|
-
const pieces = [];
|
|
83
|
-
let start = 0;
|
|
84
|
-
while (start < word.length) {
|
|
85
|
-
let end = word.length;
|
|
86
|
-
let cur = null;
|
|
87
|
-
while (start < end) {
|
|
88
|
-
let sub = word.slice(start, end);
|
|
89
|
-
if (start > 0)
|
|
90
|
-
sub = "##" + sub;
|
|
91
|
-
if (this.vocab.has(sub)) {
|
|
92
|
-
cur = sub;
|
|
93
|
-
break;
|
|
94
|
-
}
|
|
95
|
-
end--;
|
|
96
|
-
}
|
|
97
|
-
if (cur === null)
|
|
98
|
-
return [UNK]; // any unmatchable piece → whole word is UNK
|
|
99
|
-
pieces.push(cur);
|
|
100
|
-
start = end;
|
|
101
|
-
}
|
|
102
|
-
return pieces;
|
|
103
|
-
}
|
|
104
|
-
/** Tokenize text into WordPiece token strings (no special tokens). */
|
|
105
|
-
tokenize(text) {
|
|
106
|
-
const out = [];
|
|
107
|
-
for (const word of this.basicTokenize(text)) {
|
|
108
|
-
for (const piece of this.wordpiece(word))
|
|
109
|
-
out.push(piece);
|
|
110
|
-
}
|
|
111
|
-
return out;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Encode text into model inputs with [CLS]…[SEP], truncated to `maxLen`.
|
|
115
|
-
* attention_mask is all 1s (no padding for single-sequence inference).
|
|
116
|
-
*/
|
|
117
|
-
encode(text, maxLen = 256) {
|
|
118
|
-
const pieces = this.tokenize(text).slice(0, Math.max(0, maxLen - 2));
|
|
119
|
-
const inputIds = [this.clsId];
|
|
120
|
-
for (const p of pieces)
|
|
121
|
-
inputIds.push(this.vocab.get(p) ?? this.unkId);
|
|
122
|
-
inputIds.push(this.sepId);
|
|
123
|
-
return {
|
|
124
|
-
inputIds,
|
|
125
|
-
attentionMask: inputIds.map(() => 1),
|
|
126
|
-
tokenTypeIds: inputIds.map(() => 0),
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
}
|