opencode-rag-plugin 2.9.0 → 2.9.2
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/cli/commands/describe-image.js +3 -1
- package/dist/core/config.d.ts +16 -0
- package/dist/core/config.js +2 -0
- package/dist/core/paths.d.ts +27 -0
- package/dist/core/paths.js +42 -0
- package/dist/mcp/handlers.d.ts +1 -1
- package/dist/mcp/handlers.js +5 -2
- package/dist/opencode/tools.js +5 -2
- package/dist/plugin.js +313 -223
- 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/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) {
|
|
@@ -952,13 +973,242 @@ export function createRagHooks(options) {
|
|
|
952
973
|
scope: "plugin",
|
|
953
974
|
message: `Registered tools: ${toolNames}`,
|
|
954
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
|
+
};
|
|
955
1151
|
return {
|
|
956
1152
|
async event({ event }) {
|
|
957
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
|
+
}
|
|
958
1179
|
// Accumulate the most recent assistant message's text via streaming deltas.
|
|
959
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 }`.
|
|
960
1189
|
try {
|
|
961
|
-
|
|
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") {
|
|
962
1212
|
const info = event.properties;
|
|
963
1213
|
const msgInfo = info?.info;
|
|
964
1214
|
if (msgInfo?.role === "assistant" &&
|
|
@@ -1028,149 +1278,27 @@ export function createRagHooks(options) {
|
|
|
1028
1278
|
if (errorText && errorText.length > 0) {
|
|
1029
1279
|
const info = { tool: input.tool, error: errorText, sessionID: input.sessionID };
|
|
1030
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`.
|
|
1031
1289
|
const memCfg = getEffectiveCfg().memory;
|
|
1032
|
-
if (memCfg?.enabled && memCfg.
|
|
1033
|
-
const
|
|
1034
|
-
|
|
1035
|
-
maxPerSession: memCfg.toolErrorMaxPerSession ?? 3,
|
|
1290
|
+
if (memCfg?.enabled && memCfg.interceptAllErrors) {
|
|
1291
|
+
const detected = detectOutputError(input.tool, output.output ?? "", {
|
|
1292
|
+
exitCode: extractExitCode(output.metadata),
|
|
1036
1293
|
});
|
|
1037
|
-
|
|
1038
|
-
const qDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1039
|
-
// `explain: true` keeps the raw vector similarity on each result —
|
|
1040
|
-
// the confidence-discounted `score` is not comparable to a
|
|
1041
|
-
// similarity threshold, and the tiering below needs the raw value.
|
|
1042
|
-
const recall = (query, recallOpts) => recallQuirks(qDeps, query, { ...recallOpts, explain: true }).then((rs) => rs.map((r) => ({
|
|
1043
|
-
chunk: {
|
|
1044
|
-
id: r.chunk.id,
|
|
1045
|
-
content: r.chunk.content,
|
|
1046
|
-
metadata: { quirkType: r.chunk.metadata.quirkType, tags: r.chunk.metadata.tags },
|
|
1047
|
-
},
|
|
1048
|
-
score: r.score,
|
|
1049
|
-
rawSimilarity: r.explanation?.scoreBreakdown?.rawVectorScore,
|
|
1050
|
-
})));
|
|
1051
|
-
const budgetMs = memCfg.toolErrorLatencyBudgetMs ?? 1500;
|
|
1052
|
-
// One recall, two bars: the floor decides which quirks are
|
|
1053
|
-
// candidates at all, the injection bar decides which are injected.
|
|
1054
|
-
// A candidate between the two is a "probable match": it suppresses
|
|
1055
|
-
// quirk creation but is only injected when no confident match
|
|
1056
|
-
// exists.
|
|
1057
|
-
const injectBar = memCfg.toolErrorMinScore ?? 0.7;
|
|
1058
|
-
const floorBar = memCfg.toolErrorCreateMinScore ?? 0.6;
|
|
1059
|
-
const topK = memCfg.toolErrorTopK ?? 2;
|
|
1060
|
-
let timer;
|
|
1061
|
-
const recallResult = await Promise.race([
|
|
1062
|
-
recallToolErrorQuirks(recall, info, state, {
|
|
1063
|
-
minScore: floorBar,
|
|
1064
|
-
injectMinScore: injectBar,
|
|
1065
|
-
topK,
|
|
1066
|
-
minTokenOverlap: memCfg.toolErrorMinTokenOverlap ?? 1,
|
|
1067
|
-
// The injection budget limits CONTEXT, not memory: when it is
|
|
1068
|
-
// spent we still need the candidate list to decide whether a
|
|
1069
|
-
// quirk already covers this failure (and whether to create
|
|
1070
|
-
// one). The cooldown still applies.
|
|
1071
|
-
enforceBudget: state.hasBudget(),
|
|
1072
|
-
}),
|
|
1073
|
-
new Promise((resolve) => {
|
|
1074
|
-
timer = setTimeout(() => resolve(undefined), budgetMs);
|
|
1075
|
-
}),
|
|
1076
|
-
]).catch(() => undefined);
|
|
1077
|
-
if (timer)
|
|
1078
|
-
clearTimeout(timer);
|
|
1079
|
-
if (recallResult && !recallResult.blocked) {
|
|
1080
|
-
// Tier 1: confident matches (>= inject bar). Tier 2: probable
|
|
1081
|
-
// matches (>= floor bar) — used only when tier 1 is empty.
|
|
1082
|
-
const tier1 = recallResult.inject;
|
|
1083
|
-
const tier2 = recallResult.candidates.filter((c) => c.rawSimilarity < injectBar && !state.injectedQuirkIds.has(c.id));
|
|
1084
|
-
const hits = tier1.length > 0 ? tier1 : tier2.slice(0, topK);
|
|
1085
|
-
state.record(info, hits.map((h) => h.id));
|
|
1086
|
-
// No candidate at all → nothing in memory covers this failure.
|
|
1087
|
-
// Record one so a future occurrence can be answered from memory.
|
|
1088
|
-
// The duplicate check is EXACT (same tool + same cause class), not
|
|
1089
|
-
// a loose similarity floor: a floor low enough to catch a genuine
|
|
1090
|
-
// duplicate also catches unrelated quirks, which would suppress
|
|
1091
|
-
// creation on every real failure.
|
|
1092
|
-
let createdHit;
|
|
1093
|
-
let createdQuirk = false;
|
|
1094
|
-
const causeClass = classifyToolErrorCause(info.error)?.cls;
|
|
1095
|
-
const equivalent = recallResult.candidates.length > 0 ||
|
|
1096
|
-
(causeClass !== undefined &&
|
|
1097
|
-
hasEquivalentToolGotcha(await getToolErrorQuirks(qDeps), info.tool, causeClass));
|
|
1098
|
-
if (!equivalent && memCfg.autoCreateOnToolError) {
|
|
1099
|
-
const createState = sessionToolErrorCreateState.get(input.sessionID) ?? createToolErrorCreateState({
|
|
1100
|
-
maxPerSession: memCfg.toolErrorCreateMaxPerSession ?? 2,
|
|
1101
|
-
cooldownMs: memCfg.toolErrorCreateCooldownMs ?? 600_000,
|
|
1102
|
-
});
|
|
1103
|
-
boundedSet(sessionToolErrorCreateState, input.sessionID, createState, MAX_SESSION_MAP_SIZE);
|
|
1104
|
-
if (createState.shouldCreate(info)) {
|
|
1105
|
-
const content = buildToolErrorQuirkContent(info);
|
|
1106
|
-
const createBudgetMs = memCfg.toolErrorCreateLatencyBudgetMs ?? 2000;
|
|
1107
|
-
let createTimer;
|
|
1108
|
-
const created = await Promise.race([
|
|
1109
|
-
createToolErrorQuirk({ add: (q) => addQuirk(qDeps, q) }, info, content),
|
|
1110
|
-
new Promise((resolve) => {
|
|
1111
|
-
createTimer = setTimeout(() => resolve(undefined), createBudgetMs);
|
|
1112
|
-
}),
|
|
1113
|
-
]).catch(() => undefined);
|
|
1114
|
-
if (createTimer)
|
|
1115
|
-
clearTimeout(createTimer);
|
|
1116
|
-
if (created?.created && created.id) {
|
|
1117
|
-
createState.record(info, true);
|
|
1118
|
-
createdQuirk = true;
|
|
1119
|
-
// The proactive gotcha list changed — drop the cache so
|
|
1120
|
-
// the next model request sees the new gotcha.
|
|
1121
|
-
toolGotchaCache.delete(options.storePath);
|
|
1122
|
-
appendDebugLog(options.logFilePath, {
|
|
1123
|
-
scope: "quirk.tool-error",
|
|
1124
|
-
message: `created quirk ${created.id} for tool "${input.tool}"`,
|
|
1125
|
-
});
|
|
1126
|
-
if (memCfg.toolErrorInjectCreated) {
|
|
1127
|
-
createdHit = {
|
|
1128
|
-
id: created.id,
|
|
1129
|
-
content,
|
|
1130
|
-
quirkType: "gotcha",
|
|
1131
|
-
score: 1,
|
|
1132
|
-
rawSimilarity: 1,
|
|
1133
|
-
};
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
else {
|
|
1137
|
-
// A trust-monitor rejection or a store failure — log it and
|
|
1138
|
-
// carry on; the tool error must never break the session.
|
|
1139
|
-
createState.record(info, false);
|
|
1140
|
-
appendDebugLog(options.logFilePath, {
|
|
1141
|
-
scope: "quirk.tool-error",
|
|
1142
|
-
message: `quirk not created for tool "${input.tool}": ${created?.reason ?? "timeout"}`,
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
|
-
const finalHits = createdHit ? [...hits, createdHit] : hits;
|
|
1148
|
-
if (finalHits.length > 0) {
|
|
1149
|
-
boundedSet(sessionPendingToolErrorQuirk, input.sessionID, {
|
|
1150
|
-
block: formatToolErrorQuirkBlock(info, finalHits, {
|
|
1151
|
-
heading: createdHit
|
|
1152
|
-
? `⚠ **Tool error** \`${info.tool}\` — quirk memory (incl. newly recorded):`
|
|
1153
|
-
: undefined,
|
|
1154
|
-
}),
|
|
1155
|
-
ts: Date.now(),
|
|
1156
|
-
}, MAX_SESSION_MAP_SIZE);
|
|
1157
|
-
}
|
|
1158
|
-
appendDebugLog(options.logFilePath, {
|
|
1159
|
-
scope: "quirk.tool-error",
|
|
1160
|
-
message: `tool error "${input.tool}": candidates=${recallResult.candidates.length} injected=${finalHits.length} created=${createdQuirk ? "yes" : "no"}`,
|
|
1161
|
-
});
|
|
1162
|
-
}
|
|
1163
|
-
else if (recallResult) {
|
|
1294
|
+
if (detected) {
|
|
1164
1295
|
appendDebugLog(options.logFilePath, {
|
|
1165
1296
|
scope: "quirk.tool-error",
|
|
1166
|
-
message: `tool
|
|
1167
|
-
});
|
|
1168
|
-
}
|
|
1169
|
-
else {
|
|
1170
|
-
appendDebugLog(options.logFilePath, {
|
|
1171
|
-
scope: "quirk.tool-error",
|
|
1172
|
-
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"})`,
|
|
1173
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);
|
|
1174
1302
|
}
|
|
1175
1303
|
}
|
|
1176
1304
|
}
|
|
@@ -1260,55 +1388,41 @@ export function createRagHooks(options) {
|
|
|
1260
1388
|
if (wikiMode?.enabled && wikiMode.systemPrompt) {
|
|
1261
1389
|
output.system.unshift(wikiMode.systemPrompt);
|
|
1262
1390
|
}
|
|
1263
|
-
// Inject relevant quirks into system prompt when memory.autoInject is enabled
|
|
1264
1391
|
try {
|
|
1265
|
-
|
|
1266
|
-
|
|
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) {
|
|
1267
1397
|
const memCfg = getEffectiveCfg().memory;
|
|
1268
1398
|
if (memCfg?.enabled && memCfg?.autoInject) {
|
|
1269
|
-
const assistantText = sessionAssistantText.get(
|
|
1270
|
-
const userReq = sessionPrevUserReq.get(
|
|
1399
|
+
const assistantText = sessionAssistantText.get(quirkSessionId) ?? "";
|
|
1400
|
+
const userReq = sessionPrevUserReq.get(quirkSessionId) ?? "";
|
|
1271
1401
|
const query = [assistantText, userReq].filter((t) => t.length > 0).join("\n");
|
|
1272
1402
|
if (query.length > 0) {
|
|
1273
1403
|
const quirkDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1274
|
-
const
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
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: {
|
|
1278
1409
|
topK: memCfg.autoInjectTopK ?? 1,
|
|
1410
|
+
minTokenOverlap: memCfg.autoInjectMinTokenOverlap ?? 2,
|
|
1279
1411
|
minScore: memCfg.autoInjectMinScore ?? 0.75,
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
const injectedSet = getOrCreateSessionSet(sessionInjectedQuirks, sessionId, MAX_SESSION_MAP_SIZE);
|
|
1295
|
-
quirkResults = quirkResults.filter((qr) => !injectedSet.has(qr.chunk.id));
|
|
1296
|
-
// Lexical gate: drop quirks that match only the prior assistant text (no token
|
|
1297
|
-
// overlap with the user's actual request) — prevents meta-quirks (quirks about
|
|
1298
|
-
// quirks) from being injected into unrelated tasks. Disabled when autoInjectMinTokenOverlap=0.
|
|
1299
|
-
const minTokenOverlap = memCfg.autoInjectMinTokenOverlap ?? 2;
|
|
1300
|
-
if (minTokenOverlap > 0 && userReq.length > 0) {
|
|
1301
|
-
quirkResults = quirkResults.filter((qr) => sharedWords(qr.chunk.content, userReq) >= minTokenOverlap);
|
|
1302
|
-
}
|
|
1303
|
-
if (quirkResults.length > 0) {
|
|
1304
|
-
const lines = ["", "⚠ **Relevant quirks for this task:**", ""];
|
|
1305
|
-
for (const qr of quirkResults) {
|
|
1306
|
-
const m = qr.chunk.metadata;
|
|
1307
|
-
const badge = m.quirkType ? `[${m.quirkType}] ` : "";
|
|
1308
|
-
lines.push(`- ${badge}${qr.chunk.content}`);
|
|
1309
|
-
injectedSet.add(qr.chunk.id);
|
|
1310
|
-
}
|
|
1311
|
-
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
|
+
}));
|
|
1312
1426
|
}
|
|
1313
1427
|
}
|
|
1314
1428
|
}
|
|
@@ -1599,49 +1713,25 @@ export function createRagHooks(options) {
|
|
|
1599
1713
|
const quirkQuery = [assistantText, text].filter((t) => t.length > 0).join("\n");
|
|
1600
1714
|
if (quirkQuery.length > 0) {
|
|
1601
1715
|
const quirkDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1602
|
-
const budgetMs = quirkMemoryCfg.autoInjectLatencyBudgetMs ?? 2000;
|
|
1603
|
-
// Both auto-inject paths (system prompt transform and this user-message
|
|
1604
|
-
// injection) use the same high autoInjectMinScore bar — injected quirks
|
|
1605
|
-
// occupy context every turn, so only strongly relevant ones qualify.
|
|
1606
|
-
// Manual recall_quirks calls use the lower recallMinScore.
|
|
1607
|
-
const minScore = quirkMemoryCfg.autoInjectMinScore ?? 0.75;
|
|
1608
|
-
let timer;
|
|
1609
|
-
let quirkResults = await Promise.race([
|
|
1610
|
-
recallQuirks(quirkDeps, quirkQuery, {
|
|
1611
|
-
topK: quirkMemoryCfg.autoInjectTopK ?? 1,
|
|
1612
|
-
minScore,
|
|
1613
|
-
// Auto-created tool-error quirks are raw error dumps — they
|
|
1614
|
-
// are surfaced by the tool-error path, not on unrelated turns.
|
|
1615
|
-
excludeTags: [TOOL_ERROR_QUIRK_TAG],
|
|
1616
|
-
})
|
|
1617
|
-
.then((r) => {
|
|
1618
|
-
if (timer)
|
|
1619
|
-
clearTimeout(timer);
|
|
1620
|
-
return r;
|
|
1621
|
-
}),
|
|
1622
|
-
new Promise((resolve) => {
|
|
1623
|
-
timer = setTimeout(() => resolve([]), budgetMs);
|
|
1624
|
-
}),
|
|
1625
|
-
]);
|
|
1626
|
-
// Dedup: skip quirks already injected into this session
|
|
1627
1716
|
const injectedSet = getOrCreateSessionSet(sessionInjectedQuirks, input.sessionID, MAX_SESSION_MAP_SIZE);
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
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);
|
|
1645
1735
|
const parts = output?.parts ?? output?.message?.parts;
|
|
1646
1736
|
if (Array.isArray(parts) && parts.length > 0) {
|
|
1647
1737
|
const first = parts[0];
|