@unblocklabs/unblock-memory 0.12.3 → 0.14.0
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 +19 -18
- package/defaults.json +162 -0
- package/dist/src/analysis.js +1 -1
- package/dist/src/cluster-review.d.ts +2 -0
- package/dist/src/cluster-review.js +9 -8
- package/dist/src/config.d.ts +9 -6
- package/dist/src/config.js +59 -45
- package/dist/src/curation.d.ts +1 -1
- package/dist/src/decision-client.d.ts +45 -0
- package/dist/src/decision-client.js +87 -0
- package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
- package/dist/src/decision-ranking.js +155 -0
- package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
- package/dist/src/decision-review.js +193 -0
- package/dist/src/defaults.d.ts +8 -0
- package/dist/src/defaults.js +128 -0
- package/dist/src/diagnostics.d.ts +5 -5
- package/dist/src/emotion-baselines.d.ts +28 -3
- package/dist/src/emotion-baselines.js +312 -115
- package/dist/src/evidence-review.d.ts +22 -8
- package/dist/src/evidence-review.js +11 -8
- package/dist/src/extraction-chunk.d.ts +3 -0
- package/dist/src/extraction-chunk.js +25 -6
- package/dist/src/extraction-config.js +4 -2
- package/dist/src/extraction-model.d.ts +25 -17
- package/dist/src/extraction-model.js +232 -104
- package/dist/src/extraction-runtime.d.ts +3 -1
- package/dist/src/extraction-runtime.js +48 -20
- package/dist/src/extraction-source.d.ts +1 -1
- package/dist/src/extraction-source.js +21 -12
- package/dist/src/extraction-store.d.ts +29 -3
- package/dist/src/extraction-store.js +149 -25
- package/dist/src/extraction-worker.d.ts +3 -3
- package/dist/src/extraction-worker.js +250 -95
- package/dist/src/inside-out-runtime.js +43 -30
- package/dist/src/inside-out-sources.js +2 -1
- package/dist/src/inside-out-store.d.ts +2 -2
- package/dist/src/inside-out-store.js +111 -69
- package/dist/src/inside-out.d.ts +10 -9
- package/dist/src/inside-out.js +194 -106
- package/dist/src/manager.d.ts +22 -9
- package/dist/src/manager.js +279 -172
- package/dist/src/memory-database.js +3 -2
- package/dist/src/memory-passage.d.ts +2 -2
- package/dist/src/memory-passage.js +3 -2
- package/dist/src/memory-search.d.ts +4 -2
- package/dist/src/memory-search.js +5 -5
- package/dist/src/memory-whisperer.d.ts +1 -1
- package/dist/src/memory-whisperer.js +195 -129
- package/dist/src/my-turn.d.ts +1 -1
- package/dist/src/my-turn.js +90 -70
- package/dist/src/people-background.d.ts +5 -1
- package/dist/src/people-background.js +31 -7
- package/dist/src/people-dossier-review.d.ts +20 -8
- package/dist/src/people-dossier-review.js +15 -11
- package/dist/src/people-hooks.js +127 -22
- package/dist/src/people-learning-cron.d.ts +1 -1
- package/dist/src/people-learning-cron.js +107 -57
- package/dist/src/people-learning-inventory.d.ts +1 -0
- package/dist/src/people-learning-inventory.js +283 -172
- package/dist/src/people-learning-prompt.js +1 -1
- package/dist/src/people-learning-runtime.d.ts +1 -1
- package/dist/src/people-learning-runtime.js +360 -203
- package/dist/src/people-learning-store.d.ts +27 -4
- package/dist/src/people-learning-store.js +312 -96
- package/dist/src/people-primer-tool.js +13 -10
- package/dist/src/people-primer.d.ts +3 -1
- package/dist/src/people-primer.js +66 -48
- package/dist/src/people-store.d.ts +18 -21
- package/dist/src/people-store.js +188 -64
- package/dist/src/people-tools.js +138 -93
- package/dist/src/plugin.js +19 -18
- package/dist/src/quality-audit.d.ts +2 -0
- package/dist/src/quality-audit.js +11 -9
- package/dist/src/quality-triage.js +4 -3
- package/dist/src/query-generator.js +5 -2
- package/dist/src/response-audit.d.ts +1 -1
- package/dist/src/response-audit.js +78 -44
- package/dist/src/response-config.js +3 -1
- package/dist/src/response-episodes.d.ts +1 -1
- package/dist/src/response-episodes.js +15 -19
- package/dist/src/response-identity.js +2 -1
- package/dist/src/response-judge.d.ts +151 -145
- package/dist/src/response-judge.js +535 -204
- package/dist/src/response-memory.js +2 -1
- package/dist/src/response-outcome.js +9 -8
- package/dist/src/response-reviews.d.ts +29 -1
- package/dist/src/response-reviews.js +113 -15
- package/dist/src/response-runtime.js +10 -9
- package/dist/src/response-stages.d.ts +50 -53
- package/dist/src/response-stages.js +10 -4
- package/dist/src/response-store.d.ts +7 -6
- package/dist/src/response-store.js +335 -212
- package/dist/src/review-tools.d.ts +8 -2
- package/dist/src/review-tools.js +22 -21
- package/dist/src/runtime.d.ts +7 -4
- package/dist/src/runtime.js +625 -98
- package/dist/src/safety-config.js +3 -2
- package/dist/src/safety-whisperer.d.ts +2 -2
- package/dist/src/safety-whisperer.js +90 -73
- package/dist/src/session-sync.d.ts +3 -1
- package/dist/src/session-sync.js +202 -96
- package/dist/src/skill-whisperer.d.ts +2 -2
- package/dist/src/skill-whisperer.js +55 -32
- package/dist/src/slack-directory.js +3 -2
- package/dist/src/training-gate.d.ts +9 -22
- package/dist/src/training-gate.js +34 -36
- package/dist/src/training-input.js +4 -3
- package/dist/src/training-judge.d.ts +9 -16
- package/dist/src/training-judge.js +6 -5
- package/dist/src/training-models.d.ts +1 -1
- package/dist/src/training-models.js +9 -7
- package/dist/src/training-queries.d.ts +14 -9
- package/dist/src/training-queries.js +374 -231
- package/dist/src/training-retrieval.d.ts +17 -27
- package/dist/src/training-retrieval.js +186 -139
- package/dist/src/training-runtime.d.ts +3 -0
- package/dist/src/training-runtime.js +76 -18
- package/dist/src/training-store.d.ts +18 -3
- package/dist/src/training-store.js +141 -52
- package/dist/src/training.js +9 -11
- package/dist/src/whisperer-context.d.ts +13 -0
- package/dist/src/whisperer-context.js +22 -1
- package/docs/configuration.md +83 -64
- package/docs/extraction.md +26 -35
- package/docs/memory-training.md +7 -6
- package/docs/people-learning.md +2 -2
- package/docs/peoplesql.md +6 -6
- package/docs/response-audit.md +10 -8
- package/docs/retrieval.md +43 -47
- package/openclaw.plugin.json +76 -75
- package/package.json +5 -2
- package/skills/memory-curator/SKILL.md +1 -1
- package/skills/people-whisperer/SKILL.md +1 -1
- package/dist/src/typesafe-client.d.ts +0 -30
- package/dist/src/typesafe-client.js +0 -92
- package/dist/src/typesafe-review.js +0 -154
- package/dist/src/typesafe.js +0 -147
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { VectorSearchResult } from "@unblocklabs/qmd";
|
|
2
2
|
import { type SessionMessageSpan } from "./session-projector.js";
|
|
3
|
-
export declare const MEMORY_PASSAGE_CHARS
|
|
4
|
-
export declare const MEMORY_PASSAGE_VERSION
|
|
3
|
+
export declare const MEMORY_PASSAGE_CHARS: number;
|
|
4
|
+
export declare const MEMORY_PASSAGE_VERSION: string;
|
|
5
5
|
type Passage = Pick<VectorSearchResult, "body" | "bestChunk" | "chunkPos" | "chunkLen">;
|
|
6
6
|
type LocatedPassage = {
|
|
7
7
|
path: string;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
1
2
|
import { meetingRevisionAnnotation, meetingSpeakerSpans } from "./loggie-projection.js";
|
|
2
3
|
import { sessionContextSpans } from "./session-projector.js";
|
|
3
|
-
export const MEMORY_PASSAGE_CHARS =
|
|
4
|
-
export const MEMORY_PASSAGE_VERSION =
|
|
4
|
+
export const MEMORY_PASSAGE_CHARS = DEFAULTS.memoryWhisperer.judgmentExcerptChars;
|
|
5
|
+
export const MEMORY_PASSAGE_VERSION = `complete-excerpt-${MEMORY_PASSAGE_CHARS}-v1`;
|
|
5
6
|
/** Same passage eligibility in target scoring and runtime hint selection. */
|
|
6
7
|
export function duplicateMemoryPassage(passage, previous) {
|
|
7
8
|
const normalized = (text) => text.replace(/\s+/gu, " ").trim();
|
|
@@ -14,18 +14,20 @@ export type MemorySearchObservation = RetrievalTimings & {
|
|
|
14
14
|
requestsFailed: number;
|
|
15
15
|
};
|
|
16
16
|
export type MemoryRanking = {
|
|
17
|
-
rankingMode: "
|
|
17
|
+
rankingMode: "decision" | "retrieval";
|
|
18
18
|
fallbackReason?: "key_unavailable" | "all_judgments_failed";
|
|
19
19
|
};
|
|
20
20
|
/** Both entry points use the same complete passages and independent usefulness judgments. */
|
|
21
21
|
export declare function searchMemory(manager: MemoryCandidateManager, queries: QueryPair, options: CorpusSearchOptions & {
|
|
22
22
|
apiKey?: string;
|
|
23
|
+
endpoint?: string;
|
|
24
|
+
model?: string;
|
|
23
25
|
timeoutMs: number;
|
|
24
26
|
conversation: QueryConversation;
|
|
25
27
|
asOf?: string;
|
|
26
28
|
/** Only explicit, agent-requested search opts in. Automatic injection stays strict. */
|
|
27
29
|
allowRetrievalFallback?: boolean;
|
|
28
|
-
/** Cap top retrieval-ranked candidates sent to
|
|
30
|
+
/** Cap top retrieval-ranked candidates sent to the decision endpoint (after dedup and cooldown filtering). */
|
|
29
31
|
maxJudgeCandidates?: number;
|
|
30
32
|
minUsefulness?: number;
|
|
31
33
|
excludedPassages?: ReadonlyMap<string, number>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { MEMORY_PASSAGE_CHARS, duplicateMemoryPassage } from "./memory-passage.js";
|
|
3
|
-
import { judgeMemoryPassage, memoryUsefulnessRequest } from "./
|
|
3
|
+
import { judgeMemoryPassage, memoryUsefulnessRequest } from "./decision-ranking.js";
|
|
4
4
|
import { startTiming, retrievalParts, unaccounted } from "./retrieval-timing.js";
|
|
5
5
|
export function memoryPassageId(text) {
|
|
6
6
|
return createHash("sha256").update(text.replace(/\s+/gu, " ").trim()).digest("hex");
|
|
@@ -49,14 +49,14 @@ export async function searchMemory(manager, queries, options) {
|
|
|
49
49
|
const fallback = (reason) => ({
|
|
50
50
|
...timings, ...observation, rankingMode: "retrieval", fallbackReason: reason,
|
|
51
51
|
// Stable retrieval-score ordering (fused RRF scores from discovery) before maxResults truncation.
|
|
52
|
-
// These retrieval scores are not
|
|
52
|
+
// These retrieval scores are not decision model usefulness probabilities.
|
|
53
53
|
results: [...candidates].sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5),
|
|
54
54
|
});
|
|
55
55
|
if (!options.apiKey) {
|
|
56
56
|
signal?.throwIfAborted();
|
|
57
57
|
if (options.allowRetrievalFallback)
|
|
58
58
|
return fallback("key_unavailable");
|
|
59
|
-
return { ...timings, ...observation, rankingMode: "
|
|
59
|
+
return { ...timings, ...observation, rankingMode: "decision", results: [] };
|
|
60
60
|
}
|
|
61
61
|
const maxJudge = typeof options.maxJudgeCandidates === "number" && Number.isFinite(options.maxJudgeCandidates)
|
|
62
62
|
? Math.max(0, Math.floor(options.maxJudgeCandidates))
|
|
@@ -75,7 +75,7 @@ export async function searchMemory(manager, queries, options) {
|
|
|
75
75
|
excerpt: hit.snippet, corpus: hit.corpus, sourcePath: hit.path,
|
|
76
76
|
dates: [...new Set(hit.sessionMessages?.flatMap(message => message.timestamp ? [message.timestamp] : [])
|
|
77
77
|
?? (hit.messageTimestamp ? [hit.messageTimestamp] : []))],
|
|
78
|
-
}, asOf), { ...options, apiKey });
|
|
78
|
+
}, asOf, options.model), { ...options, apiKey });
|
|
79
79
|
signal?.throwIfAborted();
|
|
80
80
|
observation.requestsSucceeded++;
|
|
81
81
|
options.onJudgment?.({ candidateIndex, elapsedMs: performance.now() - requestStarted });
|
|
@@ -99,6 +99,6 @@ export async function searchMemory(manager, queries, options) {
|
|
|
99
99
|
observation.judgeMs = timings.judgeMs ?? 0;
|
|
100
100
|
if (options.allowRetrievalFallback && judgePool.length && !observation.requestsSucceeded)
|
|
101
101
|
return fallback("all_judgments_failed");
|
|
102
|
-
return { ...timings, ...observation, rankingMode: "
|
|
102
|
+
return { ...timings, ...observation, rankingMode: "decision", results: judged.filter(hit => hit.score >= (options.minUsefulness ?? 0.7))
|
|
103
103
|
.sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5) };
|
|
104
104
|
}
|
|
@@ -10,5 +10,5 @@ type MemoryWhispererRuntime = {
|
|
|
10
10
|
manager: MemoryCandidateManager | null;
|
|
11
11
|
}>;
|
|
12
12
|
};
|
|
13
|
-
export declare function registerMemoryWhisperer(api: OpenClawPluginApi, runtime: MemoryWhispererRuntime, config: UnblockMemoryConfig["memoryWhisperer"],
|
|
13
|
+
export declare function registerMemoryWhisperer(api: OpenClawPluginApi, runtime: MemoryWhispererRuntime, config: UnblockMemoryConfig["memoryWhisperer"], decisionModel: UnblockMemoryConfig["decisionModel"], diagnostics?: WhispererDiagnostics): Parameters<typeof api.on<"before_prompt_build">>[1] | undefined;
|
|
14
14
|
export {};
|
|
@@ -1,20 +1,112 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
2
|
+
import { resolveDecisionCredential, DecisionRequestError } from "./decision-client.js";
|
|
3
|
+
import { complementaryIndices, reviewMemoryRedundancy } from "./decision-review.js";
|
|
3
4
|
import { ApiQueryGenerator, compactJudgeConversation, fallbackQueries, QueryApiError, queryConversation } from "./query-generator.js";
|
|
4
5
|
import { QueryInputBudgetError } from "./query-contract.js";
|
|
5
6
|
import { searchMemory, memoryPassageId } from "./memory-search.js";
|
|
6
7
|
import { startTiming, timeStage } from "./retrieval-timing.js";
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
const
|
|
8
|
+
import { abortable, abortedByTimeout } from "./abortable.js";
|
|
9
|
+
const MAX_JUDGE_CANDIDATES = DEFAULTS.memoryWhisperer.maxJudgeCandidates;
|
|
10
|
+
const MAX_GENERATION_TIMEOUT_MS = DEFAULTS.memoryWhisperer.maxQueryGenMs;
|
|
11
|
+
const MAX_PAYLOAD_CHARS = DEFAULTS.memoryWhisperer.maxInjectedChars;
|
|
12
|
+
const MAX_SESSIONS = DEFAULTS.memoryWhisperer.maxTrackedSessions;
|
|
13
|
+
const MAX_SEEN_RUNS = DEFAULTS.memoryWhisperer.maxRunsPerSession;
|
|
10
14
|
function encodeHints(items) {
|
|
11
15
|
return JSON.stringify(items).replace(/</gu, "\\u003c").replace(/>/gu, "\\u003e");
|
|
12
16
|
}
|
|
13
|
-
|
|
14
|
-
|
|
17
|
+
function failureFields(error) {
|
|
18
|
+
return error instanceof DecisionRequestError || error instanceof QueryApiError
|
|
19
|
+
? { errorCode: error.code, httpStatus: error.status }
|
|
20
|
+
: { errorCode: "unexpected" };
|
|
21
|
+
}
|
|
22
|
+
async function generateQueriesWithFallback(params) {
|
|
23
|
+
const { generator, conversation, timeoutMs, signal, turn, agentId, diagnostics, log } = params;
|
|
24
|
+
turn.stage = "generation";
|
|
25
|
+
if (!generator) {
|
|
26
|
+
if (signal.aborted)
|
|
27
|
+
return;
|
|
28
|
+
turn.queryFallback = true;
|
|
29
|
+
diagnostics?.record(agentId, "memory", "generation_fallback");
|
|
30
|
+
return fallbackQueries(conversation);
|
|
31
|
+
}
|
|
32
|
+
const generationStarted = performance.now();
|
|
33
|
+
const endGeneration = startTiming("generationMs", turn.measurement, signal);
|
|
34
|
+
const generationTimeoutMs = Math.min(MAX_GENERATION_TIMEOUT_MS, Math.max(1, Math.floor(timeoutMs / 2)));
|
|
35
|
+
const generationSignal = AbortSignal.any([signal, AbortSignal.timeout(generationTimeoutMs)]);
|
|
36
|
+
try {
|
|
37
|
+
const queries = await generator.generate(conversation, generationSignal);
|
|
38
|
+
if (signal.aborted)
|
|
39
|
+
return;
|
|
40
|
+
diagnostics?.record(agentId, "memory", "queries_generated");
|
|
41
|
+
return queries;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (signal.aborted)
|
|
45
|
+
return;
|
|
46
|
+
turn.queryFallback = true;
|
|
47
|
+
log("warn", "generation_fallback", {
|
|
48
|
+
...failureFields(error),
|
|
49
|
+
elapsedMs: performance.now() - generationStarted,
|
|
50
|
+
timeoutMs: generationTimeoutMs,
|
|
51
|
+
});
|
|
52
|
+
diagnostics?.record(agentId, "memory", "generation_fallback");
|
|
53
|
+
return fallbackQueries(conversation);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
endGeneration();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function selectComplementaryHints(params) {
|
|
60
|
+
const { ranked, config, decisionModel, apiKey, signal, turn, agentId, diagnostics, log } = params;
|
|
61
|
+
let selected = ranked.slice(0, config.maxHints);
|
|
62
|
+
if (!config.complementaryHints || config.maxHints <= 1 || ranked.length <= 1)
|
|
63
|
+
return selected;
|
|
64
|
+
turn.stage = "redundancy";
|
|
65
|
+
try {
|
|
66
|
+
const pairs = await reviewMemoryRedundancy({
|
|
67
|
+
apiKey, endpoint: decisionModel.endpoint, model: decisionModel.model, timeoutMs: decisionModel.timeoutMs, signal,
|
|
68
|
+
excerpts: ranked.slice(0, DEFAULTS.review.maxRedundancyCandidates).map(candidate => candidate.excerpt),
|
|
69
|
+
});
|
|
70
|
+
selected = complementaryIndices(ranked.length, pairs, config.maxHints).map(index => ranked[index]);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
// Preserve the original useful candidates when the optional refinement is unavailable.
|
|
74
|
+
if (!signal.aborted) {
|
|
75
|
+
diagnostics?.record(agentId, "memory", "redundancy_unavailable");
|
|
76
|
+
log("warn", "redundancy_unavailable", failureFields(error));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return selected;
|
|
80
|
+
}
|
|
81
|
+
function renderBoundedHints(selected) {
|
|
82
|
+
// Bound the complete injected payload without slicing individual excerpts into misleading prefixes.
|
|
83
|
+
const emitted = [];
|
|
84
|
+
const hints = [];
|
|
85
|
+
let rendered = "";
|
|
86
|
+
for (const candidate of selected) {
|
|
87
|
+
const nextHint = {
|
|
88
|
+
source: candidate.hit.path,
|
|
89
|
+
lines: `${candidate.hit.startLine}-${candidate.hit.endLine}`,
|
|
90
|
+
body: candidate.excerpt,
|
|
91
|
+
};
|
|
92
|
+
const nextRendered = encodeHints([...hints, nextHint]);
|
|
93
|
+
if (nextRendered.length > MAX_PAYLOAD_CHARS)
|
|
94
|
+
continue;
|
|
95
|
+
emitted.push(candidate);
|
|
96
|
+
hints.push(nextHint);
|
|
97
|
+
rendered = nextRendered;
|
|
98
|
+
}
|
|
99
|
+
return { emitted, rendered };
|
|
100
|
+
}
|
|
101
|
+
export function registerMemoryWhisperer(api, runtime, config, decisionModel, diagnostics) {
|
|
102
|
+
if (!config.enabled || !decisionModel.enabled)
|
|
15
103
|
return;
|
|
16
104
|
const sessions = new Map();
|
|
17
|
-
const generator = new ApiQueryGenerator(config.api);
|
|
105
|
+
const generator = config.api.endpoint ? new ApiQueryGenerator(config.api) : undefined;
|
|
106
|
+
const touchSession = (key, state) => {
|
|
107
|
+
sessions.delete(key);
|
|
108
|
+
sessions.set(key, state);
|
|
109
|
+
};
|
|
18
110
|
const beforePrompt = async (event, context) => {
|
|
19
111
|
const { agentId, runId, sessionId, sessionKey } = context;
|
|
20
112
|
const scope = sessionId || sessionKey;
|
|
@@ -25,164 +117,129 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
25
117
|
return;
|
|
26
118
|
const key = JSON.stringify([agentId, scope]);
|
|
27
119
|
const previous = sessions.get(key);
|
|
28
|
-
if (previous
|
|
29
|
-
|
|
120
|
+
if (previous) {
|
|
121
|
+
touchSession(key, previous);
|
|
122
|
+
if (previous.runId === runId)
|
|
123
|
+
return previous.result;
|
|
124
|
+
// Ignore delayed prompt rebuilds for already-superseded runs so they never replace the latest run.
|
|
125
|
+
if (previous.seenRuns.has(runId))
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
30
128
|
const currentUserMessage = typeof event.currentUserMessage === "string" ? event.currentUserMessage : undefined;
|
|
31
129
|
const rawCurrent = currentUserMessage !== undefined ? currentUserMessage : event.prompt;
|
|
32
130
|
if (!rawCurrent.replace(/^\s*From: [^\r\n]+ \([^()\r\n]+\)\s*$/, "").trim())
|
|
33
131
|
return;
|
|
34
132
|
const started = performance.now();
|
|
35
133
|
const asOf = new Date().toISOString();
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
134
|
+
const turn = {
|
|
135
|
+
stage: "input",
|
|
136
|
+
reason: "completed",
|
|
137
|
+
queryFallback: false,
|
|
138
|
+
requestsSucceeded: 0,
|
|
139
|
+
requestsFailed: 0,
|
|
140
|
+
measurement: { outcome: "skipped", elapsedMs: 0 },
|
|
141
|
+
};
|
|
142
|
+
const log = (level, eventName, fields) => api.logger[level]("unblock-memory memory_whisperer " + JSON.stringify({ event: eventName, agentId, runId, sessionId, stage: turn.stage, ...fields }));
|
|
43
143
|
previous?.controller.abort();
|
|
144
|
+
if (!previous && sessions.size >= MAX_SESSIONS) {
|
|
145
|
+
const oldestKey = sessions.keys().next().value;
|
|
146
|
+
sessions.get(oldestKey)?.controller.abort();
|
|
147
|
+
sessions.delete(oldestKey);
|
|
148
|
+
}
|
|
149
|
+
const seenRuns = previous?.seenRuns ?? new Set();
|
|
150
|
+
seenRuns.add(runId);
|
|
151
|
+
if (seenRuns.size > MAX_SEEN_RUNS)
|
|
152
|
+
seenRuns.delete(seenRuns.values().next().value);
|
|
44
153
|
const state = {
|
|
45
154
|
agentId, sessionId, sessionKey, runId, turn: (previous?.turn ?? 0) + 1,
|
|
46
|
-
controller: new AbortController(), recent: previous?.recent ?? new Map(),
|
|
155
|
+
controller: new AbortController(), recent: previous?.recent ?? new Map(), seenRuns,
|
|
47
156
|
};
|
|
48
|
-
|
|
49
|
-
for (const [id,
|
|
50
|
-
if (state.turn -
|
|
157
|
+
touchSession(key, state);
|
|
158
|
+
for (const [id, recordedTurn] of state.recent) {
|
|
159
|
+
if (state.turn - recordedTurn > config.cooldownTurns)
|
|
51
160
|
state.recent.delete(id);
|
|
52
161
|
}
|
|
53
162
|
const { signal } = state.controller;
|
|
54
|
-
|
|
55
|
-
const timer = setTimeout(() => { timedOut = true; state.controller.abort(); }, config.timeoutMs);
|
|
56
|
-
let onAbort = () => { };
|
|
57
|
-
const aborted = new Promise(resolve => {
|
|
58
|
-
onAbort = () => resolve(undefined);
|
|
59
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
60
|
-
});
|
|
163
|
+
const timer = setTimeout(() => state.controller.abort(new DOMException("Memory deadline", "TimeoutError")), config.timeoutMs);
|
|
61
164
|
const run = async () => {
|
|
62
165
|
const conversation = queryConversation(event.prompt, event.messages, currentUserMessage);
|
|
63
|
-
stage = "credentials";
|
|
64
|
-
const apiKey = await timeStage("setupMs", measurement, signal, () =>
|
|
166
|
+
turn.stage = "credentials";
|
|
167
|
+
const apiKey = await timeStage("setupMs", turn.measurement, signal, () => resolveDecisionCredential(decisionModel));
|
|
65
168
|
if (signal.aborted)
|
|
66
169
|
return;
|
|
67
170
|
if (!apiKey) {
|
|
68
|
-
reason = "missing_key";
|
|
171
|
+
turn.reason = "missing_key";
|
|
69
172
|
diagnostics?.record(agentId, "memory", "missing_key");
|
|
70
173
|
return;
|
|
71
174
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (signal.aborted)
|
|
81
|
-
return;
|
|
82
|
-
diagnostics?.record(agentId, "memory", "queries_generated");
|
|
83
|
-
}
|
|
84
|
-
catch (error) {
|
|
85
|
-
if (signal.aborted)
|
|
86
|
-
return;
|
|
87
|
-
queryFallback = true;
|
|
88
|
-
queries = fallbackQueries(conversation);
|
|
89
|
-
log("warn", "generation_fallback", { ...failureFields(error), elapsedMs: performance.now() - generationStarted,
|
|
90
|
-
timeoutMs: generationTimeoutMs });
|
|
91
|
-
diagnostics?.record(agentId, "memory", "generation_fallback");
|
|
92
|
-
}
|
|
93
|
-
finally {
|
|
94
|
-
endGeneration();
|
|
95
|
-
}
|
|
96
|
-
queryCount = 2;
|
|
97
|
-
stage = "retrieval";
|
|
98
|
-
const { manager } = await timeStage("setupMs", measurement, signal, () => runtime.getMemorySearchManager({ cfg: api.config, agentId }));
|
|
175
|
+
const queries = await generateQueriesWithFallback({
|
|
176
|
+
generator, conversation, timeoutMs: config.timeoutMs, signal, turn, agentId, diagnostics, log,
|
|
177
|
+
});
|
|
178
|
+
if (!queries || signal.aborted)
|
|
179
|
+
return;
|
|
180
|
+
turn.queryCount = 2;
|
|
181
|
+
turn.stage = "retrieval";
|
|
182
|
+
const { manager } = await timeStage("setupMs", turn.measurement, signal, () => runtime.getMemorySearchManager({ cfg: api.config, agentId }));
|
|
99
183
|
if (signal.aborted)
|
|
100
184
|
return;
|
|
101
185
|
if (!manager) {
|
|
102
|
-
reason = "unavailable";
|
|
186
|
+
turn.reason = "unavailable";
|
|
103
187
|
diagnostics?.record(agentId, "memory", "unavailable");
|
|
104
188
|
return;
|
|
105
189
|
}
|
|
106
190
|
const search = await searchMemory(manager, queries, {
|
|
107
|
-
corpora, signal, apiKey, timeoutMs:
|
|
108
|
-
asOf, timings: measurement, minUsefulness: config.minUsefulness, maxResults:
|
|
191
|
+
corpora, signal, apiKey, endpoint: decisionModel.endpoint, model: decisionModel.model, timeoutMs: decisionModel.timeoutMs, conversation: compactJudgeConversation(conversation),
|
|
192
|
+
asOf, timings: turn.measurement, minUsefulness: config.minUsefulness, maxResults: DEFAULTS.memoryWhisperer.maxFinalists,
|
|
109
193
|
maxJudgeCandidates: MAX_JUDGE_CANDIDATES, excludedPassages: state.recent,
|
|
110
194
|
onCandidates: observation => {
|
|
111
|
-
measurement.retrievalMs = observation.retrievalMs;
|
|
112
|
-
measurement.candidates = observation.candidates;
|
|
113
|
-
measurement.eligible = observation.eligible;
|
|
114
|
-
measurement.outcome = "empty";
|
|
115
|
-
stage = "judgment";
|
|
195
|
+
turn.measurement.retrievalMs = observation.retrievalMs;
|
|
196
|
+
turn.measurement.candidates = observation.candidates;
|
|
197
|
+
turn.measurement.eligible = observation.eligible;
|
|
198
|
+
turn.measurement.outcome = "empty";
|
|
199
|
+
turn.stage = "judgment";
|
|
116
200
|
},
|
|
117
201
|
onJudgment: ({ candidateIndex, elapsedMs, error }) => {
|
|
118
|
-
const fields = { stage: "judgment", candidateIndex, elapsedMs, timeoutMs:
|
|
202
|
+
const fields = { stage: "judgment", candidateIndex, elapsedMs, timeoutMs: decisionModel.timeoutMs };
|
|
119
203
|
if (error !== undefined) {
|
|
120
|
-
requestsFailed++;
|
|
204
|
+
turn.requestsFailed++;
|
|
121
205
|
diagnostics?.record(agentId, "memory", "judge_candidate_failed");
|
|
122
206
|
log("warn", "candidate_failed", { ...fields, ...failureFields(error) });
|
|
123
207
|
}
|
|
124
208
|
else {
|
|
125
|
-
requestsSucceeded++;
|
|
209
|
+
turn.requestsSucceeded++;
|
|
126
210
|
log("info", "candidate_completed", fields);
|
|
127
211
|
}
|
|
128
212
|
},
|
|
129
213
|
});
|
|
130
214
|
if (signal.aborted || sessions.get(key) !== state)
|
|
131
215
|
return;
|
|
132
|
-
measurement.judgeMs = search.judgeMs;
|
|
216
|
+
turn.measurement.judgeMs = search.judgeMs;
|
|
133
217
|
if (!search.eligible) {
|
|
134
|
-
reason = "no_candidates";
|
|
218
|
+
turn.reason = "no_candidates";
|
|
135
219
|
diagnostics?.record(agentId, "memory", "no_candidates");
|
|
136
220
|
return;
|
|
137
221
|
}
|
|
138
222
|
if (!search.requestsSucceeded) {
|
|
139
|
-
reason = "all_candidates_failed";
|
|
140
|
-
measurement.outcome = "failed";
|
|
223
|
+
turn.reason = "all_candidates_failed";
|
|
224
|
+
turn.measurement.outcome = "failed";
|
|
141
225
|
diagnostics?.record(agentId, "memory", "failed");
|
|
142
226
|
return;
|
|
143
227
|
}
|
|
144
228
|
const ranked = search.results.map(hit => ({ hit, excerpt: hit.snippet, id: memoryPassageId(hit.snippet) }));
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
reason = "rejected";
|
|
229
|
+
if (!ranked.length) {
|
|
230
|
+
turn.reason = "rejected";
|
|
148
231
|
diagnostics?.record(agentId, "memory", "rejected");
|
|
149
232
|
return;
|
|
150
233
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const pairs = await reviewMemoryRedundancy({ apiKey, timeoutMs: typesafe.timeoutMs, signal,
|
|
155
|
-
excerpts: ranked.map(candidate => candidate.excerpt) });
|
|
156
|
-
selected = complementaryIndices(ranked.length, pairs, config.maxHints).map(index => ranked[index]);
|
|
157
|
-
}
|
|
158
|
-
catch (error) {
|
|
159
|
-
// Preserve the original useful candidates when the optional refinement is unavailable.
|
|
160
|
-
if (!signal.aborted) {
|
|
161
|
-
diagnostics?.record(agentId, "memory", "redundancy_unavailable");
|
|
162
|
-
log("warn", "redundancy_unavailable", failureFields(error));
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
234
|
+
const selected = await selectComplementaryHints({
|
|
235
|
+
ranked, config, decisionModel, apiKey, signal, turn, agentId, diagnostics, log,
|
|
236
|
+
});
|
|
166
237
|
if (signal.aborted || sessions.get(key) !== state)
|
|
167
238
|
return;
|
|
168
|
-
stage = "render";
|
|
169
|
-
|
|
170
|
-
const emitted = [];
|
|
171
|
-
const hints = [];
|
|
172
|
-
let rendered = "";
|
|
173
|
-
for (const candidate of selected) {
|
|
174
|
-
const nextHint = {
|
|
175
|
-
source: candidate.hit.path, lines: `${candidate.hit.startLine}-${candidate.hit.endLine}`, body: candidate.excerpt,
|
|
176
|
-
};
|
|
177
|
-
const nextRendered = encodeHints([...hints, nextHint]);
|
|
178
|
-
if (nextRendered.length > MAX_PAYLOAD_CHARS)
|
|
179
|
-
continue;
|
|
180
|
-
emitted.push(candidate);
|
|
181
|
-
hints.push(nextHint);
|
|
182
|
-
rendered = nextRendered;
|
|
183
|
-
}
|
|
239
|
+
turn.stage = "render";
|
|
240
|
+
const { emitted, rendered } = renderBoundedHints(selected);
|
|
184
241
|
if (!emitted.length) {
|
|
185
|
-
reason = "payload_limit";
|
|
242
|
+
turn.reason = "payload_limit";
|
|
186
243
|
diagnostics?.record(agentId, "memory", "payload_limit");
|
|
187
244
|
return;
|
|
188
245
|
}
|
|
@@ -190,46 +247,55 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
190
247
|
state.recent.set(candidate.id, state.turn);
|
|
191
248
|
diagnostics?.record(agentId, "memory", "emitted");
|
|
192
249
|
const appendContext = `<memory>\n${rendered}\n</memory>`;
|
|
193
|
-
measurement.outcome = "ok";
|
|
194
|
-
reason = "emitted";
|
|
195
|
-
measurement.results = emitted.length;
|
|
196
|
-
measurement.contextChars = appendContext.length;
|
|
250
|
+
turn.measurement.outcome = "ok";
|
|
251
|
+
turn.reason = "emitted";
|
|
252
|
+
turn.measurement.results = emitted.length;
|
|
253
|
+
turn.measurement.contextChars = appendContext.length;
|
|
197
254
|
return { appendContext };
|
|
198
255
|
};
|
|
199
256
|
// Prompt rebuilds need the same context, not another retrieval or an empty hook result.
|
|
200
257
|
state.result = (async () => {
|
|
201
258
|
try {
|
|
202
|
-
return await
|
|
259
|
+
return await abortable(run(), signal);
|
|
203
260
|
}
|
|
204
261
|
catch (error) {
|
|
262
|
+
if (signal.aborted)
|
|
263
|
+
return;
|
|
205
264
|
if (error instanceof QueryInputBudgetError) {
|
|
206
|
-
reason = "input_too_large";
|
|
207
|
-
measurement.outcome = "skipped";
|
|
265
|
+
turn.reason = "input_too_large";
|
|
266
|
+
turn.measurement.outcome = "skipped";
|
|
208
267
|
diagnostics?.record(agentId, "memory", "input_too_large");
|
|
209
268
|
return;
|
|
210
269
|
}
|
|
211
|
-
reason = "stage_failed";
|
|
212
|
-
measurement.outcome = "failed";
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
log("warn", "stage_failed", failureFields(error));
|
|
216
|
-
}
|
|
270
|
+
turn.reason = "stage_failed";
|
|
271
|
+
turn.measurement.outcome = "failed";
|
|
272
|
+
diagnostics?.record(agentId, "memory", "failed");
|
|
273
|
+
log("warn", "stage_failed", failureFields(error));
|
|
217
274
|
return;
|
|
218
275
|
}
|
|
219
276
|
finally {
|
|
220
|
-
measurement.elapsedMs = performance.now() - started;
|
|
277
|
+
turn.measurement.elapsedMs = performance.now() - started;
|
|
278
|
+
const timedOut = abortedByTimeout(signal);
|
|
221
279
|
if (signal.aborted) {
|
|
222
|
-
measurement.outcome = timedOut ? "timed_out" : "cancelled";
|
|
223
|
-
reason = timedOut ? "deadline" : "cancelled";
|
|
280
|
+
turn.measurement.outcome = timedOut ? "timed_out" : "cancelled";
|
|
281
|
+
turn.reason = timedOut ? "deadline" : "cancelled";
|
|
224
282
|
}
|
|
225
|
-
diagnostics?.measureMemory(agentId, measurement);
|
|
226
|
-
log("info", "completed", {
|
|
227
|
-
|
|
228
|
-
|
|
283
|
+
diagnostics?.measureMemory(agentId, turn.measurement);
|
|
284
|
+
log("info", "completed", {
|
|
285
|
+
...turn.measurement,
|
|
286
|
+
reason: turn.reason,
|
|
287
|
+
queryCount: turn.queryCount,
|
|
288
|
+
queryFallback: turn.queryFallback,
|
|
289
|
+
requestsSucceeded: turn.requestsSucceeded,
|
|
290
|
+
requestsFailed: turn.requestsFailed,
|
|
291
|
+
judgedCandidates: turn.requestsSucceeded,
|
|
292
|
+
partial: turn.requestsSucceeded > 0 && turn.requestsFailed > 0,
|
|
293
|
+
timeoutMs: config.timeoutMs,
|
|
294
|
+
requestTimeoutMs: decisionModel.timeoutMs,
|
|
295
|
+
});
|
|
229
296
|
if (signal.aborted)
|
|
230
297
|
diagnostics?.record(agentId, "memory", timedOut ? "timed_out" : "cancelled");
|
|
231
298
|
clearTimeout(timer);
|
|
232
|
-
signal.removeEventListener("abort", onAbort);
|
|
233
299
|
// Stop sibling provider/worker work after an error or an empty early result too.
|
|
234
300
|
state.controller.abort();
|
|
235
301
|
}
|
package/dist/src/my-turn.d.ts
CHANGED
|
@@ -9,4 +9,4 @@ export type MyTurnConfig = {
|
|
|
9
9
|
}>;
|
|
10
10
|
};
|
|
11
11
|
export declare function resolveMyTurn(value: unknown): MyTurnConfig;
|
|
12
|
-
export declare function registerMyTurn(api: OpenClawPluginApi, config: MyTurnConfig,
|
|
12
|
+
export declare function registerMyTurn(api: OpenClawPluginApi, config: MyTurnConfig, decisionModel: UnblockMemoryConfig["decisionModel"], diagnostics?: WhispererDiagnostics): Parameters<typeof api.on<"before_prompt_build">>[1] | undefined;
|