opencode-rag-plugin 2.4.2 → 2.4.4

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 CHANGED
@@ -196,7 +196,7 @@ See [Plugin documentation](doc/plugin.md#6-wiki-mode--slash-command-wiki) for th
196
196
 
197
197
  ## Quirk Memory
198
198
 
199
- OpenCodeRAG gives your agent **persistent, cross-session memory** of non-obvious facts — gotchas, preferences, decisions, and environment constraints — that it can recall and extend over time. Quirks are embedded and stored in the same vector store as your code, then **automatically injected into the agent's context on every user message** when their relevance score exceeds the configured threshold. Injection uses two thresholds: the stricter `recallMinScore` (0.72) for the user message context, and the more permissive `autoInjectMinScore` (0.45) for the system prompt. This lets the agent avoid repeating mistakes and accumulate project knowledge across sessions without manual recall.
199
+ OpenCodeRAG gives your agent **persistent, cross-session memory** of non-obvious facts - gotchas, preferences, decisions, and environment constraints - that it can recall and extend over time. Quirks are embedded and stored in the same vector store as your code, then **automatically injected into the agent's context on every user message** when their relevance score exceeds the configured threshold. Recall is gated by raw vector similarity (0-1, cosine mapped to [0,1]): `recallMinScore` (default 0.72) for manual `recall_quirks` calls, and the stricter `autoInjectMinScore` (default 0.75) for automatic injection - set it high (e.g. 0.85) to keep only strongly related quirks out of unrelated tasks. This lets the agent avoid repeating mistakes and accumulate project knowledge across sessions without manual recall.
200
200
 
201
201
  **Enabled by default.** Turn it on/off in `opencode-rag.json`:
202
202
 
@@ -206,9 +206,9 @@ OpenCodeRAG gives your agent **persistent, cross-session memory** of non-obvious
206
206
  "enabled": true,
207
207
  "autoInject": true,
208
208
  "minConfidence": 0.5,
209
- "recallMinScore": 0.8,
210
- "autoInjectMinScore": 0.6,
211
- "autoInjectTopK": 2,
209
+ "recallMinScore": 0.72,
210
+ "autoInjectMinScore": 0.75,
211
+ "autoInjectTopK": 1,
212
212
  "autoInjectLatencyBudgetMs": 2000,
213
213
  "decay": { "enabled": false, "halfLifeDays": 30 }
214
214
  }
@@ -238,7 +238,7 @@ opencode-rag quirk test "npm needs --legacy-peer-deps"
238
238
  # 99% confidence
239
239
  ```
240
240
 
241
- When `memory.autoInject` is `true`, the plugin checks for relevant quirks on every user message using the combined agent-response + user-query as the search query. Quirks are only injected when their relevance score exceeds the threshold — `recallMinScore` (default 0.72) for the user message, `autoInjectMinScore` (default 0.45) for the system prompt. A latency budget (`autoInjectLatencyBudgetMs`, default 2000ms) prevents slow embedders from blocking message processing. To avoid polluting the context window, each quirk is injected **at most once per session** — once recalled, it is filtered out from all subsequent auto-injections. Every `add_quirk` and every content-changing `update_quirk` is vetted by an immutable trust monitor that rejects destructive patterns (e.g. `rm -rf`, `force push`, `bypass security`). Outdated or fixed quirks should be corrected with `update_quirk` / `delete_quirk` rather than left to contradict newer memory. See [Plugin documentation](doc/plugin.md#9-quirk-memory-experiential-memory) and [CLI Reference: `quirk`](doc/cli.md#quirk).
241
+ When `memory.autoInject` is `true`, the plugin checks for relevant quirks on every user message using the combined agent-response + user-query as the search query. Quirks are only injected when their raw vector similarity to that query clears `autoInjectMinScore` (default 0.75) - the same threshold for the user-message and system-prompt injections; `recallMinScore` (default 0.72) is the bar for manual `recall_quirks` calls. A latency budget (`autoInjectLatencyBudgetMs`, default 2000ms) prevents slow embedders from blocking message processing. To avoid polluting the context window, each quirk is injected **at most once per session** — once recalled, it is filtered out from all subsequent auto-injections. Every `add_quirk` and every content-changing `update_quirk` is vetted by an immutable trust monitor that rejects destructive patterns (e.g. `rm -rf`, `force push`, `bypass security`). Outdated or fixed quirks should be corrected with `update_quirk` / `delete_quirk` rather than left to contradict newer memory. See [Plugin documentation](doc/plugin.md#9-quirk-memory-experiential-memory) and [CLI Reference: `quirk`](doc/cli.md#quirk).
242
242
 
243
243
  ## MCP Server (Optional)
244
244
 
@@ -231,13 +231,14 @@ export interface MemoryConfig {
231
231
  autoInject: boolean;
232
232
  /** Minimum confidence (0-1) for a quirk to be returned. */
233
233
  minConfidence: number;
234
- /** Minimum query-relevance score (0-1) for a quirk to be recalled. */
234
+ /** Minimum raw vector similarity (0-1, cosine mapped to [0,1]) for a quirk to be recalled by manual `recall_quirks` calls. */
235
235
  recallMinScore: number;
236
- /** Minimum relevance score for quirks to be AUTO-injected into the prompt
237
- * (both the system-prompt transform and the user message). Deliberately a
238
- * high bar: injected quirks occupy context on every turn, so only strongly
239
- * relevant ones should reach the prompt. Manual `recall_quirks` calls use
240
- * the lower `recallMinScore`. */
236
+ /** Minimum raw vector similarity (0-1, cosine mapped to [0,1]) for quirks to
237
+ * be AUTO-injected into the prompt (both the system-prompt transform and the
238
+ * user message). Deliberately a high bar: injected quirks occupy context on
239
+ * every turn, so only strongly related ones should reach the prompt - e.g.
240
+ * 0.85 admits only strongly related notes. Manual `recall_quirks` calls use
241
+ * `recallMinScore` instead. */
241
242
  autoInjectMinScore: number;
242
243
  /** Maximum latency budget (ms) for auto-inject quirk recall. If exceeded, injection is skipped. */
243
244
  autoInjectLatencyBudgetMs: number;
@@ -266,7 +267,7 @@ export interface MemoryConfig {
266
267
  * so recurring errors can become quirks.
267
268
  */
268
269
  injectOnToolError: boolean;
269
- /** Minimum relevance score (0-1) for a quirk to be injected after a tool error (default 0.7). */
270
+ /** Minimum raw vector similarity (0-1, cosine mapped to [0,1]) for a quirk to be injected after a tool error (default 0.7). */
270
271
  toolErrorMinScore: number;
271
272
  /** Max quirks injected per tool error (default 2). */
272
273
  toolErrorTopK: number;
@@ -532,8 +533,10 @@ export interface RagConfig {
532
533
  readNoResultsBehavior?: ReadNoResultsBehavior;
533
534
  /** Maximum related files shown when read results are empty. */
534
535
  readRelatedFilesMax?: number;
535
- /** Whether to inject RAG tool guidance into system prompts (default true). */
536
+ /** Whether to inject RAG tool guidance into system prompts when the session's tool catalog exposes the RAG tools (default true). */
536
537
  injectSystemPrompt?: boolean;
538
+ /** Whether to grant the read-only RAG tools to the built-in `explore` agent (default true). */
539
+ exploreAgentTools?: boolean;
537
540
  };
538
541
  /** Custom chunker module registrations. */
539
542
  chunkers?: ChunkerConfig[];
@@ -164,6 +164,7 @@ export const DEFAULT_CONFIG = {
164
164
  maxContextChunks: 10,
165
165
  readOverride: true,
166
166
  injectSystemPrompt: true,
167
+ exploreAgentTools: true,
167
168
  autoIndex: {
168
169
  enabled: false,
169
170
  debounceMs: 2000,
package/dist/plugin.d.ts CHANGED
@@ -37,6 +37,12 @@ type CreateRagHooksOptions = {
37
37
  /** Pre-created description provider for chunk descriptions. */
38
38
  descriptionProvider?: DescriptionProvider;
39
39
  };
40
+ /**
41
+ * Plugin tool names advertised by the mandatory guidance and granted to the
42
+ * built-in `explore` agent. `read` is deliberately absent — the read override
43
+ * shadows a built-in tool name and is ambiguous.
44
+ */
45
+ export declare const RAG_TOOL_NAMES: readonly ["search_semantic", "get_file_skeleton", "find_usages", "describe_image", "make_decision", "recall_quirks", "add_quirk", "update_quirk", "delete_quirk"];
40
46
  /**
41
47
  * Create the RAG plugin hook implementations for an OpenCode workspace.
42
48
  *
package/dist/plugin.js CHANGED
@@ -333,6 +333,47 @@ const defaultDependencies = {
333
333
  createStore: (storePath, dimension, config) => createVectorStore(config, storePath, dimension),
334
334
  retrieve,
335
335
  };
336
+ /**
337
+ * Plugin tool names advertised by the mandatory guidance and granted to the
338
+ * built-in `explore` agent. `read` is deliberately absent — the read override
339
+ * shadows a built-in tool name and is ambiguous.
340
+ */
341
+ export const RAG_TOOL_NAMES = [
342
+ "search_semantic",
343
+ "get_file_skeleton",
344
+ "find_usages",
345
+ "describe_image",
346
+ "make_decision",
347
+ "recall_quirks",
348
+ "add_quirk",
349
+ "update_quirk",
350
+ "delete_quirk",
351
+ ];
352
+ /**
353
+ * Built-in agents that ship with a permission policy denying every RAG tool
354
+ * (e.g. `explore`: deny all except read/glob/grep and the web tools). When the
355
+ * host sends no tool catalog, the guidance gate assumes they lack the tools —
356
+ * unless the explore tool grant (openCode.exploreAgentTools) is active.
357
+ */
358
+ const TOOLLESS_BUILTIN_AGENTS = new Set(["explore"]);
359
+ /**
360
+ * Decide whether the mandatory RAG guidance should be injected into the
361
+ * session's system prompt. OpenCode V2 passes the session's tool catalog to
362
+ * the context hook: advertise the tools only when at least one RAG tool is
363
+ * actually exposed. Restricted agents (`explore`) and custom permission
364
+ * overrides would otherwise receive an inert mandate referencing tools they
365
+ * cannot call. Hosts that do not send a catalog assume the legacy state —
366
+ * tool-less built-in agents stay skipped unless the explore tool grant is on.
367
+ */
368
+ function shouldInjectSystemGuidance(tools, agent, exploreToolsGranted) {
369
+ if (tools) {
370
+ return RAG_TOOL_NAMES.some((name) => name in tools);
371
+ }
372
+ if (agent !== undefined && TOOLLESS_BUILTIN_AGENTS.has(agent)) {
373
+ return exploreToolsGranted;
374
+ }
375
+ return true;
376
+ }
336
377
  /**
337
378
  * Format a list of relevant files (aggregated from chunks) for display.
338
379
  * Groups chunks by file path and sorts by maximum relevance score.
@@ -845,13 +886,18 @@ export function createRagHooks(options) {
845
886
  // Non-critical — must never throw
846
887
  }
847
888
  },
848
- async "experimental.chat.system.transform"(_input, output) {
889
+ async "experimental.chat.system.transform"(input, output) {
890
+ const cfg = getEffectiveCfg();
891
+ const guidanceEnabled = cfg.openCode.injectSystemPrompt !== false;
892
+ const exploreToolsGranted = cfg.openCode.exploreAgentTools !== false;
893
+ const injectGuidance = guidanceEnabled && shouldInjectSystemGuidance(input?.tools, input?.agent, exploreToolsGranted);
849
894
  appendDebugLog(options.logFilePath, {
850
895
  scope: "experimental.chat.system.transform",
851
- message: "system guidance injected",
896
+ message: injectGuidance
897
+ ? "system guidance injected"
898
+ : `system guidance skipped (${guidanceEnabled ? `no RAG tools in session; agent=${input?.agent ?? "unknown"}` : "injectSystemPrompt=false"})`,
852
899
  });
853
- const cfg = getEffectiveCfg();
854
- if (cfg.openCode.injectSystemPrompt !== false) {
900
+ if (injectGuidance) {
855
901
  const guidance = buildSystemGuidanceLines({ promptEnforcement: !!cfg.memory?.promptEnforcement, decisionEnabled: !!cfg.decision?.enabled, routeBeforeAsking: !!cfg.decision?.routeBeforeAsking });
856
902
  output.system.unshift(guidance.join("\n"));
857
903
  }
@@ -888,7 +934,7 @@ export function createRagHooks(options) {
888
934
  }
889
935
  // Inject relevant quirks into system prompt when memory.autoInject is enabled
890
936
  try {
891
- const sessionId = _input?.sessionID;
937
+ const sessionId = input?.sessionID;
892
938
  if (sessionId) {
893
939
  const memCfg = getEffectiveCfg().memory;
894
940
  if (memCfg?.enabled && memCfg?.autoInject) {
@@ -900,7 +946,7 @@ export function createRagHooks(options) {
900
946
  const budgetMs = memCfg.autoInjectLatencyBudgetMs ?? 2000;
901
947
  let timer;
902
948
  let quirkResults = await Promise.race([
903
- recallQuirks(quirkDeps, query, { topK: memCfg.autoInjectTopK ?? 1, minScore: memCfg.autoInjectMinScore })
949
+ recallQuirks(quirkDeps, query, { topK: memCfg.autoInjectTopK ?? 1, minScore: memCfg.autoInjectMinScore ?? 0.75 })
904
950
  .then((r) => {
905
951
  if (timer)
906
952
  clearTimeout(timer);
@@ -936,7 +982,7 @@ export function createRagHooks(options) {
936
982
  // Tool-error quirks: flush the pending block captured in tool.execute.after.
937
983
  // Freshness-bounded — a stale error must not leak into a later turn.
938
984
  try {
939
- const sessionId = _input?.sessionID;
985
+ const sessionId = input?.sessionID;
940
986
  if (sessionId) {
941
987
  const pending = sessionPendingToolErrorQuirk.get(sessionId);
942
988
  if (pending) {
@@ -76,12 +76,22 @@ export interface QuirkReconcileResult {
76
76
  * @returns Counts of what changed (all zero when already consistent).
77
77
  */
78
78
  export declare function reconcileQuirks(deps: QuirkReconcileDeps): Promise<QuirkReconcileResult>;
79
- /** Recall quirks matching a query, with confidence re-weighting. */
79
+ /**
80
+ * Recall quirks matching a query, gated on raw vector similarity and ranked by
81
+ * confidence-weighted similarity.
82
+ *
83
+ * The threshold is compared against the quirk's raw vector similarity
84
+ * (`(cosine + 1) / 2`, the stores' native 0-1 domain) — never against the
85
+ * hybrid rank-fusion score, whose top candidate of a small list always scores
86
+ * ~0.6+ regardless of relevance.
87
+ */
80
88
  export declare function recallQuirks(deps: QuirkStoreDeps, query: string, options?: {
81
89
  topK?: number;
82
90
  quirkType?: string;
83
91
  tags?: string[];
84
- /** Override recallMinScore from config. Used by auto-inject for a lower threshold. */
92
+ /** Override recallMinScore from config. Semantic similarity threshold (0-1,
93
+ * cosine mapped to [0,1] the same way the vector stores report raw scores).
94
+ * Auto-inject passes its own (usually higher) bar. */
85
95
  minScore?: number;
86
96
  }): Promise<SearchResult[]>;
87
97
  /** Lint quirks for low confidence, staleness, duplicates, and orphan source refs. */
@@ -489,7 +489,15 @@ export async function reconcileQuirks(deps) {
489
489
  }
490
490
  return result;
491
491
  }
492
- /** Recall quirks matching a query, with confidence re-weighting. */
492
+ /**
493
+ * Recall quirks matching a query, gated on raw vector similarity and ranked by
494
+ * confidence-weighted similarity.
495
+ *
496
+ * The threshold is compared against the quirk's raw vector similarity
497
+ * (`(cosine + 1) / 2`, the stores' native 0-1 domain) — never against the
498
+ * hybrid rank-fusion score, whose top candidate of a small list always scores
499
+ * ~0.6+ regardless of relevance.
500
+ */
493
501
  export async function recallQuirks(deps, query, options) {
494
502
  const topK = options?.topK ?? 10;
495
503
  const minConfidence = deps.cfg.memory?.minConfidence ?? 0.5;
@@ -499,20 +507,32 @@ export async function recallQuirks(deps, query, options) {
499
507
  // Type filtering happens in the post-filter below instead.
500
508
  const filter = { kinds: ["quirk"] };
501
509
  const recallMinScore = options?.minScore ?? deps.cfg.memory?.recallMinScore ?? 0.72;
510
+ // Fetch with the hybrid `minScore` gate disabled: the relevance decision is
511
+ // taken below against the RAW VECTOR SIMILARITY, not the rank-fusion score.
512
+ // The fused score is rank-based — the top quirk of a small candidate list
513
+ // always scores ~0.6+ no matter how unrelated it is — so a high threshold on
514
+ // it never filtered non-relevant quirks. `explain: true` exposes
515
+ // `rawVectorScore` for every fused candidate.
502
516
  const raw = await retrieve(query, deps.embedder, deps.store, {
503
517
  topK: topK * 3,
504
- minScore: recallMinScore,
518
+ minScore: 0,
519
+ explain: true,
505
520
  keywordIndex: deps.keywordIndex,
506
521
  keywordWeight: deps.cfg.retrieval.hybridSearch?.keywordWeight,
507
522
  hybridEnabled: true,
508
523
  queryPrefix: deps.cfg.embedding.queryPrefix,
509
524
  filter,
510
525
  });
511
- // Confidence re-weighting + type/tag filtering
526
+ // Confidence + semantic-similarity + type/tag filtering. The similarity gate
527
+ // is `(cosine + 1) / 2` in [0,1] — the same domain the vector stores report.
528
+ // A keyword-only candidate has rawVectorScore 0 and never passes minScore > 0.
512
529
  const filtered = raw.filter((r) => {
513
530
  const conf = r.chunk.metadata.confidence ?? 1;
514
531
  if (conf < minConfidence)
515
532
  return false;
533
+ const similarity = r.explanation?.scoreBreakdown?.rawVectorScore ?? 0;
534
+ if (similarity < recallMinScore)
535
+ return false;
516
536
  if (options?.quirkType && r.chunk.metadata.quirkType !== options.quirkType)
517
537
  return false;
518
538
  if (options?.tags?.length) {
@@ -522,10 +542,14 @@ export async function recallQuirks(deps, query, options) {
522
542
  }
523
543
  return true;
524
544
  });
525
- // Re-weight score by confidence, re-sort
545
+ // Rank by semantic similarity (confidence-weighted) and report that same
546
+ // signal as `score`, so top-K selection is relevance-ordered and callers
547
+ // display a meaningful number instead of the rank-fusion artifact.
526
548
  for (const r of filtered) {
527
549
  const conf = r.chunk.metadata.confidence ?? 1;
528
- r.score = r.score * Math.min(1, Math.max(0.01, conf));
550
+ const similarity = r.explanation?.scoreBreakdown?.rawVectorScore ?? 0;
551
+ r.score = similarity * Math.min(1, Math.max(0.01, conf));
552
+ delete r.explanation;
529
553
  }
530
554
  filtered.sort((a, b) => b.score - a.score);
531
555
  return filtered.slice(0, topK);
@@ -47,7 +47,14 @@ declare module "@opencode-ai/plugin" {
47
47
  output: { messages: { info: Message; parts: Part[] }[] }
48
48
  ) => Promise<void>;
49
49
  "experimental.chat.system.transform"?: (
50
- input: { sessionID?: string; model: Model },
50
+ input: {
51
+ sessionID?: string;
52
+ model: Model;
53
+ /** Session agent ID (OpenCode V2); absent when the host does not send it. */
54
+ agent?: string;
55
+ /** Tool catalog exposed to the session (OpenCode V2); absent when the host does not send it. */
56
+ tools?: Record<string, { description?: string; input?: unknown }>;
57
+ },
51
58
  output: { system: string[] }
52
59
  ) => Promise<void>;
53
60
  }
@@ -16,6 +16,10 @@
16
16
  * | `tool.execute.after` | `ctx.tool.hook("execute.after", ...)` |
17
17
  * | `event` | `ctx.event.subscribe({ signal })` |
18
18
  *
19
+ * Additional V2-only registration (no V1 equivalent): the read-only RAG tools
20
+ * are granted to the built-in `explore` agent via `ctx.agent.transform`
21
+ * (config `openCode.exploreAgentTools`, default on).
22
+ *
19
23
  * The V2 prompt hook exposes the user's text as a mutable `event.prompt.text`
20
24
  * instead of V1's parts-mutation contract; the adapter shims a V1-shaped
21
25
  * `output.parts` view around it and writes the mutated text back.
@@ -45,6 +49,24 @@ type V2EventDomain = {
45
49
  signal: AbortSignal;
46
50
  }): AsyncIterable<unknown>;
47
51
  };
52
+ /** Permission rule shape inside an agent definition (OpenCode V2 schema). */
53
+ type V2PermissionRule = {
54
+ action: string;
55
+ resource: string;
56
+ effect: "allow" | "deny" | "ask";
57
+ };
58
+ /** Mutable agent definition subset used by the explore tool grant. */
59
+ type V2AgentInfo = {
60
+ permissions?: V2PermissionRule[];
61
+ };
62
+ type V2AgentEditor = {
63
+ get(id: string): V2AgentInfo | undefined;
64
+ update(id: string, update: (agent: V2AgentInfo) => void): void;
65
+ };
66
+ type V2AgentDomain = {
67
+ transform(callback: (editor: V2AgentEditor) => void): Promise<V2Registration>;
68
+ reload(): Promise<void>;
69
+ };
48
70
  /** Structural subset of the OpenCode V2 plugin context. */
49
71
  export type V2Context = {
50
72
  location: {
@@ -54,6 +76,7 @@ export type V2Context = {
54
76
  tool: V2ToolDomain;
55
77
  session: V2SessionDomain;
56
78
  event: V2EventDomain;
79
+ agent?: V2AgentDomain;
57
80
  };
58
81
  /** A registered V2 tool definition (structural subset of Tool.Info). */
59
82
  type V2Tool = {
@@ -104,9 +127,19 @@ type V2PromptHookEvent = {
104
127
  text: string;
105
128
  };
106
129
  };
107
- /** V2 `context` hook event. */
130
+ /**
131
+ * V2 `context` hook event. `agent` and `tools` mirror the host's
132
+ * `SessionContext` (session agent ID and the tool catalog actually exposed to
133
+ * it); both stay optional so hosts that don't send them keep the legacy
134
+ * unconditional guidance injection.
135
+ */
108
136
  type V2ContextHookEvent = {
109
137
  sessionID: string;
138
+ agent?: string;
139
+ tools?: Record<string, {
140
+ description?: string;
141
+ input?: unknown;
142
+ }>;
110
143
  system: Array<{
111
144
  type: "text";
112
145
  text: string;
@@ -119,6 +152,14 @@ type V2ContextHookEvent = {
119
152
  export declare function zodArgToJsonSchema(schema: unknown): Record<string, unknown>;
120
153
  /** Convert a V1 `args` record (zod raw shape) to a JSON schema object. Exported for tests. */
121
154
  export declare function zodShapeToJsonSchema(shape: Record<string, unknown>): Record<string, unknown>;
155
+ /**
156
+ * Grant the read-only RAG tools to the built-in `explore` agent. Appends an
157
+ * `allow` rule per tool action AFTER the shipped deny-all policy (OpenCode
158
+ * resolves permissions with "last matching rule wins"); an existing explicit
159
+ * rule for a tool action — user-configured allow, ask, or deny — is respected
160
+ * and left untouched. No-op when the agent is absent. Exported for tests.
161
+ */
162
+ export declare function grantExploreToolPermissions(editor: V2AgentEditor): void;
122
163
  /**
123
164
  * Run the V1 `ragPlugin` factory for the V2 context's location and register
124
165
  * all returned hooks as V2 transforms/hooks. Returns a cleanup function that
@@ -16,6 +16,10 @@
16
16
  * | `tool.execute.after` | `ctx.tool.hook("execute.after", ...)` |
17
17
  * | `event` | `ctx.event.subscribe({ signal })` |
18
18
  *
19
+ * Additional V2-only registration (no V1 equivalent): the read-only RAG tools
20
+ * are granted to the built-in `explore` agent via `ctx.agent.transform`
21
+ * (config `openCode.exploreAgentTools`, default on).
22
+ *
19
23
  * The V2 prompt hook exposes the user's text as a mutable `event.prompt.text`
20
24
  * instead of V1's parts-mutation contract; the adapter shims a V1-shaped
21
25
  * `output.parts` view around it and writes the mutated text back.
@@ -26,7 +30,8 @@
26
30
  * queries and session-end extraction fall back gracefully.
27
31
  * - The read-tool override keeps its V1 execute contract (args + sessionID).
28
32
  */
29
- import { ragPlugin } from "../plugin.js";
33
+ import { findConfigFile, loadConfig } from "../core/config.js";
34
+ import { ragPlugin, RAG_TOOL_NAMES } from "../plugin.js";
30
35
  /**
31
36
  * Extract a human-readable error string from a V2 `execute.after` error event.
32
37
  * The exact error payload differs across OpenCode versions; probe the known
@@ -160,6 +165,25 @@ function v1ToolToV2(name, def, codemode) {
160
165
  // ────────────────────────────────────────────────────────────────────────────
161
166
  // Registration entry point
162
167
  // ────────────────────────────────────────────────────────────────────────────
168
+ /**
169
+ * Grant the read-only RAG tools to the built-in `explore` agent. Appends an
170
+ * `allow` rule per tool action AFTER the shipped deny-all policy (OpenCode
171
+ * resolves permissions with "last matching rule wins"); an existing explicit
172
+ * rule for a tool action — user-configured allow, ask, or deny — is respected
173
+ * and left untouched. No-op when the agent is absent. Exported for tests.
174
+ */
175
+ export function grantExploreToolPermissions(editor) {
176
+ if (!editor.get("explore"))
177
+ return;
178
+ editor.update("explore", (agent) => {
179
+ const rules = (agent.permissions ??= []);
180
+ for (const name of RAG_TOOL_NAMES) {
181
+ if (rules.some((rule) => rule.action === name))
182
+ continue;
183
+ rules.push({ action: name, resource: "*", effect: "allow" });
184
+ }
185
+ });
186
+ }
163
187
  /**
164
188
  * Run the V1 `ragPlugin` factory for the V2 context's location and register
165
189
  * all returned hooks as V2 transforms/hooks. Returns a cleanup function that
@@ -176,6 +200,18 @@ export async function registerRagPluginV2(ctx) {
176
200
  // to force the previous code-mode-only behavior.
177
201
  const codemode = typeof ctx.options?.codemode === "boolean" ? ctx.options.codemode : false;
178
202
  const registrations = [];
203
+ // Explore keeps its RAG tool grant across reloads; opt out via
204
+ // `openCode.exploreAgentTools: false` in opencode-rag.json.
205
+ let exploreToolsEnabled = true;
206
+ try {
207
+ const cfgPath = findConfigFile(ctx.location.directory);
208
+ if (cfgPath) {
209
+ exploreToolsEnabled = loadConfig(cfgPath, false).openCode.exploreAgentTools !== false;
210
+ }
211
+ }
212
+ catch {
213
+ // Malformed config — the V1 factory reports it; fall back to the default
214
+ }
179
215
  // ── Tools ────────────────────────────────────────────────────────────────
180
216
  const toolDefs = (hooks.tool ?? {});
181
217
  const toolEntries = Object.entries(toolDefs);
@@ -187,6 +223,20 @@ export async function registerRagPluginV2(ctx) {
187
223
  });
188
224
  registrations.push(registration);
189
225
  }
226
+ // Explore agent tool grant: hand the read-only RAG tools to the built-in
227
+ // search agent. The grant appends allow rules after the shipped deny-all
228
+ // policy (last matching rule wins) and respects explicit user rules.
229
+ if (ctx.agent && exploreToolsEnabled) {
230
+ try {
231
+ const registration = await ctx.agent.transform((editor) => {
232
+ grantExploreToolPermissions(editor);
233
+ });
234
+ registrations.push(registration);
235
+ }
236
+ catch {
237
+ // Non-critical — the guidance gate falls back on the tool catalog
238
+ }
239
+ }
190
240
  // ── prompt hook (V1 `chat.message`) ─────────────────────────────────────
191
241
  // Shims a V1-shaped output (parts array) around the mutable prompt text,
192
242
  // runs the V1 handler, and writes the (possibly replaced) text back.
@@ -218,7 +268,7 @@ export async function registerRagPluginV2(ctx) {
218
268
  const registration = await ctx.session.hook("context", async (event) => {
219
269
  const output = { system: [] };
220
270
  try {
221
- await systemTransformHook({ sessionID: event.sessionID }, output);
271
+ await systemTransformHook({ sessionID: event.sessionID, agent: event.agent, tools: event.tools }, output);
222
272
  }
223
273
  catch {
224
274
  // Non-critical — must never throw
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-rag-plugin",
3
- "version": "2.4.2",
3
+ "version": "2.4.4",
4
4
  "description": "OpenCode plugin for local-first RAG-based semantic code search",
5
5
  "type": "module",
6
6
  "main": "./dist/plugin-entry.js",