-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhooks.ts
More file actions
161 lines (142 loc) · 4.7 KB
/
hooks.ts
File metadata and controls
161 lines (142 loc) · 4.7 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
/**
* Supermemory Hooks
*
* Lifecycle hook handlers for automatic memory operations:
* - before_agent_start: Auto-recall relevant memories into context
* - after_compaction: Store compacted summaries as long-term memory
*/
import type { SupermemoryClient } from "./supermemory-client.js";
import type { SupermemoryConfig } from "./types.js";
import { resolveContainerTag } from "./types.js";
import { sanitizeQuery } from "./sanitize-query.js";
export type HookContext = {
client: SupermemoryClient | null;
config: SupermemoryConfig;
logger: {
info: (msg: string) => void;
warn: (msg: string) => void;
error: (msg: string) => void;
};
};
/**
* Create the before_agent_start hook handler for auto-recall.
* Queries Supermemory search API and injects relevant memories into context.
*/
export function createBeforeAgentStartHandler(ctx: HookContext) {
return async (
event: { prompt: string; messages?: unknown[] },
hookCtx: { agentId?: string; sessionKey?: string },
): Promise<{ prependContext?: string } | void> => {
// Skip if client not configured (apiKey missing)
if (!ctx.client) {
return;
}
// Skip if auto-recall is disabled or mode is off
if (!ctx.config.autoRecall || ctx.config.mode === "off") {
return;
}
// Skip empty or very short prompts
if (!event.prompt || event.prompt.length < 5) {
return;
}
// Sanitize the prompt to remove channel metadata and artifacts
const sanitizedQuery = sanitizeQuery(event.prompt);
if (!sanitizedQuery || sanitizedQuery.length < 3) {
return;
}
// Resolve container tag based on scope configuration
const containerTag = resolveContainerTag({
config: ctx.config,
agentId: hookCtx.agentId,
sessionKey: hookCtx.sessionKey,
});
try {
const results = await ctx.client.search({
q: sanitizedQuery,
containerTag,
limit: 5,
chunkThreshold: ctx.config.threshold,
});
if (results.length === 0) {
return;
}
const memoryContext = results
.slice(0, 5)
.map((r) => `- ${r.content}`)
.join("\n");
ctx.logger.info(`supermemory: injecting ${results.length} memories into context`);
return {
prependContext:
`<supermemory-context>\n` +
`The following memories from Supermemory may be relevant:\n${memoryContext}\n` +
`</supermemory-context>`,
};
} catch (err) {
ctx.logger.warn(`supermemory: auto-recall failed: ${String(err)}`);
return;
}
};
}
/**
* Create the after_compaction hook handler for memory storage.
* Stores compacted summaries as long-term memories in Supermemory.
*/
export function createAfterCompactionHandler(ctx: HookContext) {
return async (
event: {
messageCount: number;
tokenCount?: number;
compactedCount: number;
summary: string;
sessionId?: string;
sessionKey?: string;
},
hookCtx: { agentId?: string; sessionKey?: string },
): Promise<void> => {
ctx.logger.info(
`supermemory: after_compaction fired (client: ${!!ctx.client}, mode: ${ctx.config.mode}, ` +
`summaryLen: ${event.summary?.length ?? 0}, compacted: ${event.compactedCount})`,
);
// Skip if client not configured (apiKey missing)
if (!ctx.client) {
ctx.logger.warn("supermemory: after_compaction skipped — no client");
return;
}
// Skip if mode is off
if (ctx.config.mode === "off") {
return;
}
// Skip if no summary provided
if (!event.summary || event.summary.trim().length === 0) {
ctx.logger.warn("supermemory: after_compaction called without summary, skipping storage");
return;
}
try {
// Resolve container tag based on scope configuration
const containerTag = resolveContainerTag({
config: ctx.config,
agentId: hookCtx.agentId,
sessionKey: event.sessionKey ?? hookCtx.sessionKey,
});
// Store the compacted summary as a document
const result = await ctx.client.add({
content: event.summary,
containerTag,
metadata: {
source: "clawdbot-compaction",
sessionId: event.sessionId,
sessionKey: event.sessionKey,
compactedCount: event.compactedCount,
timestamp: new Date().toISOString(),
},
});
ctx.logger.info(
`supermemory: stored compaction summary (${event.compactedCount} messages compacted, ` +
`id: ${result.id}, status: ${result.status})`,
);
} catch (err) {
// Fire-and-forget: log error but don't block compaction
ctx.logger.error(`supermemory: failed to store compaction summary: ${String(err)}`);
}
};
}