forked from plastic-labs/openclaw-honcho
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.ts
More file actions
284 lines (250 loc) · 9.94 KB
/
Copy pathruntime.ts
File metadata and controls
284 lines (250 loc) · 9.94 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
// @ts-ignore - resolved by openclaw runtime
import type { MemoryPluginCapability } from "openclaw/plugin-sdk/core";
import { isManagedHonchoCloud, type PluginState } from "./state.js";
const DEFAULT_SEARCH_RESULTS = 10;
const MAX_SEARCH_RESULTS = 50;
const SESSION_TRANSCRIPT_CACHE_TTL_MS = 5_000;
type TranscriptCacheEntry = {
expiresAt: number;
promise: Promise<string>;
};
const transcriptCaches = new WeakMap<PluginState, Map<string, TranscriptCacheEntry>>();
/** Convert a Honcho session id into the generic memory tool path shape. */
function normalizeSessionPath(sessionId: string): string {
return `sessions/${sessionId}.txt`;
}
/** Parse the synthetic transcript path used by memory_get back into a session id. */
function parseSessionPath(relPath: string): string | null {
const m = /^sessions\/(.+)\.txt$/.exec(relPath);
return m ? m[1] : null;
}
/** Match the active Honcho session for scoped reads/searches. New-scheme ids
* embed a per-session hash suffix, so no real id is a prefix of another and
* scope-checking collapses to equality. */
function matchesSessionScope(sessionId: string, activeSessionKey: string): boolean {
return sessionId === activeSessionKey;
}
/** Return only the requested line window from a synthesized Honcho transcript. */
function sliceLines(text: string, from = 1, lines?: number): string {
const all = text.split(/\r?\n/);
const start = Math.max(1, from) - 1;
const end = lines == null ? all.length : Math.min(all.length, start + Math.max(0, lines));
return all.slice(start, end).join("\n");
}
/** Reconstruct a readable session transcript from Honcho session context data. */
async function fetchSessionTranscript(
state: PluginState,
agentId: string,
sessionId: string
): Promise<string> {
await state.ensureInitialized();
const participantPeer = await state.resolveSessionParticipantPeer(sessionId);
const agentPeer = await state.getAgentPeer(agentId);
const session = await state.honcho.session(sessionId);
const context = await session.context({
summary: true,
tokens: 20000,
peerTarget: participantPeer,
peerPerspective: agentPeer,
});
const lines: string[] = [];
if (context.summary?.content) {
lines.push("# Summary", context.summary.content, "");
}
for (const msg of context.messages ?? []) {
const speaker =
msg.peerId === participantPeer.id
? "User"
: msg.peerId === agentPeer.id
? `Agent(${agentId})`
: state.isParticipantPeerId(msg.peerId)
? `User(${msg.peerId})`
: `Peer(${msg.peerId})`;
const ts = msg.createdAt ? ` ${msg.createdAt}` : "";
lines.push(`## ${speaker}${ts}`, msg.content ?? "", "");
}
return `${lines.join("\n").trimEnd()}\n`;
}
function buildSessionTranscript(
state: PluginState,
agentId: string,
sessionId: string,
): Promise<string> {
const cache = transcriptCaches.get(state) ?? new Map<string, TranscriptCacheEntry>();
transcriptCaches.set(state, cache);
const cacheKey = `${agentId}\0${sessionId}`;
const now = Date.now();
const cached = cache.get(cacheKey);
if (cached && cached.expiresAt > now) return cached.promise;
const promise = fetchSessionTranscript(state, agentId, sessionId);
cache.set(cacheKey, { expiresAt: now + SESSION_TRANSCRIPT_CACHE_TTL_MS, promise });
promise.catch(() => {
const current = cache.get(cacheKey);
if (current?.promise === promise) cache.delete(cacheKey);
});
return promise;
}
/** Best-effort map a matched snippet back to transcript line numbers for memory_search. */
function findSnippetLineRange(transcript: string, snippet: string): { startLine: number; endLine: number } {
const transcriptLines = transcript.split(/\r?\n/);
const snippetLines = snippet.split(/\r?\n/);
if (!snippet.trim()) {
return { startLine: 1, endLine: 1 };
}
for (let i = 0; i <= transcriptLines.length - snippetLines.length; i += 1) {
let matches = true;
for (let j = 0; j < snippetLines.length; j += 1) {
if (transcriptLines[i + j] !== snippetLines[j]) {
matches = false;
break;
}
}
if (matches) {
return { startLine: i + 1, endLine: i + snippetLines.length };
}
}
const firstNeedle = snippetLines.find((line) => line.trim().length > 0);
if (firstNeedle) {
const idx = transcriptLines.findIndex((line) => line.includes(firstNeedle));
if (idx >= 0) {
return {
startLine: idx + 1,
endLine: Math.min(transcriptLines.length, idx + snippetLines.length),
};
}
}
return {
startLine: 1,
endLine: Math.min(Math.max(1, transcriptLines.length), Math.max(1, snippetLines.length)),
};
}
/**
* Build a Honcho-backed memory manager that satisfies OpenClaw's active-memory contract.
*
* The returned manager powers both the registered memory runtime and the direct
* memory_search / memory_get compatibility tools.
*/
export async function getHonchoMemorySearchManager(
state: PluginState,
params: { agentId?: string; sessionKey?: string } = {}
) {
const { agentId = state.resolveDefaultAgentId(), sessionKey: activeSessionKey } = params;
await state.ensureInitialized();
return {
manager: {
async search(query: string, opts: { maxResults?: number; crossSessionSearch?: boolean; sessionKey?: string } = {}) {
await state.ensureInitialized();
// The active-memory contract scopes per call (search opts.sessionKey);
// fall back to the key captured at manager creation for the legacy /
// passthrough-tool path.
const sessionKey = opts.sessionKey ?? activeSessionKey;
const participantPeer = sessionKey
? await state.resolveSessionParticipantPeer(sessionKey)
: await state.getParticipantPeer();
const requested = Number.isFinite(opts.maxResults)
? Number(opts.maxResults)
: DEFAULT_SEARCH_RESULTS;
const limit = Math.min(MAX_SEARCH_RESULTS, Math.max(1, Math.trunc(requested)));
const crossSession = opts.crossSessionSearch ?? state.cfg.crossSessionSearch;
const rawResults: Array<any> = crossSession || !sessionKey
? await participantPeer.search(query, { limit })
: await (
await state.honcho.session(sessionKey, { metadata: { agentId } })
).search(query, { limit });
const seen = new Set<string>();
const filtered: Array<any> = [];
for (const msg of rawResults) {
if (filtered.length >= limit) break;
const sessionId = typeof msg?.sessionId === "string" ? msg.sessionId : "";
if (!sessionId) continue;
const dedupeKey = `${sessionId}:${String(msg?.id ?? msg?.createdAt ?? msg?.content ?? "")}`;
if (seen.has(dedupeKey)) continue;
seen.add(dedupeKey);
filtered.push(msg);
}
const transcriptCache = new Map<string, Promise<string>>();
return Promise.all(
filtered.map(async (msg: any) => {
const snippet = typeof msg.content === "string" ? msg.content : "";
let transcriptPromise = transcriptCache.get(msg.sessionId);
if (!transcriptPromise) {
transcriptPromise = buildSessionTranscript(state, agentId, msg.sessionId);
transcriptCache.set(msg.sessionId, transcriptPromise);
}
const transcript = await transcriptPromise;
const { startLine, endLine } = findSnippetLineRange(transcript, snippet);
return {
path: normalizeSessionPath(msg.sessionId),
startLine,
endLine,
score: 1,
snippet,
source: "sessions" as const,
};
})
);
},
async readFile(params: { relPath: string; from?: number; lines?: number }) {
const sessionId = parseSessionPath(params.relPath);
if (!sessionId) {
throw new Error(`Unsupported Honcho memory path: ${params.relPath}`);
}
if (!state.cfg.crossSessionSearch && activeSessionKey && !matchesSessionScope(sessionId, activeSessionKey)) {
throw new Error(`Requested Honcho memory path is outside the active session: ${params.relPath}`);
}
const transcript = await buildSessionTranscript(state, agentId, sessionId);
return {
path: params.relPath,
text: sliceLines(transcript, params.from, params.lines),
};
},
status() {
return {
backend: "qmd" as const,
provider: isManagedHonchoCloud(state.cfg.baseUrl) ? "honcho" : "honcho-selfhosted",
model: "n/a",
sources: ["sessions" as const],
custom: {
searchMode: "semantic",
workspaceId: state.cfg.workspaceId,
baseUrl: state.cfg.baseUrl,
},
};
},
async probeEmbeddingAvailability() {
return { ok: true };
},
async probeVectorAvailability() {
return true;
},
},
};
}
/** Resolve the memory backend descriptor expected by the OpenClaw memory slot. */
export function resolveHonchoMemoryBackendConfig(
_params: { agentId?: string } = {},
) {
return {
backend: "qmd" as const,
qmd: {},
};
}
/** Build the Honcho adapter for OpenClaw's active memory capability.
*
* The current host contract creates a session-agnostic manager here and passes
* the active session key per call via `search(query, { sessionKey })`, so this
* adapter does not forward a session key at creation time. Session-scoped reads
* still flow through the memory_search / memory_get passthrough tools, which
* resolve the session key from their tool context. */
export function createHonchoMemoryRuntime(
state: PluginState,
): NonNullable<MemoryPluginCapability["runtime"]> {
return {
async getMemorySearchManager(params: { agentId?: string }) {
return getHonchoMemorySearchManager(state, { agentId: params.agentId });
},
resolveMemoryBackendConfig(params: { agentId?: string } = {}) {
return resolveHonchoMemoryBackendConfig(params);
},
};
}