@unblocklabs/unblock-memory 0.12.1 → 0.12.3
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 +1 -1
- package/dist/src/config.js +3 -3
- package/dist/src/diagnostics.d.ts +6 -7
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/manager.d.ts +1 -2
- package/dist/src/manager.js +25 -6
- package/dist/src/memory-search.d.ts +2 -0
- package/dist/src/memory-search.js +10 -5
- package/dist/src/memory-whisperer.js +137 -150
- package/dist/src/people-learning-runtime.js +72 -10
- package/dist/src/plugin.js +1 -1
- package/dist/src/query-generator.d.ts +7 -3
- package/dist/src/query-generator.js +165 -17
- package/dist/src/response-text.d.ts +2 -0
- package/dist/src/response-text.js +182 -36
- package/dist/src/retrieval-telemetry.d.ts +2 -3
- package/dist/src/retrieval-telemetry.js +1 -1
- package/dist/src/retrieval-timing.d.ts +1 -1
- package/docs/configuration.md +6 -6
- package/docs/retrieval.md +81 -76
- package/openclaw.plugin.json +7 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -115,7 +115,7 @@ Everything below is off until you configure it.
|
|
|
115
115
|
| --- | --- |
|
|
116
116
|
| [Session indexing](docs/retrieval.md#sessions) | Makes past conversations searchable. Group and channel chats by default; DMs only if you add them. |
|
|
117
117
|
| [Skill Whisperer](docs/retrieval.md#skill-whisperer) | Suggests one relevant skill for a user message. Never runs it. Turns on when you add a `skills` corpus; works without TypeSafe. |
|
|
118
|
-
| [Memory Whisperer](docs/retrieval.md#memory-whisperer) | Adds up to
|
|
118
|
+
| [Memory Whisperer](docs/retrieval.md#memory-whisperer) | Adds up to three relevant past excerpts before the agent replies. Needs TypeSafe; optionally uses a self-hosted query-generation API with local fallback. |
|
|
119
119
|
| [Safety Whisperer](docs/configuration.md#safety-whisperer) | Reminds the agent not to share sensitive topics, such as one person's salary, with requestors you haven't approved. A prompt-level guardrail, not access control; fails open if TypeSafe is unavailable. |
|
|
120
120
|
| [My Turn](docs/configuration.md#my-turn) | Asks Jev whether a group/channel conversation needs this agent's response. Advises `NO_REPLY` only when silence is clearly favored; the agent keeps the final say. Opt-in; failures leave the turn unchanged. |
|
|
121
121
|
| [People dossiers](docs/peoplesql.md) | Lets the agent keep a short, evidence-backed note about each person it works with. |
|
package/dist/src/config.js
CHANGED
|
@@ -87,8 +87,8 @@ const DEFAULT_SKILL_WHISPERER = {
|
|
|
87
87
|
cooldownTurns: 10,
|
|
88
88
|
};
|
|
89
89
|
const DEFAULT_MEMORY_WHISPERER = {
|
|
90
|
-
enabled: false, complementaryHints: false, corpora: [], minUsefulness: 0.
|
|
91
|
-
maxHints:
|
|
90
|
+
enabled: false, complementaryHints: false, corpora: [], minUsefulness: 0.5,
|
|
91
|
+
maxHints: 3, cooldownTurns: 10, timeoutMs: 3000,
|
|
92
92
|
api: { endpoint: "http://192.168.1.191:18087" },
|
|
93
93
|
};
|
|
94
94
|
function resolveQueryApi(value) {
|
|
@@ -156,7 +156,7 @@ function resolveMemoryWhisperer(value, corpora) {
|
|
|
156
156
|
}
|
|
157
157
|
return {
|
|
158
158
|
enabled, complementaryHints, corpora: [...new Set(selected)], cooldownTurns, minUsefulness,
|
|
159
|
-
maxHints: positiveInteger(config.maxHints,
|
|
159
|
+
maxHints: positiveInteger(config.maxHints, DEFAULT_MEMORY_WHISPERER.maxHints, "memoryWhisperer.maxHints", 3),
|
|
160
160
|
timeoutMs: positiveInteger(config.timeoutMs, 3000, "memoryWhisperer.timeoutMs", 10_000),
|
|
161
161
|
api: resolveQueryApi(config.api),
|
|
162
162
|
};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { RetrievalTelemetry } from "./retrieval-telemetry.js";
|
|
2
2
|
type Whisperer = "skill" | "memory" | "safety" | "myTurn";
|
|
3
|
-
type Outcome = "missing_key" | "typesafe_disabled" | "no_candidates" | "rejected" | "cooldown" | "emitted" | "failed" | "timed_out" | "cancelled" | "unavailable" | "payload_limit" | "redundancy_unavailable" | "
|
|
3
|
+
type Outcome = "missing_key" | "typesafe_disabled" | "no_candidates" | "rejected" | "cooldown" | "emitted" | "failed" | "timed_out" | "cancelled" | "unavailable" | "payload_limit" | "redundancy_unavailable" | "queries_generated" | "generation_fallback" | "judge_candidate_failed" | "input_too_large" | "excluded" | "no_scenarios" | "empty_request" | "no_match" | "flagged" | "missing_identity" | "partial_response";
|
|
4
4
|
/** Process-local, content-free and bounded. Agent IDs are keys, never included in snapshots. */
|
|
5
5
|
export declare class WhispererDiagnostics {
|
|
6
6
|
#private;
|
|
@@ -24,8 +24,8 @@ export declare class WhispererDiagnostics {
|
|
|
24
24
|
unavailable?: number | undefined;
|
|
25
25
|
payload_limit?: number | undefined;
|
|
26
26
|
redundancy_unavailable?: number | undefined;
|
|
27
|
-
recall_not_needed?: number | undefined;
|
|
28
27
|
queries_generated?: number | undefined;
|
|
28
|
+
generation_fallback?: number | undefined;
|
|
29
29
|
judge_candidate_failed?: number | undefined;
|
|
30
30
|
input_too_large?: number | undefined;
|
|
31
31
|
excluded?: number | undefined;
|
|
@@ -49,8 +49,8 @@ export declare class WhispererDiagnostics {
|
|
|
49
49
|
unavailable?: number | undefined;
|
|
50
50
|
payload_limit?: number | undefined;
|
|
51
51
|
redundancy_unavailable?: number | undefined;
|
|
52
|
-
recall_not_needed?: number | undefined;
|
|
53
52
|
queries_generated?: number | undefined;
|
|
53
|
+
generation_fallback?: number | undefined;
|
|
54
54
|
judge_candidate_failed?: number | undefined;
|
|
55
55
|
input_too_large?: number | undefined;
|
|
56
56
|
excluded?: number | undefined;
|
|
@@ -74,8 +74,8 @@ export declare class WhispererDiagnostics {
|
|
|
74
74
|
unavailable?: number | undefined;
|
|
75
75
|
payload_limit?: number | undefined;
|
|
76
76
|
redundancy_unavailable?: number | undefined;
|
|
77
|
-
recall_not_needed?: number | undefined;
|
|
78
77
|
queries_generated?: number | undefined;
|
|
78
|
+
generation_fallback?: number | undefined;
|
|
79
79
|
judge_candidate_failed?: number | undefined;
|
|
80
80
|
input_too_large?: number | undefined;
|
|
81
81
|
excluded?: number | undefined;
|
|
@@ -102,8 +102,8 @@ export declare class WhispererDiagnostics {
|
|
|
102
102
|
unavailable?: number | undefined;
|
|
103
103
|
payload_limit?: number | undefined;
|
|
104
104
|
redundancy_unavailable?: number | undefined;
|
|
105
|
-
recall_not_needed?: number | undefined;
|
|
106
105
|
queries_generated?: number | undefined;
|
|
106
|
+
generation_fallback?: number | undefined;
|
|
107
107
|
judge_candidate_failed?: number | undefined;
|
|
108
108
|
input_too_large?: number | undefined;
|
|
109
109
|
excluded?: number | undefined;
|
|
@@ -150,11 +150,10 @@ export declare class WhispererDiagnostics {
|
|
|
150
150
|
otherMs?: number | undefined;
|
|
151
151
|
retrievalMs?: number | undefined;
|
|
152
152
|
judgeMs?: number | undefined;
|
|
153
|
+
generationMs?: number | undefined;
|
|
153
154
|
metadataReloads?: number | undefined;
|
|
154
155
|
vectorScanAttempts?: number | undefined;
|
|
155
156
|
elapsedMs?: number | undefined;
|
|
156
|
-
gateMs?: number | undefined;
|
|
157
|
-
generationMs?: number | undefined;
|
|
158
157
|
candidates?: number | undefined;
|
|
159
158
|
eligible?: number | undefined;
|
|
160
159
|
results?: number | undefined;
|
package/dist/src/diagnostics.js
CHANGED
|
@@ -4,7 +4,7 @@ export class WhispererDiagnostics {
|
|
|
4
4
|
static shared() {
|
|
5
5
|
const scope = globalThis;
|
|
6
6
|
// Bump the version whenever the shape changes so an older loaded copy is never reused.
|
|
7
|
-
const symbol = Symbol.for("unblock-memory.whisperer-diagnostics.
|
|
7
|
+
const symbol = Symbol.for("unblock-memory.whisperer-diagnostics.v5");
|
|
8
8
|
return (scope[symbol] ??= new WhispererDiagnostics());
|
|
9
9
|
}
|
|
10
10
|
#agents = new Map();
|
package/dist/src/manager.d.ts
CHANGED
|
@@ -84,11 +84,10 @@ export declare class QmdMemoryManager implements MemorySearchManagerContract {
|
|
|
84
84
|
otherMs?: number | undefined;
|
|
85
85
|
retrievalMs?: number | undefined;
|
|
86
86
|
judgeMs?: number | undefined;
|
|
87
|
+
generationMs?: number | undefined;
|
|
87
88
|
metadataReloads?: number | undefined;
|
|
88
89
|
vectorScanAttempts?: number | undefined;
|
|
89
90
|
elapsedMs?: number | undefined;
|
|
90
|
-
gateMs?: number | undefined;
|
|
91
|
-
generationMs?: number | undefined;
|
|
92
91
|
candidates?: number | undefined;
|
|
93
92
|
eligible?: number | undefined;
|
|
94
93
|
results?: number | undefined;
|
package/dist/src/manager.js
CHANGED
|
@@ -840,6 +840,7 @@ export class QmdMemoryManager {
|
|
|
840
840
|
return this.#allowedPaths(collections, opts.sessionFilter);
|
|
841
841
|
});
|
|
842
842
|
const store = await timeStage("storeSetupMs", timings, signal, () => this.#getAnalysisStore());
|
|
843
|
+
const RRF_K = 60;
|
|
843
844
|
const hits = new Map();
|
|
844
845
|
// Serialize native QMD work. Cancellation prevents further queries/collections.
|
|
845
846
|
for (const lane of ["lex", "vec"]) {
|
|
@@ -853,15 +854,33 @@ export class QmdMemoryManager {
|
|
|
853
854
|
timings.vectorOtherMs = unaccounted(timings.vectorMs, timings, vectorParts);
|
|
854
855
|
}
|
|
855
856
|
}
|
|
856
|
-
for (const hit of candidates) {
|
|
857
|
-
const
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
857
|
+
for (const [index, hit] of candidates.entries()) {
|
|
858
|
+
const rank = hit.bm25?.rank ?? hit.vector?.rank ?? index + 1;
|
|
859
|
+
const contribution = 1 / (RRF_K + rank);
|
|
860
|
+
const key = JSON.stringify([hit.file, hit.bestChunkPos, hit.bestChunk.trim()]);
|
|
861
|
+
const existing = hits.get(key);
|
|
862
|
+
if (existing) {
|
|
863
|
+
existing.rrfScore += contribution;
|
|
864
|
+
existing.topRank = Math.min(existing.topRank, rank);
|
|
865
|
+
}
|
|
866
|
+
else {
|
|
867
|
+
hits.set(key, {
|
|
868
|
+
hit: { file: hit.file, body: hit.body, bestChunk: hit.bestChunk,
|
|
869
|
+
chunkPos: hit.bestChunkPos, chunkLen: hit.bestChunk.length, displayPath: hit.file, score: 0 },
|
|
870
|
+
rrfScore: contribution,
|
|
871
|
+
topRank: rank,
|
|
872
|
+
});
|
|
873
|
+
}
|
|
861
874
|
}
|
|
862
875
|
}
|
|
876
|
+
// Passage-level RRF (k=60) with QMD's top-rank bonuses so rank-1 single-lane
|
|
877
|
+
// hits compete cleanly alongside dual-lane matches before any candidate cap.
|
|
878
|
+
const fused = [...hits.values()].map(entry => ({
|
|
879
|
+
...entry.hit,
|
|
880
|
+
score: entry.rrfScore + (entry.topRank === 1 ? 0.05 : entry.topRank <= 3 ? 0.02 : 0),
|
|
881
|
+
})).sort((a, b) => b.score - a.score);
|
|
863
882
|
opts.signal?.throwIfAborted();
|
|
864
|
-
return timeStage("passageMs", timings, signal, () => this.#renderSearchHits(
|
|
883
|
+
return timeStage("passageMs", timings, signal, () => this.#renderSearchHits(fused, store, opts, true));
|
|
865
884
|
});
|
|
866
885
|
}
|
|
867
886
|
finally {
|
|
@@ -25,6 +25,8 @@ export declare function searchMemory(manager: MemoryCandidateManager, queries: Q
|
|
|
25
25
|
asOf?: string;
|
|
26
26
|
/** Only explicit, agent-requested search opts in. Automatic injection stays strict. */
|
|
27
27
|
allowRetrievalFallback?: boolean;
|
|
28
|
+
/** Cap top retrieval-ranked candidates sent to TypeSafe (after dedup and cooldown filtering). */
|
|
29
|
+
maxJudgeCandidates?: number;
|
|
28
30
|
minUsefulness?: number;
|
|
29
31
|
excludedPassages?: ReadonlyMap<string, number>;
|
|
30
32
|
onCandidates?: (observation: MemorySearchObservation) => void;
|
|
@@ -48,9 +48,8 @@ export async function searchMemory(manager, queries, options) {
|
|
|
48
48
|
options.onCandidates?.(observation);
|
|
49
49
|
const fallback = (reason) => ({
|
|
50
50
|
...timings, ...observation, rankingMode: "retrieval", fallbackReason: reason,
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
// These original lane scores are not fused ranks or usefulness probabilities.
|
|
51
|
+
// Stable retrieval-score ordering (fused RRF scores from discovery) before maxResults truncation.
|
|
52
|
+
// These retrieval scores are not TypeSafe usefulness probabilities.
|
|
54
53
|
results: [...candidates].sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5),
|
|
55
54
|
});
|
|
56
55
|
if (!options.apiKey) {
|
|
@@ -59,11 +58,17 @@ export async function searchMemory(manager, queries, options) {
|
|
|
59
58
|
return fallback("key_unavailable");
|
|
60
59
|
return { ...timings, ...observation, rankingMode: "typesafe_usefulness", results: [] };
|
|
61
60
|
}
|
|
61
|
+
const maxJudge = typeof options.maxJudgeCandidates === "number" && Number.isFinite(options.maxJudgeCandidates)
|
|
62
|
+
? Math.max(0, Math.floor(options.maxJudgeCandidates))
|
|
63
|
+
: undefined;
|
|
64
|
+
const judgePool = maxJudge !== undefined
|
|
65
|
+
? [...candidates].sort((a, b) => b.score - a.score).slice(0, maxJudge)
|
|
66
|
+
: candidates;
|
|
62
67
|
const apiKey = options.apiKey;
|
|
63
68
|
const endJudge = startTiming("judgeMs", timings, signal);
|
|
64
69
|
let judged;
|
|
65
70
|
try {
|
|
66
|
-
judged = (await Promise.all(
|
|
71
|
+
judged = (await Promise.all(judgePool.map(async (hit, candidateIndex) => {
|
|
67
72
|
const requestStarted = performance.now();
|
|
68
73
|
try {
|
|
69
74
|
const { probability } = await judgeMemoryPassage(memoryUsefulnessRequest(options.conversation, {
|
|
@@ -92,7 +97,7 @@ export async function searchMemory(manager, queries, options) {
|
|
|
92
97
|
}
|
|
93
98
|
signal?.throwIfAborted();
|
|
94
99
|
observation.judgeMs = timings.judgeMs ?? 0;
|
|
95
|
-
if (options.allowRetrievalFallback &&
|
|
100
|
+
if (options.allowRetrievalFallback && judgePool.length && !observation.requestsSucceeded)
|
|
96
101
|
return fallback("all_judgments_failed");
|
|
97
102
|
return { ...timings, ...observation, rankingMode: "typesafe_usefulness", results: judged.filter(hit => hit.score >= (options.minUsefulness ?? 0.7))
|
|
98
103
|
.sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5) };
|
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
|
|
2
2
|
import { complementaryIndices, reviewMemoryRedundancy } from "./typesafe-review.js";
|
|
3
|
-
import { ApiQueryGenerator, QueryApiError, queryConversation } from "./query-generator.js";
|
|
4
|
-
import { judgeTrainingInput, TRAINING_GATE_THRESHOLD } from "./training-gate.js";
|
|
3
|
+
import { ApiQueryGenerator, compactJudgeConversation, fallbackQueries, QueryApiError, queryConversation } from "./query-generator.js";
|
|
5
4
|
import { QueryInputBudgetError } from "./query-contract.js";
|
|
6
5
|
import { searchMemory, memoryPassageId } from "./memory-search.js";
|
|
7
|
-
import { timeStage } from "./retrieval-timing.js";
|
|
6
|
+
import { startTiming, timeStage } from "./retrieval-timing.js";
|
|
7
|
+
const MAX_JUDGE_CANDIDATES = 6;
|
|
8
|
+
const MAX_GENERATION_TIMEOUT_MS = 1_500;
|
|
9
|
+
const MAX_PAYLOAD_CHARS = 5_000;
|
|
10
|
+
function encodeHints(items) {
|
|
11
|
+
return JSON.stringify(items).replace(/</gu, "\\u003c").replace(/>/gu, "\\u003e");
|
|
12
|
+
}
|
|
8
13
|
export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnostics) {
|
|
9
14
|
if (!config.enabled || !typesafe.enabled)
|
|
10
15
|
return;
|
|
@@ -13,7 +18,7 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
13
18
|
const beforePrompt = async (event, context) => {
|
|
14
19
|
const { agentId, runId, sessionId, sessionKey } = context;
|
|
15
20
|
const scope = sessionId || sessionKey;
|
|
16
|
-
if (context.trigger !== "user" || !agentId || !runId || !scope
|
|
21
|
+
if (context.trigger !== "user" || !agentId || !runId || !scope)
|
|
17
22
|
return;
|
|
18
23
|
const corpora = config.corpora;
|
|
19
24
|
if (!corpora.length)
|
|
@@ -22,11 +27,15 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
22
27
|
const previous = sessions.get(key);
|
|
23
28
|
if (previous?.runId === runId)
|
|
24
29
|
return previous.result;
|
|
30
|
+
const currentUserMessage = typeof event.currentUserMessage === "string" ? event.currentUserMessage : undefined;
|
|
31
|
+
const rawCurrent = currentUserMessage !== undefined ? currentUserMessage : event.prompt;
|
|
32
|
+
if (!rawCurrent.replace(/^\s*From: [^\r\n]+ \([^()\r\n]+\)\s*$/, "").trim())
|
|
33
|
+
return;
|
|
25
34
|
const started = performance.now();
|
|
26
35
|
const asOf = new Date().toISOString();
|
|
27
36
|
const measurement = { outcome: "skipped", elapsedMs: 0 };
|
|
28
37
|
let stage = "input", reason = "completed";
|
|
29
|
-
let
|
|
38
|
+
let queryCount, queryFallback = false;
|
|
30
39
|
let requestsSucceeded = 0, requestsFailed = 0;
|
|
31
40
|
const log = (level, event, fields) => api.logger[level]("unblock-memory memory_whisperer " + JSON.stringify({ event, agentId, runId, sessionId, stage, ...fields }));
|
|
32
41
|
const failureFields = (error) => error instanceof TypeSafeRequestError || error instanceof QueryApiError
|
|
@@ -43,8 +52,6 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
43
52
|
}
|
|
44
53
|
const { signal } = state.controller;
|
|
45
54
|
let timedOut = false;
|
|
46
|
-
let recallRejected = false;
|
|
47
|
-
let gateFailed = false;
|
|
48
55
|
const timer = setTimeout(() => { timedOut = true; state.controller.abort(); }, config.timeoutMs);
|
|
49
56
|
let onAbort = () => { };
|
|
50
57
|
const aborted = new Promise(resolve => {
|
|
@@ -52,7 +59,7 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
52
59
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
53
60
|
});
|
|
54
61
|
const run = async () => {
|
|
55
|
-
const conversation = queryConversation(event.prompt, event.messages);
|
|
62
|
+
const conversation = queryConversation(event.prompt, event.messages, currentUserMessage);
|
|
56
63
|
stage = "credentials";
|
|
57
64
|
const apiKey = await timeStage("setupMs", measurement, signal, () => resolveTypeSafeApiKey(typesafe));
|
|
58
65
|
if (signal.aborted)
|
|
@@ -62,152 +69,132 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
62
69
|
diagnostics?.record(agentId, "memory", "missing_key");
|
|
63
70
|
return;
|
|
64
71
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
72
|
+
let queries;
|
|
73
|
+
stage = "generation";
|
|
74
|
+
const generationStarted = performance.now();
|
|
75
|
+
const endGeneration = startTiming("generationMs", measurement, signal);
|
|
76
|
+
const generationTimeoutMs = Math.min(MAX_GENERATION_TIMEOUT_MS, Math.max(1, Math.floor(config.timeoutMs / 2)));
|
|
77
|
+
const generationSignal = AbortSignal.any([signal, AbortSignal.timeout(generationTimeoutMs)]);
|
|
78
|
+
try {
|
|
79
|
+
queries = await generator.generate(conversation, generationSignal);
|
|
70
80
|
if (signal.aborted)
|
|
71
|
-
return false;
|
|
72
|
-
measurement.gateMs = performance.now() - gateStarted;
|
|
73
|
-
recallProbability = result.probability;
|
|
74
|
-
if (result.probability >= TRAINING_GATE_THRESHOLD)
|
|
75
|
-
return true;
|
|
76
|
-
recallRejected = true;
|
|
77
|
-
diagnostics?.record(agentId, "memory", "recall_not_needed");
|
|
78
|
-
state.controller.abort();
|
|
79
|
-
return false;
|
|
80
|
-
}).catch(error => {
|
|
81
|
-
if (!signal.aborted) {
|
|
82
|
-
measurement.gateMs = performance.now() - gateStarted;
|
|
83
|
-
log("warn", "recall_failed", { stage: "recall", elapsedMs: measurement.gateMs, timeoutMs: typesafe.timeoutMs,
|
|
84
|
-
...failureFields(error instanceof TypeSafeRequestError ? error :
|
|
85
|
-
new TypeSafeRequestError("Recall judgment failed", "invalid_response")) });
|
|
86
|
-
gateFailed = true;
|
|
87
|
-
diagnostics?.record(agentId, "memory", "failed");
|
|
88
|
-
state.controller.abort();
|
|
89
|
-
}
|
|
90
|
-
return false;
|
|
91
|
-
});
|
|
92
|
-
const retrieveAndJudge = async () => {
|
|
93
|
-
let queries;
|
|
94
|
-
stage = "generation";
|
|
95
|
-
const generationStarted = performance.now();
|
|
96
|
-
try {
|
|
97
|
-
queries = await generator.generate(conversation, signal);
|
|
98
|
-
if (signal.aborted)
|
|
99
|
-
return;
|
|
100
|
-
queryCount = 2;
|
|
101
|
-
diagnostics?.record(agentId, "memory", "queries_generated");
|
|
102
|
-
}
|
|
103
|
-
catch (error) {
|
|
104
|
-
if (signal.aborted)
|
|
105
|
-
return;
|
|
106
|
-
reason = "generation_failed";
|
|
107
|
-
measurement.outcome = "failed";
|
|
108
|
-
log("warn", "generation_failed", { ...failureFields(error), elapsedMs: performance.now() - generationStarted });
|
|
109
|
-
diagnostics?.record(agentId, "memory", "failed");
|
|
110
81
|
return;
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
}
|
|
115
|
-
stage = "retrieval";
|
|
116
|
-
const { manager } = await timeStage("setupMs", measurement, signal, () => runtime.getMemorySearchManager({ cfg: api.config, agentId }));
|
|
82
|
+
diagnostics?.record(agentId, "memory", "queries_generated");
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
117
85
|
if (signal.aborted)
|
|
118
86
|
return;
|
|
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
|
-
if (!await gate || signal.aborted || sessions.get(key) !== state)
|
|
156
|
-
return;
|
|
157
|
-
if (!search.requestsSucceeded) {
|
|
158
|
-
reason = "all_candidates_failed";
|
|
159
|
-
measurement.outcome = "failed";
|
|
160
|
-
diagnostics?.record(agentId, "memory", "failed");
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
const ranked = search.results.map(hit => ({ hit, excerpt: hit.snippet, id: memoryPassageId(hit.snippet) }));
|
|
164
|
-
let selected = ranked.slice(0, config.maxHints);
|
|
165
|
-
if (!selected.length) {
|
|
166
|
-
reason = "rejected";
|
|
167
|
-
diagnostics?.record(agentId, "memory", "rejected");
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
if (config.complementaryHints && config.maxHints > 1 && ranked.length > 1) {
|
|
171
|
-
stage = "redundancy";
|
|
172
|
-
try {
|
|
173
|
-
const pairs = await reviewMemoryRedundancy({ apiKey, timeoutMs: typesafe.timeoutMs, signal,
|
|
174
|
-
excerpts: ranked.map(candidate => candidate.excerpt) });
|
|
175
|
-
selected = complementaryIndices(ranked.length, pairs, config.maxHints).map(index => ranked[index]);
|
|
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 }));
|
|
99
|
+
if (signal.aborted)
|
|
100
|
+
return;
|
|
101
|
+
if (!manager) {
|
|
102
|
+
reason = "unavailable";
|
|
103
|
+
diagnostics?.record(agentId, "memory", "unavailable");
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const search = await searchMemory(manager, queries, {
|
|
107
|
+
corpora, signal, apiKey, timeoutMs: typesafe.timeoutMs, conversation: compactJudgeConversation(conversation),
|
|
108
|
+
asOf, timings: measurement, minUsefulness: config.minUsefulness, maxResults: 4,
|
|
109
|
+
maxJudgeCandidates: MAX_JUDGE_CANDIDATES, excludedPassages: state.recent,
|
|
110
|
+
onCandidates: observation => {
|
|
111
|
+
measurement.retrievalMs = observation.retrievalMs;
|
|
112
|
+
measurement.candidates = observation.candidates;
|
|
113
|
+
measurement.eligible = observation.eligible;
|
|
114
|
+
measurement.outcome = "empty";
|
|
115
|
+
stage = "judgment";
|
|
116
|
+
},
|
|
117
|
+
onJudgment: ({ candidateIndex, elapsedMs, error }) => {
|
|
118
|
+
const fields = { stage: "judgment", candidateIndex, elapsedMs, timeoutMs: typesafe.timeoutMs };
|
|
119
|
+
if (error !== undefined) {
|
|
120
|
+
requestsFailed++;
|
|
121
|
+
diagnostics?.record(agentId, "memory", "judge_candidate_failed");
|
|
122
|
+
log("warn", "candidate_failed", { ...fields, ...failureFields(error) });
|
|
176
123
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
diagnostics?.record(agentId, "memory", "redundancy_unavailable");
|
|
181
|
-
log("warn", "redundancy_unavailable", failureFields(error));
|
|
182
|
-
}
|
|
124
|
+
else {
|
|
125
|
+
requestsSucceeded++;
|
|
126
|
+
log("info", "candidate_completed", fields);
|
|
183
127
|
}
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
if (signal.aborted || sessions.get(key) !== state)
|
|
131
|
+
return;
|
|
132
|
+
measurement.judgeMs = search.judgeMs;
|
|
133
|
+
if (!search.eligible) {
|
|
134
|
+
reason = "no_candidates";
|
|
135
|
+
diagnostics?.record(agentId, "memory", "no_candidates");
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (!search.requestsSucceeded) {
|
|
139
|
+
reason = "all_candidates_failed";
|
|
140
|
+
measurement.outcome = "failed";
|
|
141
|
+
diagnostics?.record(agentId, "memory", "failed");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const ranked = search.results.map(hit => ({ hit, excerpt: hit.snippet, id: memoryPassageId(hit.snippet) }));
|
|
145
|
+
let selected = ranked.slice(0, config.maxHints);
|
|
146
|
+
if (!selected.length) {
|
|
147
|
+
reason = "rejected";
|
|
148
|
+
diagnostics?.record(agentId, "memory", "rejected");
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (config.complementaryHints && config.maxHints > 1 && ranked.length > 1) {
|
|
152
|
+
stage = "redundancy";
|
|
153
|
+
try {
|
|
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]);
|
|
184
157
|
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
// Bound the complete injected payload, including source metadata.
|
|
192
|
-
// Preserve exact JSON values while keeping source text inside its prompt tags.
|
|
193
|
-
const rendered = JSON.stringify(hints).replace(/</gu, "\\u003c").replace(/>/gu, "\\u003e");
|
|
194
|
-
if (rendered.length > 5000) {
|
|
195
|
-
reason = "payload_limit";
|
|
196
|
-
diagnostics?.record(agentId, "memory", "payload_limit");
|
|
197
|
-
return;
|
|
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
|
+
}
|
|
198
164
|
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
165
|
+
}
|
|
166
|
+
if (signal.aborted || sessions.get(key) !== state)
|
|
167
|
+
return;
|
|
168
|
+
stage = "render";
|
|
169
|
+
// Bound the complete injected payload without slicing individual excerpts into misleading prefixes.
|
|
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
|
+
}
|
|
184
|
+
if (!emitted.length) {
|
|
185
|
+
reason = "payload_limit";
|
|
186
|
+
diagnostics?.record(agentId, "memory", "payload_limit");
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
for (const candidate of emitted)
|
|
190
|
+
state.recent.set(candidate.id, state.turn);
|
|
191
|
+
diagnostics?.record(agentId, "memory", "emitted");
|
|
192
|
+
const appendContext = `<memory>\n${rendered}\n</memory>`;
|
|
193
|
+
measurement.outcome = "ok";
|
|
194
|
+
reason = "emitted";
|
|
195
|
+
measurement.results = emitted.length;
|
|
196
|
+
measurement.contextChars = appendContext.length;
|
|
197
|
+
return { appendContext };
|
|
211
198
|
};
|
|
212
199
|
// Prompt rebuilds need the same context, not another retrieval or an empty hook result.
|
|
213
200
|
state.result = (async () => {
|
|
@@ -232,14 +219,14 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
|
|
|
232
219
|
finally {
|
|
233
220
|
measurement.elapsedMs = performance.now() - started;
|
|
234
221
|
if (signal.aborted) {
|
|
235
|
-
measurement.outcome =
|
|
236
|
-
reason =
|
|
222
|
+
measurement.outcome = timedOut ? "timed_out" : "cancelled";
|
|
223
|
+
reason = timedOut ? "deadline" : "cancelled";
|
|
237
224
|
}
|
|
238
225
|
diagnostics?.measureMemory(agentId, measurement);
|
|
239
|
-
log("info", "completed", { ...measurement, reason,
|
|
226
|
+
log("info", "completed", { ...measurement, reason, queryCount, queryFallback, requestsSucceeded, requestsFailed,
|
|
240
227
|
judgedCandidates: requestsSucceeded, partial: requestsSucceeded > 0 && requestsFailed > 0, timeoutMs: config.timeoutMs,
|
|
241
228
|
requestTimeoutMs: typesafe.timeoutMs });
|
|
242
|
-
if (signal.aborted
|
|
229
|
+
if (signal.aborted)
|
|
243
230
|
diagnostics?.record(agentId, "memory", timedOut ? "timed_out" : "cancelled");
|
|
244
231
|
clearTimeout(timer);
|
|
245
232
|
signal.removeEventListener("abort", onAbort);
|