|
| 1 | +import { runTasksWithConcurrency } from "openclaw/plugin-sdk/concurrency-runtime"; |
| 2 | +import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime"; |
| 3 | +import { |
| 4 | + listMemoryCorpusSupplements, |
| 5 | + type MemoryCorpusSearchResult, |
| 6 | +} from "openclaw/plugin-sdk/memory-core-host-runtime-core"; |
| 7 | +import { |
| 8 | + DEFAULT_MEMORY_SEARCH_TIMEOUT_MS, |
| 9 | + resolveMemorySearchAbortError, |
| 10 | +} from "./memory/search-deadline.js"; |
| 11 | + |
| 12 | +type MemoryCorpus = "memory" | "wiki"; |
| 13 | +type MemorySupplement = ReturnType<typeof listMemoryCorpusSupplements>[number]; |
| 14 | +type MemorySupplementGetResult = NonNullable< |
| 15 | + Awaited<ReturnType<MemorySupplement["supplement"]["get"]>> |
| 16 | +>; |
| 17 | +type MemorySupplementReadResult = Omit<MemorySupplementGetResult, "content"> & { |
| 18 | + status: "ok"; |
| 19 | + text: string; |
| 20 | +}; |
| 21 | + |
| 22 | +export type MemoryCorpusAttempt<T> = |
| 23 | + | { corpus: MemoryCorpus; outcome: "ok"; value: T } |
| 24 | + | { corpus: MemoryCorpus; outcome: "unavailable"; value: T; error: string } |
| 25 | + | { corpus: MemoryCorpus; outcome: "not-registered" }; |
| 26 | + |
| 27 | +export function unavailableMemoryCorpus<T>( |
| 28 | + corpus: MemoryCorpus, |
| 29 | + value: T, |
| 30 | + error: unknown, |
| 31 | +): MemoryCorpusAttempt<T> { |
| 32 | + return { corpus, outcome: "unavailable", value, error: formatErrorMessage(error) }; |
| 33 | +} |
| 34 | + |
| 35 | +async function raceMemoryCorpusSignal<T>(signal: AbortSignal, task: Promise<T>): Promise<T> { |
| 36 | + if (signal.aborted) { |
| 37 | + throw resolveMemorySearchAbortError(signal); |
| 38 | + } |
| 39 | + let removeAbort = () => {}; |
| 40 | + const aborted = new Promise<never>((_resolve, reject) => { |
| 41 | + const onAbort = () => reject(resolveMemorySearchAbortError(signal)); |
| 42 | + signal.addEventListener("abort", onAbort, { once: true }); |
| 43 | + removeAbort = () => signal.removeEventListener("abort", onAbort); |
| 44 | + }); |
| 45 | + try { |
| 46 | + return await Promise.race([task, aborted]); |
| 47 | + } finally { |
| 48 | + removeAbort(); |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +export async function attemptMemoryCorpus<T>(params: { |
| 53 | + corpus: MemoryCorpus; |
| 54 | + signal: AbortSignal; |
| 55 | + unavailableValue: T; |
| 56 | + run: () => Promise<T>; |
| 57 | +}): Promise<MemoryCorpusAttempt<T>> { |
| 58 | + try { |
| 59 | + return { |
| 60 | + corpus: params.corpus, |
| 61 | + outcome: "ok", |
| 62 | + value: await raceMemoryCorpusSignal(params.signal, params.run()), |
| 63 | + }; |
| 64 | + } catch (error) { |
| 65 | + return unavailableMemoryCorpus(params.corpus, params.unavailableValue, error); |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +export async function runMemoryCorpusDeadline<T>(params: { |
| 70 | + operation: "memory_search" | "memory_get"; |
| 71 | + parentSignal?: AbortSignal; |
| 72 | + run: (signal: AbortSignal) => Promise<T>; |
| 73 | +}): Promise<T> { |
| 74 | + if (params.parentSignal?.aborted) { |
| 75 | + throw resolveMemorySearchAbortError(params.parentSignal); |
| 76 | + } |
| 77 | + const controller = new AbortController(); |
| 78 | + const timer = setTimeout(() => { |
| 79 | + controller.abort( |
| 80 | + new Error(`${params.operation} timed out after ${DEFAULT_MEMORY_SEARCH_TIMEOUT_MS / 1000}s`), |
| 81 | + ); |
| 82 | + }, DEFAULT_MEMORY_SEARCH_TIMEOUT_MS); |
| 83 | + timer.unref?.(); |
| 84 | + const onParentAbort = () => controller.abort(resolveMemorySearchAbortError(params.parentSignal!)); |
| 85 | + params.parentSignal?.addEventListener("abort", onParentAbort, { once: true }); |
| 86 | + try { |
| 87 | + const result = await params.run(controller.signal); |
| 88 | + if (params.parentSignal?.aborted) { |
| 89 | + throw resolveMemorySearchAbortError(params.parentSignal); |
| 90 | + } |
| 91 | + return result; |
| 92 | + } finally { |
| 93 | + clearTimeout(timer); |
| 94 | + params.parentSignal?.removeEventListener("abort", onParentAbort); |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +export function composeMemoryCorpusMetadata( |
| 99 | + attempts: readonly MemoryCorpusAttempt<unknown>[], |
| 100 | + extraWarnings: readonly string[] = [], |
| 101 | +) { |
| 102 | + const ordered = attempts.toSorted( |
| 103 | + (left, right) => Number(left.corpus === "wiki") - Number(right.corpus === "wiki"), |
| 104 | + ); |
| 105 | + const warnings = ordered.flatMap((attempt) => { |
| 106 | + if (attempt.outcome === "ok") { |
| 107 | + return []; |
| 108 | + } |
| 109 | + const label = attempt.corpus === "memory" ? "Memory" : "Wiki"; |
| 110 | + return [ |
| 111 | + attempt.outcome === "not-registered" |
| 112 | + ? `${label} corpus is not registered; results do not cover that requested corpus.` |
| 113 | + : `${label} corpus unavailable: ${attempt.error}`, |
| 114 | + ]; |
| 115 | + }); |
| 116 | + warnings.push(...extraWarnings); |
| 117 | + const errors = ordered.flatMap((attempt) => |
| 118 | + attempt.outcome === "unavailable" ? [attempt.error] : [], |
| 119 | + ); |
| 120 | + return { |
| 121 | + corpora: ordered.map((attempt) => |
| 122 | + attempt.outcome === "unavailable" |
| 123 | + ? { corpus: attempt.corpus, outcome: attempt.outcome, error: attempt.error } |
| 124 | + : { corpus: attempt.corpus, outcome: attempt.outcome }, |
| 125 | + ), |
| 126 | + ...(warnings.length > 0 ? { warning: warnings.join(" ") } : {}), |
| 127 | + ...(errors.length > 0 ? { error: errors.join("; ") } : {}), |
| 128 | + }; |
| 129 | +} |
| 130 | + |
| 131 | +async function settleMemorySupplements<T>(params: { |
| 132 | + signal: AbortSignal; |
| 133 | + run: (registration: MemorySupplement) => Promise<T>; |
| 134 | + merge: (results: T[]) => T; |
| 135 | +}): Promise<MemoryCorpusAttempt<T>> { |
| 136 | + const supplements = listMemoryCorpusSupplements().toSorted((left, right) => |
| 137 | + left.pluginId.localeCompare(right.pluginId), |
| 138 | + ); |
| 139 | + if (supplements.length === 0) { |
| 140 | + return { corpus: "wiki", outcome: "not-registered" }; |
| 141 | + } |
| 142 | + const failures: Array<{ pluginId: string; error: string }> = []; |
| 143 | + const completed: Array<T | undefined> = Array.from({ length: supplements.length }); |
| 144 | + try { |
| 145 | + await raceMemoryCorpusSignal( |
| 146 | + params.signal, |
| 147 | + runTasksWithConcurrency({ |
| 148 | + tasks: supplements.map((registration, index) => async () => { |
| 149 | + const result = await params.run(registration); |
| 150 | + completed[index] = result; |
| 151 | + return result; |
| 152 | + }), |
| 153 | + limit: Math.min(4, supplements.length), |
| 154 | + onTaskError: (error, index) => { |
| 155 | + failures.push({ |
| 156 | + pluginId: supplements[index]!.pluginId, |
| 157 | + error: formatErrorMessage(error), |
| 158 | + }); |
| 159 | + }, |
| 160 | + }), |
| 161 | + ); |
| 162 | + } catch (error) { |
| 163 | + return unavailableMemoryCorpus( |
| 164 | + "wiki", |
| 165 | + params.merge(completed.filter((result): result is T => result !== undefined)), |
| 166 | + error, |
| 167 | + ); |
| 168 | + } |
| 169 | + const value = params.merge(completed.filter((result): result is T => result !== undefined)); |
| 170 | + if (failures.length === 0) { |
| 171 | + return { corpus: "wiki", outcome: "ok", value }; |
| 172 | + } |
| 173 | + const orderedFailures = failures.toSorted((left, right) => |
| 174 | + left.pluginId.localeCompare(right.pluginId), |
| 175 | + ); |
| 176 | + const error = |
| 177 | + orderedFailures.length === 1 |
| 178 | + ? orderedFailures[0]!.error |
| 179 | + : orderedFailures.map((entry) => `${entry.pluginId}: ${entry.error}`).join("; "); |
| 180 | + return { corpus: "wiki", outcome: "unavailable", value, error }; |
| 181 | +} |
| 182 | + |
| 183 | +export async function searchMemoryCorpusSupplements(params: { |
| 184 | + query: string; |
| 185 | + maxResults?: number; |
| 186 | + agentId?: string; |
| 187 | + agentSessionKey?: string; |
| 188 | + sandboxed?: boolean; |
| 189 | + signal: AbortSignal; |
| 190 | +}): Promise<MemoryCorpusAttempt<MemoryCorpusSearchResult[]>> { |
| 191 | + const { signal, ...query } = params; |
| 192 | + return await settleMemorySupplements({ |
| 193 | + signal, |
| 194 | + run: async ({ supplement }) => await supplement.search(query), |
| 195 | + merge: (results) => |
| 196 | + results |
| 197 | + .flat() |
| 198 | + .toSorted((left, right) => right.score - left.score || left.path.localeCompare(right.path)) |
| 199 | + .slice(0, Math.max(1, params.maxResults ?? 10)), |
| 200 | + }); |
| 201 | +} |
| 202 | + |
| 203 | +export async function readMemoryCorpusSupplements(params: { |
| 204 | + lookup: string; |
| 205 | + fromLine?: number; |
| 206 | + lineCount?: number; |
| 207 | + agentId?: string; |
| 208 | + agentSessionKey?: string; |
| 209 | + sandboxed?: boolean; |
| 210 | + signal: AbortSignal; |
| 211 | +}): Promise<MemoryCorpusAttempt<MemorySupplementReadResult | null>> { |
| 212 | + const { signal, ...query } = params; |
| 213 | + return await settleMemorySupplements({ |
| 214 | + signal, |
| 215 | + run: async ({ supplement }) => { |
| 216 | + const result = await supplement.get(query); |
| 217 | + if (!result) { |
| 218 | + return null; |
| 219 | + } |
| 220 | + const { content, ...details } = result; |
| 221 | + return { ...details, status: "ok", text: content }; |
| 222 | + }, |
| 223 | + merge: (results) => results.find((result) => result !== null) ?? null, |
| 224 | + }); |
| 225 | +} |
0 commit comments