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.
@@ -82,6 +82,31 @@ const ERROR_CAUSES = [
82
82
  pattern: /timed? ?out|timeout|etimedout/i,
83
83
  cause: "the operation timed out",
84
84
  },
85
+ // The classes below cover failures detected in a tool's OUTPUT rather than
86
+ // reported by the host (see src/quirks/error-signals.ts). They are appended
87
+ // so the pre-existing precedence above is unchanged - a `ENOENT` in a
88
+ // command's output stays `path`, which is more actionable than "the
89
+ // command exited non-zero".
90
+ {
91
+ cls: "runtime",
92
+ pattern: /traceback \(most recent call last\)|^(?:type|reference|syntax|range|uri)error:/im,
93
+ cause: "the program raised an unhandled exception",
94
+ },
95
+ {
96
+ cls: "tooling",
97
+ pattern: /npm err!|eresolve|peer dep/i,
98
+ cause: "the package manager rejected the operation",
99
+ },
100
+ {
101
+ cls: "crash",
102
+ pattern: /segmentation fault|core dumped|panic:/i,
103
+ cause: "the process crashed",
104
+ },
105
+ {
106
+ cls: "exit-code",
107
+ pattern: /exited with code|command failed/i,
108
+ cause: "the command exited with a non-zero status",
109
+ },
85
110
  ];
86
111
  /**
87
112
  * Cause classes that are worth surfacing BEFORE the tool is called.
@@ -63,6 +63,12 @@ export interface ToolErrorQuirkHit {
63
63
  score: number;
64
64
  /** Raw vector similarity (0-1) — the value thresholds are compared against. */
65
65
  rawSimilarity: number;
66
+ /**
67
+ * The quirk's tags. Carried so the caller's duplicate check can be EXACT
68
+ * (`tool:<name>` + `cause:<class>`) without a second lookup — the content is
69
+ * embedded error text, not a reliable identity.
70
+ */
71
+ tags?: string[];
66
72
  }
67
73
  /** Tunables for the tool-error quirk path. */
68
74
  export interface ToolErrorRecallOptions {
@@ -130,6 +130,7 @@ export async function recallToolErrorQuirks(recall, info, state, options) {
130
130
  quirkType: hit.chunk.metadata?.quirkType,
131
131
  score: hit.score,
132
132
  rawSimilarity: hit.rawSimilarity ?? hit.score,
133
+ tags: hit.chunk.metadata?.tags,
133
134
  });
134
135
  }
135
136
  candidates.sort((a, b) => b.rawSimilarity - a.rawSimilarity);
@@ -2,10 +2,35 @@
2
2
  * @fileoverview Performs hybrid vector-keyword retrieval with configurable scoring and explanation.
3
3
  */
4
4
  import type { EmbeddingProvider, KeywordIndex, RerankProvider, VectorStore, SearchResult, MetadataFilter } from "../core/interfaces.js";
5
+ /**
6
+ * How the `minScore` gate reads the score.
7
+ *
8
+ * - `"fused"` — compare against the raw fused RRF score. Its scale depends on
9
+ * `keywordWeight`, so the same threshold means different things at
10
+ * different weights.
11
+ * - `"normalized"` — compare against the score divided by the maximum that
12
+ * result could reach. Scale-free: the threshold keeps its meaning when
13
+ * `keywordWeight` changes.
14
+ */
15
+ export type MinScoreMode = "fused" | "normalized";
5
16
  /** Options controlling the retrieval behavior. */
6
17
  export interface RetrieveOptions {
7
18
  topK?: number;
8
19
  minScore?: number;
20
+ /**
21
+ * How the `minScore` gate reads the score.
22
+ *
23
+ * - `"fused"` (default): the gate compares against the raw fused RRF score.
24
+ * That score's scale DEPENDS on `keywordWeight` — a vector-only hit can
25
+ * never exceed `(1 - kw)`, so at `kw = 0.4` the fused score maxes out at
26
+ * 0.6 and a fixed `minScore` of 0.65 silently demands a DUAL hit.
27
+ * - `"normalized"`: the fused score is divided by the maximum that result
28
+ * could reach given the legs it has (a dual hit reaches the same maximum
29
+ * at every `keywordWeight`, a vector-only hit reaches `(1 - kw)` times
30
+ * that). The score becomes scale-free, so `minScore` means the same
31
+ * thing at every `keywordWeight`.
32
+ */
33
+ minScoreMode?: MinScoreMode;
9
34
  keywordIndex?: KeywordIndex;
10
35
  keywordWeight?: number;
11
36
  /** Keyword weight for symbol-style queries (a bare identifier like `cosineSimilarity`).
@@ -5,6 +5,18 @@ const FETCH_OVERFETCH_FACTOR = 3;
5
5
  const RRF_K = 60;
6
6
  /** Multiply raw RRF scores by (K+1) to normalize to ~[0,1]. */
7
7
  const RRF_NORMALIZE = RRF_K + 1;
8
+ /**
9
+ * The highest score a result with the given legs could reach (rank 0 in each).
10
+ *
11
+ * A dual hit reaches `(1 - kw) + kw` of the maximum — the same at every
12
+ * `keywordWeight`. A vector-only hit reaches `(1 - kw)` of it, a keyword-only
13
+ * hit `kw` of it. Dividing by this value is what makes the score scale-free.
14
+ */
15
+ function maxReachableScore(hasVector, hasKeyword, keywordWeight) {
16
+ const vector = hasVector ? ((1 - keywordWeight) * RRF_NORMALIZE) / (RRF_K + 1) : 0;
17
+ const keyword = hasKeyword ? (keywordWeight * RRF_NORMALIZE) / (RRF_K + 1) : 0;
18
+ return vector + keyword;
19
+ }
8
20
  const RERANK_DEFAULTS = {
9
21
  candidates: 20,
10
22
  maxDocChars: 1200,
@@ -122,6 +134,7 @@ export async function retrieve(query, embedder, store, options = {}) {
122
134
  try {
123
135
  const topK = options.topK ?? 10;
124
136
  const minScore = options.minScore ?? 0;
137
+ const minScoreMode = options.minScoreMode ?? "fused";
125
138
  const queryShape = detectQueryShape(query);
126
139
  const baseKw = options.keywordWeight ?? 0.4;
127
140
  // Symbol queries are exact-identifier lookups — keyword search is the strong
@@ -182,7 +195,12 @@ export async function retrieve(query, embedder, store, options = {}) {
182
195
  const kMultiplier = kR !== undefined ? keywordDemotion(chunk, docDemotion, testDemotion) : 1;
183
196
  const vContrib = vR !== undefined ? ((1 - kw) * RRF_NORMALIZE) / (RRF_K + vR + 1) : 0;
184
197
  const kContrib = kR !== undefined ? (kw * RRF_NORMALIZE) / (RRF_K + kR + 1) * kMultiplier : 0;
185
- const score = vContrib + kContrib;
198
+ const fusedScore = vContrib + kContrib;
199
+ // In "normalized" mode the score is divided by the maximum this result
200
+ // could reach, so the `minScore` gate keeps its meaning no matter what
201
+ // `keywordWeight` is set to.
202
+ const maxReachable = maxReachableScore(vR !== undefined, kR !== undefined, kw);
203
+ const score = minScoreMode === "normalized" && maxReachable > 0 ? fusedScore / maxReachable : fusedScore;
186
204
  const result = { chunk, score };
187
205
  if (options.explain) {
188
206
  result.explanation = {
@@ -194,6 +212,7 @@ export async function retrieve(query, embedder, store, options = {}) {
194
212
  keywordWeight: kw,
195
213
  vectorRank: vR,
196
214
  keywordRank: kR,
215
+ ...(minScoreMode === "normalized" ? { maxReachableScore: maxReachable } : {}),
197
216
  },
198
217
  queryShape,
199
218
  };
@@ -120,6 +120,23 @@ type V2ToolExecuteAfterEvent = {
120
120
  error?: unknown;
121
121
  message?: unknown;
122
122
  };
123
+ /**
124
+ * Join the text parts of a tool result's `content`.
125
+ *
126
+ * V2 delivers a completed tool result as an array of content parts. The
127
+ * shell tool uses one part per output line plus a separate part for the
128
+ * `Exited with code N` marker, so every part matters.
129
+ */
130
+ export declare function extractContentText(content: unknown): string | undefined;
131
+ /**
132
+ * Extract the raw text from a tool result's structured `output`.
133
+ *
134
+ * The shell tool reports `{ exit, truncated, output, status }` — the `output`
135
+ * field is the command's real stdout+stderr. Returning the whole object
136
+ * would hand the failure detector a JSON blob in which the command's text is
137
+ * escaped, which defeats every text rule.
138
+ */
139
+ export declare function extractStructuredOutput(output: unknown): string | undefined;
123
140
  /** V2 `prompt` hook event. */
124
141
  type V2PromptHookEvent = {
125
142
  sessionID: string;
@@ -32,6 +32,42 @@
32
32
  */
33
33
  import { findConfigFile, loadConfig } from "../core/config.js";
34
34
  import { ragPlugin, RAG_TOOL_NAMES } from "../plugin.js";
35
+ /**
36
+ * Join the text parts of a tool result's `content`.
37
+ *
38
+ * V2 delivers a completed tool result as an array of content parts. The
39
+ * shell tool uses one part per output line plus a separate part for the
40
+ * `Exited with code N` marker, so every part matters.
41
+ */
42
+ export function extractContentText(content) {
43
+ if (typeof content === "string")
44
+ return content;
45
+ if (!Array.isArray(content))
46
+ return undefined;
47
+ const texts = [];
48
+ for (const part of content) {
49
+ if (part && typeof part === "object") {
50
+ const text = part.text;
51
+ if (typeof text === "string" && text.length > 0)
52
+ texts.push(text);
53
+ }
54
+ }
55
+ return texts.length > 0 ? texts.join("\n") : undefined;
56
+ }
57
+ /**
58
+ * Extract the raw text from a tool result's structured `output`.
59
+ *
60
+ * The shell tool reports `{ exit, truncated, output, status }` — the `output`
61
+ * field is the command's real stdout+stderr. Returning the whole object
62
+ * would hand the failure detector a JSON blob in which the command's text is
63
+ * escaped, which defeats every text rule.
64
+ */
65
+ export function extractStructuredOutput(output) {
66
+ if (!output || typeof output !== "object")
67
+ return undefined;
68
+ const text = output.output;
69
+ return typeof text === "string" && text.length > 0 ? text : undefined;
70
+ }
35
71
  /**
36
72
  * Extract a human-readable error string from a V2 `execute.after` error event.
37
73
  * The exact error payload differs across OpenCode versions; probe the known
@@ -291,19 +327,30 @@ export async function registerRagPluginV2(ctx) {
291
327
  try {
292
328
  const isError = event.status === "error";
293
329
  const result = event.result;
330
+ // The COMPLETED branch carries its text as an ARRAY of content parts
331
+ // (measured live 2026-10-21: the shell tool returns one text part
332
+ // per line plus a separate `Exited with code N` part). Reading only
333
+ // `content` as a string fell through to `JSON.stringify(result.output)`
334
+ // — a JSON blob that does NOT contain the failure marker, so nothing
335
+ // downstream could see it. Join the text parts instead.
294
336
  const outputText = isError
295
337
  ? extractToolErrorText(event)
296
- : typeof result?.content === "string"
297
- ? result.content
298
- : result?.output !== undefined
299
- ? JSON.stringify(result.output)
300
- : "";
338
+ : extractContentText(result?.content) ??
339
+ extractStructuredOutput(result?.output) ??
340
+ (result?.output !== undefined ? JSON.stringify(result.output) : "");
301
341
  await toolAfterHook({
302
342
  sessionID: event.sessionID,
303
343
  tool: event.tool,
304
344
  callID: event.id,
305
345
  status: isError ? "error" : "completed",
306
- }, { output: outputText, error: isError ? outputText : undefined });
346
+ }, {
347
+ output: outputText,
348
+ // The metadata carries the structured exit code
349
+ // (`{ status, truncated, exit }` for the shell tool) — the most
350
+ // reliable failure signal there is, and it is not text.
351
+ metadata: result?.metadata,
352
+ error: isError ? outputText : undefined,
353
+ });
307
354
  }
308
355
  catch {
309
356
  // Non-critical — must never throw
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-rag-plugin",
3
- "version": "2.8.0",
3
+ "version": "2.9.1",
4
4
  "description": "OpenCode plugin for local-first RAG-based semantic code search",
5
5
  "type": "module",
6
6
  "main": "./dist/plugin-entry.js",