opencode-rag-plugin 2.8.0 → 2.9.1
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/dist/api.d.ts +8 -0
- package/dist/api.js +1 -0
- package/dist/cli/commands/eval.js +1 -0
- package/dist/cli/commands/query.js +1 -0
- package/dist/core/config.d.ts +28 -0
- package/dist/core/config.js +6 -0
- package/dist/core/interfaces.d.ts +6 -0
- package/dist/mcp/handlers.js +1 -0
- package/dist/plugin.js +318 -227
- package/dist/quirks/auto-inject.d.ts +127 -0
- package/dist/quirks/auto-inject.js +240 -0
- package/dist/quirks/error-signals.d.ts +81 -0
- package/dist/quirks/error-signals.js +225 -0
- package/dist/quirks/tool-error-create.js +25 -0
- package/dist/quirks/tool-error-recall.d.ts +6 -0
- package/dist/quirks/tool-error-recall.js +1 -0
- package/dist/retriever/retriever.d.ts +25 -0
- package/dist/retriever/retriever.js +20 -1
- package/dist/v2/v2-adapter.d.ts +17 -0
- package/dist/v2/v2-adapter.js +53 -6
- package/package.json +1 -1
package/dist/plugin.js
CHANGED
|
@@ -29,11 +29,13 @@ import { countTokens } from "./eval/token-counter.js";
|
|
|
29
29
|
import { checkForUpdate, getCurrentVersion, installLatestUpdate } from "./core/version-check.js";
|
|
30
30
|
import { loadAutoUpdateState, saveAutoUpdateState, shouldAttemptInstall } from "./core/auto-update-state.js";
|
|
31
31
|
import { destroyAllPooledConnections } from "./embedder/http.js";
|
|
32
|
-
import { listQuirks, lintQuirks, recallQuirks,
|
|
32
|
+
import { listQuirks, lintQuirks, recallQuirks, reconcileQuirks, addQuirk, listToolErrorQuirks } from "./quirks/quirk-store.js";
|
|
33
33
|
import { autoCaptureQuirks } from "./quirks/auto-capture.js";
|
|
34
|
+
import { detectOutputError, detectSessionError, extractExitCode, } from "./quirks/error-signals.js";
|
|
34
35
|
import { createToolErrorInjectionState, recallToolErrorQuirks, formatToolErrorQuirkBlock, toToolErrorCaptureEntry, } from "./quirks/tool-error-recall.js";
|
|
35
36
|
import { buildToolErrorQuirkContent, classifyToolErrorCause, createToolErrorCreateState, createToolErrorQuirk, formatToolGotchaBlock, hasEquivalentToolGotcha, selectToolGotchas, TOOL_ERROR_CREATE_DEFAULTS, TOOL_ERROR_QUIRK_TAG, } from "./quirks/tool-error-create.js";
|
|
36
37
|
import { buildSystemGuidanceLines } from "./opencode/system-guidance.js";
|
|
38
|
+
import { describeAutoInjectSelection, formatAutoInjectBlock, selectAutoInjectQuirksWithinBudget, } from "./quirks/auto-inject.js";
|
|
37
39
|
import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
38
40
|
import path from "node:path";
|
|
39
41
|
/** Maximum entries per session map before oldest entries are evicted. */
|
|
@@ -105,6 +107,25 @@ function boundedSet(map, key, value, maxSize) {
|
|
|
105
107
|
map.set(key, value);
|
|
106
108
|
}
|
|
107
109
|
/** Get or create a Set for a session key in the given Map, bounded by maxSize. */
|
|
110
|
+
/**
|
|
111
|
+
* Read an event's payload.
|
|
112
|
+
*
|
|
113
|
+
* V2 puts it in `data` and never sets `properties`; V1 used `properties`.
|
|
114
|
+
* Measured live 2026-10-21 across every event type of a full session:
|
|
115
|
+
* `hasData=true, hasProperties=false` for all of them.
|
|
116
|
+
*/
|
|
117
|
+
function eventPayload(event) {
|
|
118
|
+
if (!event || typeof event !== "object")
|
|
119
|
+
return undefined;
|
|
120
|
+
const record = event;
|
|
121
|
+
const data = record.data;
|
|
122
|
+
if (data && typeof data === "object")
|
|
123
|
+
return data;
|
|
124
|
+
const properties = record.properties;
|
|
125
|
+
if (properties && typeof properties === "object")
|
|
126
|
+
return properties;
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
108
129
|
function getOrCreateSessionSet(map, key, maxSize) {
|
|
109
130
|
let set = map.get(key);
|
|
110
131
|
if (!set) {
|
|
@@ -433,10 +454,10 @@ function buildRetrievalQuery(hints) {
|
|
|
433
454
|
* Perform a retrieval query against the vector store with the given parameters.
|
|
434
455
|
* Returns an empty array for blank queries.
|
|
435
456
|
*/
|
|
436
|
-
async function retrieveContext(query, embedder, store, topK, retrieveFn = retrieve, minScore = 0, keywordIndex, keywordWeight, queryPrefix, explain = false, hybridEnabled, filter, reranker, reranking) {
|
|
457
|
+
async function retrieveContext(query, embedder, store, topK, retrieveFn = retrieve, minScore = 0, keywordIndex, keywordWeight, queryPrefix, explain = false, hybridEnabled, filter, reranker, reranking, minScoreMode) {
|
|
437
458
|
if (query.trim().length === 0)
|
|
438
459
|
return [];
|
|
439
|
-
return retrieveFn(query, embedder, store, { topK, minScore, keywordIndex, keywordWeight, hybridEnabled, queryPrefix, explain, filter, reranker, reranking });
|
|
460
|
+
return retrieveFn(query, embedder, store, { topK, minScore, keywordIndex, keywordWeight, hybridEnabled, queryPrefix, explain, filter, reranker, reranking, minScoreMode });
|
|
440
461
|
}
|
|
441
462
|
/**
|
|
442
463
|
* Load results from one or two queries (primary + optional extra), optimize
|
|
@@ -445,11 +466,12 @@ async function retrieveContext(query, embedder, store, topK, retrieveFn = retrie
|
|
|
445
466
|
*/
|
|
446
467
|
async function loadRetrievedResults(query, embedder, store, cfg, retrieveFn = retrieve, topK = cfg.retrieval.topK, extraQuery, keywordIndex, queryPrefix, explain = false, filter, reranker, reranking) {
|
|
447
468
|
const minScore = cfg.retrieval.minScore;
|
|
469
|
+
const minScoreMode = cfg.retrieval.minScoreMode;
|
|
448
470
|
const kw = cfg.retrieval.hybridSearch?.keywordWeight;
|
|
449
471
|
const hybridEnabled = cfg.retrieval.hybridSearch?.enabled;
|
|
450
|
-
const primaryResults = await retrieveContext(query, embedder, store, topK, retrieveFn, minScore, keywordIndex, kw, queryPrefix, explain, hybridEnabled, filter, reranker, reranking);
|
|
472
|
+
const primaryResults = await retrieveContext(query, embedder, store, topK, retrieveFn, minScore, keywordIndex, kw, queryPrefix, explain, hybridEnabled, filter, reranker, reranking, minScoreMode);
|
|
451
473
|
const extraResults = extraQuery
|
|
452
|
-
? await retrieveContext(extraQuery, embedder, store, topK, retrieveFn, minScore, keywordIndex, kw, queryPrefix, explain, hybridEnabled, filter, reranker, reranking)
|
|
474
|
+
? await retrieveContext(extraQuery, embedder, store, topK, retrieveFn, minScore, keywordIndex, kw, queryPrefix, explain, hybridEnabled, filter, reranker, reranking, minScoreMode)
|
|
453
475
|
: [];
|
|
454
476
|
const optCfg = cfg.retrieval.contextOptimization ?? DEFAULT_CONTEXT_OPTIMIZATION;
|
|
455
477
|
return optimizeContext([...primaryResults, ...extraResults], { topK, config: optCfg })
|
|
@@ -951,13 +973,242 @@ export function createRagHooks(options) {
|
|
|
951
973
|
scope: "plugin",
|
|
952
974
|
message: `Registered tools: ${toolNames}`,
|
|
953
975
|
});
|
|
976
|
+
/**
|
|
977
|
+
* Handle an intercepted error: recall the quirks that cover it and inject
|
|
978
|
+
* the best match into the NEXT model request; create a quirk when nothing
|
|
979
|
+
* in memory covers the failure.
|
|
980
|
+
*
|
|
981
|
+
* `source` names the surface the failure came from: `host` (the host
|
|
982
|
+
* rejected the call), `output` (the call was reported as successful but its
|
|
983
|
+
* output reports a failure) and `session` (a model/provider error).
|
|
984
|
+
* `causeClassOverride` supplies a stable cause class when the generic
|
|
985
|
+
* classifier cannot derive one — the exact duplicate check needs it, and an
|
|
986
|
+
* output-derived failure (raw stderr) is too varied for the classifier
|
|
987
|
+
* alone.
|
|
988
|
+
*/
|
|
989
|
+
const interceptError = async (info, source, causeClassOverride) => {
|
|
990
|
+
const memCfg = getEffectiveCfg().memory;
|
|
991
|
+
if (!memCfg?.enabled || !memCfg.injectOnToolError)
|
|
992
|
+
return;
|
|
993
|
+
if (source !== "host" && !memCfg.interceptAllErrors)
|
|
994
|
+
return;
|
|
995
|
+
// Every session-scoped map below is keyed by session, so a failure
|
|
996
|
+
// without one cannot be tracked.
|
|
997
|
+
const sessionID = info.sessionID;
|
|
998
|
+
if (!sessionID)
|
|
999
|
+
return;
|
|
1000
|
+
const state = sessionToolErrorState.get(sessionID) ?? createToolErrorInjectionState({
|
|
1001
|
+
cooldownMs: memCfg.toolErrorCooldownMs ?? 60_000,
|
|
1002
|
+
maxPerSession: memCfg.toolErrorMaxPerSession ?? 3,
|
|
1003
|
+
});
|
|
1004
|
+
boundedSet(sessionToolErrorState, sessionID, state, MAX_SESSION_MAP_SIZE);
|
|
1005
|
+
const qDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1006
|
+
// `explain: true` keeps the raw vector similarity on each result —
|
|
1007
|
+
// the confidence-discounted `score` is not comparable to a
|
|
1008
|
+
// similarity threshold, and the tiering below needs the raw value.
|
|
1009
|
+
const recall = (query, recallOpts) => recallQuirks(qDeps, query, { ...recallOpts, explain: true }).then((rs) => rs.map((r) => ({
|
|
1010
|
+
chunk: {
|
|
1011
|
+
id: r.chunk.id,
|
|
1012
|
+
content: r.chunk.content,
|
|
1013
|
+
metadata: { quirkType: r.chunk.metadata.quirkType, tags: r.chunk.metadata.tags },
|
|
1014
|
+
},
|
|
1015
|
+
score: r.score,
|
|
1016
|
+
rawSimilarity: r.explanation?.scoreBreakdown?.rawVectorScore,
|
|
1017
|
+
})));
|
|
1018
|
+
const budgetMs = memCfg.toolErrorLatencyBudgetMs ?? 1500;
|
|
1019
|
+
// One recall, two bars: the floor decides which quirks are
|
|
1020
|
+
// candidates at all, the injection bar decides which are injected.
|
|
1021
|
+
// A candidate between the two is a "probable match": it suppresses
|
|
1022
|
+
// quirk creation but is only injected when no confident match
|
|
1023
|
+
// exists.
|
|
1024
|
+
const injectBar = memCfg.toolErrorMinScore ?? 0.7;
|
|
1025
|
+
const floorBar = memCfg.toolErrorCreateMinScore ?? 0.6;
|
|
1026
|
+
const topK = memCfg.toolErrorTopK ?? 2;
|
|
1027
|
+
let timer;
|
|
1028
|
+
const recallResult = await Promise.race([
|
|
1029
|
+
recallToolErrorQuirks(recall, info, state, {
|
|
1030
|
+
minScore: floorBar,
|
|
1031
|
+
injectMinScore: injectBar,
|
|
1032
|
+
topK,
|
|
1033
|
+
minTokenOverlap: memCfg.toolErrorMinTokenOverlap ?? 1,
|
|
1034
|
+
// The injection budget limits CONTEXT, not memory: when it is
|
|
1035
|
+
// spent we still need the candidate list to decide whether a
|
|
1036
|
+
// quirk already covers this failure (and whether to create
|
|
1037
|
+
// one). The cooldown still applies.
|
|
1038
|
+
enforceBudget: state.hasBudget(),
|
|
1039
|
+
}),
|
|
1040
|
+
new Promise((resolve) => {
|
|
1041
|
+
timer = setTimeout(() => resolve(undefined), budgetMs);
|
|
1042
|
+
}),
|
|
1043
|
+
]).catch(() => undefined);
|
|
1044
|
+
if (timer)
|
|
1045
|
+
clearTimeout(timer);
|
|
1046
|
+
if (recallResult && !recallResult.blocked) {
|
|
1047
|
+
// Tier 1: confident matches (>= inject bar). Tier 2: probable
|
|
1048
|
+
// matches (>= floor bar) — used only when tier 1 is empty.
|
|
1049
|
+
const tier1 = recallResult.inject;
|
|
1050
|
+
const tier2 = recallResult.candidates.filter((c) => c.rawSimilarity < injectBar && !state.injectedQuirkIds.has(c.id));
|
|
1051
|
+
const hits = tier1.length > 0 ? tier1 : tier2.slice(0, topK);
|
|
1052
|
+
state.record(info, hits.map((h) => h.id));
|
|
1053
|
+
// No candidate at all → nothing in memory covers this failure.
|
|
1054
|
+
// Record one so a future occurrence can be answered from memory.
|
|
1055
|
+
// The duplicate check is EXACT (same tool + same cause class), not
|
|
1056
|
+
// a loose similarity floor: a floor low enough to catch a genuine
|
|
1057
|
+
// duplicate also catches unrelated quirks, which would suppress
|
|
1058
|
+
// creation on every real failure.
|
|
1059
|
+
let createdHit;
|
|
1060
|
+
let createdQuirk = false;
|
|
1061
|
+
const causeClass = classifyToolErrorCause(info.error)?.cls ?? causeClassOverride;
|
|
1062
|
+
// The duplicate check is EXACT: same tool + same cause class, read
|
|
1063
|
+
// from the `tool:<name>` / `cause:<class>` tags. A merely similar
|
|
1064
|
+
// quirk is still injected (it may genuinely help), but it must not
|
|
1065
|
+
// block recording the lesson — a 0.7 floor sits inside the measured
|
|
1066
|
+
// error-vs-noise band, so `candidates.length > 0` suppressed
|
|
1067
|
+
// creation for failures nothing in memory covered.
|
|
1068
|
+
const equivalent = causeClass !== undefined &&
|
|
1069
|
+
((await hasEquivalentToolGotcha(await getToolErrorQuirks(qDeps), info.tool, causeClass)) ||
|
|
1070
|
+
recallResult.candidates.some((c) => (c.tags ?? []).includes(`tool:${info.tool}`) &&
|
|
1071
|
+
(c.tags ?? []).includes(`cause:${causeClass}`)));
|
|
1072
|
+
if (!equivalent &&
|
|
1073
|
+
(source === "host" ? memCfg.autoCreateOnToolError : memCfg.autoCreateOnInterceptedError)) {
|
|
1074
|
+
const createState = sessionToolErrorCreateState.get(sessionID) ?? createToolErrorCreateState({
|
|
1075
|
+
maxPerSession: memCfg.toolErrorCreateMaxPerSession ?? 2,
|
|
1076
|
+
cooldownMs: memCfg.toolErrorCreateCooldownMs ?? 600_000,
|
|
1077
|
+
});
|
|
1078
|
+
boundedSet(sessionToolErrorCreateState, sessionID, createState, MAX_SESSION_MAP_SIZE);
|
|
1079
|
+
if (createState.shouldCreate(info)) {
|
|
1080
|
+
const content = buildToolErrorQuirkContent(info);
|
|
1081
|
+
const createBudgetMs = memCfg.toolErrorCreateLatencyBudgetMs ?? 2000;
|
|
1082
|
+
let createTimer;
|
|
1083
|
+
const created = await Promise.race([
|
|
1084
|
+
createToolErrorQuirk({ add: (q) => addQuirk(qDeps, q) }, info, content),
|
|
1085
|
+
new Promise((resolve) => {
|
|
1086
|
+
createTimer = setTimeout(() => resolve(undefined), createBudgetMs);
|
|
1087
|
+
}),
|
|
1088
|
+
]).catch(() => undefined);
|
|
1089
|
+
if (createTimer)
|
|
1090
|
+
clearTimeout(createTimer);
|
|
1091
|
+
if (created?.created && created.id) {
|
|
1092
|
+
createState.record(info, true);
|
|
1093
|
+
createdQuirk = true;
|
|
1094
|
+
// The proactive gotcha list changed — drop the cache so
|
|
1095
|
+
// the next model request sees the new gotcha.
|
|
1096
|
+
toolGotchaCache.delete(options.storePath);
|
|
1097
|
+
appendDebugLog(options.logFilePath, {
|
|
1098
|
+
scope: "quirk.tool-error",
|
|
1099
|
+
message: `created quirk ${created.id} for tool "${info.tool}" (source=${source})`,
|
|
1100
|
+
});
|
|
1101
|
+
if (memCfg.toolErrorInjectCreated) {
|
|
1102
|
+
createdHit = {
|
|
1103
|
+
id: created.id,
|
|
1104
|
+
content,
|
|
1105
|
+
quirkType: "gotcha",
|
|
1106
|
+
score: 1,
|
|
1107
|
+
rawSimilarity: 1,
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
else {
|
|
1112
|
+
// A trust-monitor rejection or a store failure — log it and
|
|
1113
|
+
// carry on; the tool error must never break the session.
|
|
1114
|
+
createState.record(info, false);
|
|
1115
|
+
appendDebugLog(options.logFilePath, {
|
|
1116
|
+
scope: "quirk.tool-error",
|
|
1117
|
+
message: `quirk not created for tool "${info.tool}": ${created?.reason ?? "timeout"}`,
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
const finalHits = createdHit ? [...hits, createdHit] : hits;
|
|
1123
|
+
if (finalHits.length > 0) {
|
|
1124
|
+
boundedSet(sessionPendingToolErrorQuirk, sessionID, {
|
|
1125
|
+
block: formatToolErrorQuirkBlock(info, finalHits, {
|
|
1126
|
+
heading: createdHit
|
|
1127
|
+
? `⚠ **Tool error** \`${info.tool}\` — quirk memory (incl. newly recorded):`
|
|
1128
|
+
: undefined,
|
|
1129
|
+
}),
|
|
1130
|
+
ts: Date.now(),
|
|
1131
|
+
}, MAX_SESSION_MAP_SIZE);
|
|
1132
|
+
}
|
|
1133
|
+
appendDebugLog(options.logFilePath, {
|
|
1134
|
+
scope: "quirk.tool-error",
|
|
1135
|
+
message: `tool error "${info.tool}": source=${source} candidates=${recallResult.candidates.length} injected=${finalHits.length} created=${createdQuirk ? "yes" : "no"}`,
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
else if (recallResult) {
|
|
1139
|
+
appendDebugLog(options.logFilePath, {
|
|
1140
|
+
scope: "quirk.tool-error",
|
|
1141
|
+
message: `tool error "${info.tool}": skipped (cooldown or budget)`,
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
else {
|
|
1145
|
+
appendDebugLog(options.logFilePath, {
|
|
1146
|
+
scope: "quirk.tool-error",
|
|
1147
|
+
message: `tool error "${info.tool}": skipped (recall timed out after ${budgetMs}ms)`,
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
954
1151
|
return {
|
|
955
1152
|
async event({ event }) {
|
|
956
1153
|
sessionLogger.onEvent(event);
|
|
1154
|
+
// Session-level errors (a failed model call, a provider error) are
|
|
1155
|
+
// reported on the event stream, not as tool errors, so the tool-error
|
|
1156
|
+
// path never saw them. Intercept them here so the same
|
|
1157
|
+
// recall -> inject path applies.
|
|
1158
|
+
//
|
|
1159
|
+
// The V2 event is `session.execution.failed` (measured live 2026-10-21:
|
|
1160
|
+
// the vocabulary is `session.execution.{started,succeeded,failed}` and
|
|
1161
|
+
// the payload is `{ sessionID, error }`); `session.error` is the legacy
|
|
1162
|
+
// name and is never emitted by V2. V2 carries the payload in `data`,
|
|
1163
|
+
// V1 in `properties` — V2 never sets `properties` at all.
|
|
1164
|
+
try {
|
|
1165
|
+
const evType = event.type;
|
|
1166
|
+
if (evType === "session.execution.failed" || evType === "session.error") {
|
|
1167
|
+
const payload = eventPayload(event);
|
|
1168
|
+
const sessionID = typeof payload?.sessionID === "string" ? payload.sessionID : undefined;
|
|
1169
|
+
const detected = detectSessionError(payload?.error);
|
|
1170
|
+
if (sessionID && detected) {
|
|
1171
|
+
const info = { tool: "session", error: detected.text, sessionID };
|
|
1172
|
+
await interceptError(info, "session", detected.causeClass);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
catch {
|
|
1177
|
+
// Non-critical — must never throw
|
|
1178
|
+
}
|
|
957
1179
|
// Accumulate the most recent assistant message's text via streaming deltas.
|
|
958
1180
|
// Used to build the 2-message retrieval query in chat.message.
|
|
1181
|
+
//
|
|
1182
|
+
// V2 renamed these events: `message.updated` / `message.part.updated`
|
|
1183
|
+
// never fire (measured live 2026-10-21: zero occurrences across a full
|
|
1184
|
+
// session), and the payload moved from `properties` to `data` — so the
|
|
1185
|
+
// V1 branches below were DEAD on V2 and the assistant text was NEVER
|
|
1186
|
+
// accumulated, leaving the auto-inject query with the user message
|
|
1187
|
+
// only. The V2 equivalents are `session.text.started` and
|
|
1188
|
+
// `session.text.delta`, both carrying `{ sessionID, assistantMessageID }`.
|
|
959
1189
|
try {
|
|
960
|
-
|
|
1190
|
+
const evType = event.type;
|
|
1191
|
+
if (evType === "session.text.delta") {
|
|
1192
|
+
const data = eventPayload(event);
|
|
1193
|
+
const sessionID = data?.sessionID;
|
|
1194
|
+
const messageID = data?.assistantMessageID;
|
|
1195
|
+
const delta = data?.delta;
|
|
1196
|
+
if (typeof sessionID === "string" &&
|
|
1197
|
+
typeof messageID === "string" &&
|
|
1198
|
+
typeof delta === "string") {
|
|
1199
|
+
// A new assistant message id means a new message: start over.
|
|
1200
|
+
// (One message can carry several text blocks; they share the id.)
|
|
1201
|
+
if (sessionAssistantMessageId.get(sessionID) !== messageID) {
|
|
1202
|
+
boundedSet(sessionAssistantMessageId, sessionID, messageID, MAX_SESSION_MAP_SIZE);
|
|
1203
|
+
boundedSet(sessionAssistantText, sessionID, delta, MAX_SESSION_MAP_SIZE);
|
|
1204
|
+
}
|
|
1205
|
+
else {
|
|
1206
|
+
const existing = sessionAssistantText.get(sessionID) ?? "";
|
|
1207
|
+
boundedSet(sessionAssistantText, sessionID, existing + delta, MAX_SESSION_MAP_SIZE);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
else if (event.type === "message.updated") {
|
|
961
1212
|
const info = event.properties;
|
|
962
1213
|
const msgInfo = info?.info;
|
|
963
1214
|
if (msgInfo?.role === "assistant" &&
|
|
@@ -1027,149 +1278,27 @@ export function createRagHooks(options) {
|
|
|
1027
1278
|
if (errorText && errorText.length > 0) {
|
|
1028
1279
|
const info = { tool: input.tool, error: errorText, sessionID: input.sessionID };
|
|
1029
1280
|
results.push(toToolErrorCaptureEntry(info));
|
|
1281
|
+
await interceptError(info, "host");
|
|
1282
|
+
}
|
|
1283
|
+
else if (input.status !== "error") {
|
|
1284
|
+
// The host reported SUCCESS. The failure may still be in the output:
|
|
1285
|
+
// a command that exits non-zero, a script that raises, a file that
|
|
1286
|
+
// cannot be read. Those are the most common real failures in an
|
|
1287
|
+
// agent session, and they used to be invisible — the host reports
|
|
1288
|
+
// them as `status=completed`.
|
|
1030
1289
|
const memCfg = getEffectiveCfg().memory;
|
|
1031
|
-
if (memCfg?.enabled && memCfg.
|
|
1032
|
-
const
|
|
1033
|
-
|
|
1034
|
-
maxPerSession: memCfg.toolErrorMaxPerSession ?? 3,
|
|
1290
|
+
if (memCfg?.enabled && memCfg.interceptAllErrors) {
|
|
1291
|
+
const detected = detectOutputError(input.tool, output.output ?? "", {
|
|
1292
|
+
exitCode: extractExitCode(output.metadata),
|
|
1035
1293
|
});
|
|
1036
|
-
|
|
1037
|
-
const qDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1038
|
-
// `explain: true` keeps the raw vector similarity on each result —
|
|
1039
|
-
// the confidence-discounted `score` is not comparable to a
|
|
1040
|
-
// similarity threshold, and the tiering below needs the raw value.
|
|
1041
|
-
const recall = (query, recallOpts) => recallQuirks(qDeps, query, { ...recallOpts, explain: true }).then((rs) => rs.map((r) => ({
|
|
1042
|
-
chunk: {
|
|
1043
|
-
id: r.chunk.id,
|
|
1044
|
-
content: r.chunk.content,
|
|
1045
|
-
metadata: { quirkType: r.chunk.metadata.quirkType, tags: r.chunk.metadata.tags },
|
|
1046
|
-
},
|
|
1047
|
-
score: r.score,
|
|
1048
|
-
rawSimilarity: r.explanation?.scoreBreakdown?.rawVectorScore,
|
|
1049
|
-
})));
|
|
1050
|
-
const budgetMs = memCfg.toolErrorLatencyBudgetMs ?? 1500;
|
|
1051
|
-
// One recall, two bars: the floor decides which quirks are
|
|
1052
|
-
// candidates at all, the injection bar decides which are injected.
|
|
1053
|
-
// A candidate between the two is a "probable match": it suppresses
|
|
1054
|
-
// quirk creation but is only injected when no confident match
|
|
1055
|
-
// exists.
|
|
1056
|
-
const injectBar = memCfg.toolErrorMinScore ?? 0.7;
|
|
1057
|
-
const floorBar = memCfg.toolErrorCreateMinScore ?? 0.6;
|
|
1058
|
-
const topK = memCfg.toolErrorTopK ?? 2;
|
|
1059
|
-
let timer;
|
|
1060
|
-
const recallResult = await Promise.race([
|
|
1061
|
-
recallToolErrorQuirks(recall, info, state, {
|
|
1062
|
-
minScore: floorBar,
|
|
1063
|
-
injectMinScore: injectBar,
|
|
1064
|
-
topK,
|
|
1065
|
-
minTokenOverlap: memCfg.toolErrorMinTokenOverlap ?? 1,
|
|
1066
|
-
// The injection budget limits CONTEXT, not memory: when it is
|
|
1067
|
-
// spent we still need the candidate list to decide whether a
|
|
1068
|
-
// quirk already covers this failure (and whether to create
|
|
1069
|
-
// one). The cooldown still applies.
|
|
1070
|
-
enforceBudget: state.hasBudget(),
|
|
1071
|
-
}),
|
|
1072
|
-
new Promise((resolve) => {
|
|
1073
|
-
timer = setTimeout(() => resolve(undefined), budgetMs);
|
|
1074
|
-
}),
|
|
1075
|
-
]).catch(() => undefined);
|
|
1076
|
-
if (timer)
|
|
1077
|
-
clearTimeout(timer);
|
|
1078
|
-
if (recallResult && !recallResult.blocked) {
|
|
1079
|
-
// Tier 1: confident matches (>= inject bar). Tier 2: probable
|
|
1080
|
-
// matches (>= floor bar) — used only when tier 1 is empty.
|
|
1081
|
-
const tier1 = recallResult.inject;
|
|
1082
|
-
const tier2 = recallResult.candidates.filter((c) => c.rawSimilarity < injectBar && !state.injectedQuirkIds.has(c.id));
|
|
1083
|
-
const hits = tier1.length > 0 ? tier1 : tier2.slice(0, topK);
|
|
1084
|
-
state.record(info, hits.map((h) => h.id));
|
|
1085
|
-
// No candidate at all → nothing in memory covers this failure.
|
|
1086
|
-
// Record one so a future occurrence can be answered from memory.
|
|
1087
|
-
// The duplicate check is EXACT (same tool + same cause class), not
|
|
1088
|
-
// a loose similarity floor: a floor low enough to catch a genuine
|
|
1089
|
-
// duplicate also catches unrelated quirks, which would suppress
|
|
1090
|
-
// creation on every real failure.
|
|
1091
|
-
let createdHit;
|
|
1092
|
-
let createdQuirk = false;
|
|
1093
|
-
const causeClass = classifyToolErrorCause(info.error)?.cls;
|
|
1094
|
-
const equivalent = recallResult.candidates.length > 0 ||
|
|
1095
|
-
(causeClass !== undefined &&
|
|
1096
|
-
hasEquivalentToolGotcha(await getToolErrorQuirks(qDeps), info.tool, causeClass));
|
|
1097
|
-
if (!equivalent && memCfg.autoCreateOnToolError) {
|
|
1098
|
-
const createState = sessionToolErrorCreateState.get(input.sessionID) ?? createToolErrorCreateState({
|
|
1099
|
-
maxPerSession: memCfg.toolErrorCreateMaxPerSession ?? 2,
|
|
1100
|
-
cooldownMs: memCfg.toolErrorCreateCooldownMs ?? 600_000,
|
|
1101
|
-
});
|
|
1102
|
-
boundedSet(sessionToolErrorCreateState, input.sessionID, createState, MAX_SESSION_MAP_SIZE);
|
|
1103
|
-
if (createState.shouldCreate(info)) {
|
|
1104
|
-
const content = buildToolErrorQuirkContent(info);
|
|
1105
|
-
const createBudgetMs = memCfg.toolErrorCreateLatencyBudgetMs ?? 2000;
|
|
1106
|
-
let createTimer;
|
|
1107
|
-
const created = await Promise.race([
|
|
1108
|
-
createToolErrorQuirk({ add: (q) => addQuirk(qDeps, q) }, info, content),
|
|
1109
|
-
new Promise((resolve) => {
|
|
1110
|
-
createTimer = setTimeout(() => resolve(undefined), createBudgetMs);
|
|
1111
|
-
}),
|
|
1112
|
-
]).catch(() => undefined);
|
|
1113
|
-
if (createTimer)
|
|
1114
|
-
clearTimeout(createTimer);
|
|
1115
|
-
if (created?.created && created.id) {
|
|
1116
|
-
createState.record(info, true);
|
|
1117
|
-
createdQuirk = true;
|
|
1118
|
-
// The proactive gotcha list changed — drop the cache so
|
|
1119
|
-
// the next model request sees the new gotcha.
|
|
1120
|
-
toolGotchaCache.delete(options.storePath);
|
|
1121
|
-
appendDebugLog(options.logFilePath, {
|
|
1122
|
-
scope: "quirk.tool-error",
|
|
1123
|
-
message: `created quirk ${created.id} for tool "${input.tool}"`,
|
|
1124
|
-
});
|
|
1125
|
-
if (memCfg.toolErrorInjectCreated) {
|
|
1126
|
-
createdHit = {
|
|
1127
|
-
id: created.id,
|
|
1128
|
-
content,
|
|
1129
|
-
quirkType: "gotcha",
|
|
1130
|
-
score: 1,
|
|
1131
|
-
rawSimilarity: 1,
|
|
1132
|
-
};
|
|
1133
|
-
}
|
|
1134
|
-
}
|
|
1135
|
-
else {
|
|
1136
|
-
// A trust-monitor rejection or a store failure — log it and
|
|
1137
|
-
// carry on; the tool error must never break the session.
|
|
1138
|
-
createState.record(info, false);
|
|
1139
|
-
appendDebugLog(options.logFilePath, {
|
|
1140
|
-
scope: "quirk.tool-error",
|
|
1141
|
-
message: `quirk not created for tool "${input.tool}": ${created?.reason ?? "timeout"}`,
|
|
1142
|
-
});
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
const finalHits = createdHit ? [...hits, createdHit] : hits;
|
|
1147
|
-
if (finalHits.length > 0) {
|
|
1148
|
-
boundedSet(sessionPendingToolErrorQuirk, input.sessionID, {
|
|
1149
|
-
block: formatToolErrorQuirkBlock(info, finalHits, {
|
|
1150
|
-
heading: createdHit
|
|
1151
|
-
? `⚠ **Tool error** \`${info.tool}\` — quirk memory (incl. newly recorded):`
|
|
1152
|
-
: undefined,
|
|
1153
|
-
}),
|
|
1154
|
-
ts: Date.now(),
|
|
1155
|
-
}, MAX_SESSION_MAP_SIZE);
|
|
1156
|
-
}
|
|
1157
|
-
appendDebugLog(options.logFilePath, {
|
|
1158
|
-
scope: "quirk.tool-error",
|
|
1159
|
-
message: `tool error "${input.tool}": candidates=${recallResult.candidates.length} injected=${finalHits.length} created=${createdQuirk ? "yes" : "no"}`,
|
|
1160
|
-
});
|
|
1161
|
-
}
|
|
1162
|
-
else if (recallResult) {
|
|
1294
|
+
if (detected) {
|
|
1163
1295
|
appendDebugLog(options.logFilePath, {
|
|
1164
1296
|
scope: "quirk.tool-error",
|
|
1165
|
-
message: `tool
|
|
1166
|
-
});
|
|
1167
|
-
}
|
|
1168
|
-
else {
|
|
1169
|
-
appendDebugLog(options.logFilePath, {
|
|
1170
|
-
scope: "quirk.tool-error",
|
|
1171
|
-
message: `tool error "${input.tool}": skipped (recall timed out after ${budgetMs}ms)`,
|
|
1297
|
+
message: `tool "${input.tool}" status=completed but its output reports a failure (${detected.causeClass ?? "unknown"})`,
|
|
1172
1298
|
});
|
|
1299
|
+
const info = { tool: input.tool, error: detected.text, sessionID: input.sessionID };
|
|
1300
|
+
results.push(toToolErrorCaptureEntry(info));
|
|
1301
|
+
await interceptError(info, "output", detected.causeClass);
|
|
1173
1302
|
}
|
|
1174
1303
|
}
|
|
1175
1304
|
}
|
|
@@ -1259,55 +1388,41 @@ export function createRagHooks(options) {
|
|
|
1259
1388
|
if (wikiMode?.enabled && wikiMode.systemPrompt) {
|
|
1260
1389
|
output.system.unshift(wikiMode.systemPrompt);
|
|
1261
1390
|
}
|
|
1262
|
-
// Inject relevant quirks into system prompt when memory.autoInject is enabled
|
|
1263
1391
|
try {
|
|
1264
|
-
|
|
1265
|
-
|
|
1392
|
+
// Inject relevant quirks into the system prompt (memory.autoInject).
|
|
1393
|
+
// The selector is shared with the chat.message path — one gate, one
|
|
1394
|
+
// ranking, one log line — so the two surfaces cannot drift apart again.
|
|
1395
|
+
const quirkSessionId = input?.sessionID;
|
|
1396
|
+
if (quirkSessionId) {
|
|
1266
1397
|
const memCfg = getEffectiveCfg().memory;
|
|
1267
1398
|
if (memCfg?.enabled && memCfg?.autoInject) {
|
|
1268
|
-
const assistantText = sessionAssistantText.get(
|
|
1269
|
-
const userReq = sessionPrevUserReq.get(
|
|
1399
|
+
const assistantText = sessionAssistantText.get(quirkSessionId) ?? "";
|
|
1400
|
+
const userReq = sessionPrevUserReq.get(quirkSessionId) ?? "";
|
|
1270
1401
|
const query = [assistantText, userReq].filter((t) => t.length > 0).join("\n");
|
|
1271
1402
|
if (query.length > 0) {
|
|
1272
1403
|
const quirkDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1404
|
+
const injectedSet = getOrCreateSessionSet(sessionInjectedQuirks, quirkSessionId, MAX_SESSION_MAP_SIZE);
|
|
1405
|
+
const selection = await selectAutoInjectQuirksWithinBudget((q, o) => recallQuirks(quirkDeps, q, { ...o, excludeTags: [TOOL_ERROR_QUIRK_TAG] }), {
|
|
1406
|
+
query,
|
|
1407
|
+
userText: userReq,
|
|
1408
|
+
options: {
|
|
1277
1409
|
topK: memCfg.autoInjectTopK ?? 1,
|
|
1410
|
+
minTokenOverlap: memCfg.autoInjectMinTokenOverlap ?? 2,
|
|
1278
1411
|
minScore: memCfg.autoInjectMinScore ?? 0.75,
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
const injectedSet = getOrCreateSessionSet(sessionInjectedQuirks, sessionId, MAX_SESSION_MAP_SIZE);
|
|
1294
|
-
quirkResults = quirkResults.filter((qr) => !injectedSet.has(qr.chunk.id));
|
|
1295
|
-
// Lexical gate: drop quirks that match only the prior assistant text (no token
|
|
1296
|
-
// overlap with the user's actual request) — prevents meta-quirks (quirks about
|
|
1297
|
-
// quirks) from being injected into unrelated tasks. Disabled when autoInjectMinTokenOverlap=0.
|
|
1298
|
-
const minTokenOverlap = memCfg.autoInjectMinTokenOverlap ?? 2;
|
|
1299
|
-
if (minTokenOverlap > 0 && userReq.length > 0) {
|
|
1300
|
-
quirkResults = quirkResults.filter((qr) => sharedWords(qr.chunk.content, userReq) >= minTokenOverlap);
|
|
1301
|
-
}
|
|
1302
|
-
if (quirkResults.length > 0) {
|
|
1303
|
-
const lines = ["", "⚠ **Relevant quirks for this task:**", ""];
|
|
1304
|
-
for (const qr of quirkResults) {
|
|
1305
|
-
const m = qr.chunk.metadata;
|
|
1306
|
-
const badge = m.quirkType ? `[${m.quirkType}] ` : "";
|
|
1307
|
-
lines.push(`- ${badge}${qr.chunk.content}`);
|
|
1308
|
-
injectedSet.add(qr.chunk.id);
|
|
1309
|
-
}
|
|
1310
|
-
output.system.unshift(lines.join("\n"));
|
|
1412
|
+
injectedIds: injectedSet,
|
|
1413
|
+
},
|
|
1414
|
+
}, memCfg.autoInjectLatencyBudgetMs ?? 2000);
|
|
1415
|
+
appendDebugLog(options.logFilePath, {
|
|
1416
|
+
scope: "quirk.auto-inject",
|
|
1417
|
+
message: `system: ${describeAutoInjectSelection(selection)} req="${userReq.slice(0, 120)}"`,
|
|
1418
|
+
});
|
|
1419
|
+
if (selection.hits.length > 0) {
|
|
1420
|
+
for (const hit of selection.hits)
|
|
1421
|
+
injectedSet.add(hit.id);
|
|
1422
|
+
output.system.unshift(formatAutoInjectBlock(selection.hits, {
|
|
1423
|
+
heading: "⚠ **Relevant quirks for this task:**",
|
|
1424
|
+
separator: false,
|
|
1425
|
+
}));
|
|
1311
1426
|
}
|
|
1312
1427
|
}
|
|
1313
1428
|
}
|
|
@@ -1598,49 +1713,25 @@ export function createRagHooks(options) {
|
|
|
1598
1713
|
const quirkQuery = [assistantText, text].filter((t) => t.length > 0).join("\n");
|
|
1599
1714
|
if (quirkQuery.length > 0) {
|
|
1600
1715
|
const quirkDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1601
|
-
const budgetMs = quirkMemoryCfg.autoInjectLatencyBudgetMs ?? 2000;
|
|
1602
|
-
// Both auto-inject paths (system prompt transform and this user-message
|
|
1603
|
-
// injection) use the same high autoInjectMinScore bar — injected quirks
|
|
1604
|
-
// occupy context every turn, so only strongly relevant ones qualify.
|
|
1605
|
-
// Manual recall_quirks calls use the lower recallMinScore.
|
|
1606
|
-
const minScore = quirkMemoryCfg.autoInjectMinScore ?? 0.75;
|
|
1607
|
-
let timer;
|
|
1608
|
-
let quirkResults = await Promise.race([
|
|
1609
|
-
recallQuirks(quirkDeps, quirkQuery, {
|
|
1610
|
-
topK: quirkMemoryCfg.autoInjectTopK ?? 1,
|
|
1611
|
-
minScore,
|
|
1612
|
-
// Auto-created tool-error quirks are raw error dumps — they
|
|
1613
|
-
// are surfaced by the tool-error path, not on unrelated turns.
|
|
1614
|
-
excludeTags: [TOOL_ERROR_QUIRK_TAG],
|
|
1615
|
-
})
|
|
1616
|
-
.then((r) => {
|
|
1617
|
-
if (timer)
|
|
1618
|
-
clearTimeout(timer);
|
|
1619
|
-
return r;
|
|
1620
|
-
}),
|
|
1621
|
-
new Promise((resolve) => {
|
|
1622
|
-
timer = setTimeout(() => resolve([]), budgetMs);
|
|
1623
|
-
}),
|
|
1624
|
-
]);
|
|
1625
|
-
// Dedup: skip quirks already injected into this session
|
|
1626
1716
|
const injectedSet = getOrCreateSessionSet(sessionInjectedQuirks, input.sessionID, MAX_SESSION_MAP_SIZE);
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1717
|
+
const selection = await selectAutoInjectQuirksWithinBudget((q, o) => recallQuirks(quirkDeps, q, { ...o, excludeTags: [TOOL_ERROR_QUIRK_TAG] }), {
|
|
1718
|
+
query: quirkQuery,
|
|
1719
|
+
userText: text,
|
|
1720
|
+
options: {
|
|
1721
|
+
topK: quirkMemoryCfg.autoInjectTopK ?? 1,
|
|
1722
|
+
minTokenOverlap: quirkMemoryCfg.autoInjectMinTokenOverlap ?? 2,
|
|
1723
|
+
minScore: quirkMemoryCfg.autoInjectMinScore ?? 0.75,
|
|
1724
|
+
injectedIds: injectedSet,
|
|
1725
|
+
},
|
|
1726
|
+
}, quirkMemoryCfg.autoInjectLatencyBudgetMs ?? 2000);
|
|
1727
|
+
appendDebugLog(options.logFilePath, {
|
|
1728
|
+
scope: "quirk.auto-inject",
|
|
1729
|
+
message: `chat.message: ${describeAutoInjectSelection(selection)} text="${text.slice(0, 120)}"`,
|
|
1730
|
+
});
|
|
1731
|
+
if (selection.hits.length > 0) {
|
|
1732
|
+
for (const hit of selection.hits)
|
|
1733
|
+
injectedSet.add(hit.id);
|
|
1734
|
+
const quirkBlock = formatAutoInjectBlock(selection.hits);
|
|
1644
1735
|
const parts = output?.parts ?? output?.message?.parts;
|
|
1645
1736
|
if (Array.isArray(parts) && parts.length > 0) {
|
|
1646
1737
|
const first = parts[0];
|