-
-
Notifications
You must be signed in to change notification settings - Fork 76.2k
Expand file tree
/
Copy pathtools.shared.ts
More file actions
223 lines (210 loc) · 6.46 KB
/
tools.shared.ts
File metadata and controls
223 lines (210 loc) · 6.46 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
import {
listMemoryCorpusSupplements,
resolveMemorySearchConfig,
resolveSessionAgentIds,
type MemoryCorpusSearchResult,
type AnyAgentTool,
type OpenClawConfig,
} from "openclaw/plugin-sdk/memory-core-host-runtime-core";
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
import { Type } from "typebox";
type MemoryToolRuntime = typeof import("./tools.runtime.js");
type MemorySearchManagerResult = Awaited<
ReturnType<(typeof import("./memory/index.js"))["getMemorySearchManager"]>
>;
type MemoryToolOptions = {
config?: OpenClawConfig;
getConfig?: () => OpenClawConfig | undefined;
agentId?: string;
agentSessionKey?: string;
};
let memoryToolRuntimePromise: Promise<MemoryToolRuntime> | null = null;
export async function loadMemoryToolRuntime(): Promise<MemoryToolRuntime> {
memoryToolRuntimePromise ??= import("./tools.runtime.js");
return await memoryToolRuntimePromise;
}
export const MemorySearchSchema = Type.Object({
query: Type.String(),
maxResults: Type.Optional(Type.Number()),
minScore: Type.Optional(Type.Number()),
corpus: Type.Optional(
Type.Union([
Type.Literal("memory"),
Type.Literal("wiki"),
Type.Literal("all"),
Type.Literal("sessions"),
]),
),
});
export const MemoryGetSchema = Type.Object({
path: Type.String(),
from: Type.Optional(Type.Number()),
lines: Type.Optional(Type.Number()),
corpus: Type.Optional(
Type.Union([Type.Literal("memory"), Type.Literal("wiki"), Type.Literal("all")]),
),
});
function resolveMemoryToolContext(options: MemoryToolOptions) {
const cfg = options.getConfig?.() ?? options.config;
if (!cfg) {
return null;
}
const { sessionAgentId: agentId } = resolveSessionAgentIds({
sessionKey: options.agentSessionKey,
config: cfg,
agentId: options.agentId,
});
if (!resolveMemorySearchConfig(cfg, agentId)) {
return null;
}
return { cfg, agentId };
}
export async function getMemoryManagerContext(params: {
cfg: OpenClawConfig;
agentId: string;
}): Promise<
| {
manager: NonNullable<MemorySearchManagerResult["manager"]>;
}
| {
error: string | undefined;
}
> {
return await getMemoryManagerContextWithPurpose({ ...params, purpose: undefined });
}
export async function getMemoryManagerContextWithPurpose(params: {
cfg: OpenClawConfig;
agentId: string;
purpose?: "default" | "status" | "cli";
}): Promise<
| {
manager: NonNullable<MemorySearchManagerResult["manager"]>;
}
| {
error: string | undefined;
}
> {
const { getMemorySearchManager } = await loadMemoryToolRuntime();
const { manager, error } = await getMemorySearchManager({
cfg: params.cfg,
agentId: params.agentId,
purpose: params.purpose,
});
return manager ? { manager } : { error };
}
export function createMemoryTool(params: {
options: MemoryToolOptions;
label: string;
name: string;
description: string;
parameters: typeof MemorySearchSchema | typeof MemoryGetSchema;
execute: (ctx: { cfg: OpenClawConfig; agentId: string }) => AnyAgentTool["execute"];
}): AnyAgentTool | null {
const ctx = resolveMemoryToolContext(params.options);
if (!ctx) {
return null;
}
return {
label: params.label,
name: params.name,
description: params.description,
parameters: params.parameters,
execute: async (toolCallId, toolParams) => {
const latestCtx = resolveMemoryToolContext(params.options) ?? ctx;
return await params.execute(latestCtx)(toolCallId, toolParams);
},
};
}
export function buildMemorySearchUnavailableResult(error: string | undefined) {
const reason = (error ?? "memory search unavailable").trim() || "memory search unavailable";
const isQuotaError = /insufficient_quota|quota|429/.test(normalizeLowercaseStringOrEmpty(reason));
const warning = isQuotaError
? "Memory search is unavailable because the embedding provider quota is exhausted."
: "Memory search is unavailable due to an embedding/provider error.";
const action = isQuotaError
? "Top up or switch embedding provider, then retry memory_search."
: "Check embedding provider configuration and retry memory_search.";
return {
results: [],
disabled: true,
unavailable: true,
error: reason,
warning,
action,
debug: {
warning,
action,
error: reason,
},
};
}
export async function searchMemoryCorpusSupplements(params: {
query: string;
maxResults?: number;
agentSessionKey?: string;
corpus?: "memory" | "wiki" | "all" | "sessions";
}): Promise<MemoryCorpusSearchResult[]> {
if (params.corpus === "memory" || params.corpus === "sessions") {
return [];
}
const supplements = listMemoryCorpusSupplements();
if (supplements.length === 0) {
return [];
}
// Use allSettled so a single misbehaving supplement does not discard sibling
// results. Invariant: result ⊇ ⋃_{s succeeds} s.search(params).
const settled = await Promise.allSettled(
supplements.map(async (registration) => await registration.supplement.search(params)),
);
const results: MemoryCorpusSearchResult[] = [];
for (let i = 0; i < settled.length; i++) {
const outcome = settled[i];
if (outcome.status === "fulfilled") {
results.push(...outcome.value);
} else {
const pluginId = supplements[i]?.pluginId ?? "<unknown>";
console.warn(
`memory-core: corpus supplement "${pluginId}" search failed; sibling results preserved (${formatSupplementError(outcome.reason)}).`,
);
}
}
return results
.toSorted((left, right) => {
if (left.score !== right.score) {
return right.score - left.score;
}
return left.path.localeCompare(right.path);
})
.slice(0, Math.max(1, params.maxResults ?? 10));
}
function formatSupplementError(reason: unknown): string {
if (reason instanceof Error) {
return reason.message || reason.name || "Error";
}
if (typeof reason === "string") {
return reason;
}
try {
return JSON.stringify(reason);
} catch {
return String(reason);
}
}
export async function getMemoryCorpusSupplementResult(params: {
lookup: string;
fromLine?: number;
lineCount?: number;
agentSessionKey?: string;
corpus?: "memory" | "wiki" | "all" | "sessions";
}) {
if (params.corpus === "memory" || params.corpus === "sessions") {
return null;
}
for (const registration of listMemoryCorpusSupplements()) {
const result = await registration.supplement.get(params);
if (result) {
return result;
}
}
return null;
}