opencode-rag-plugin 2.9.1 → 2.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ReadMe.md CHANGED
@@ -265,7 +265,7 @@ opencode-rag mcp
265
265
  | `search_semantic` | Vector + keyword hybrid search across the indexed codebase |
266
266
  | `get_file_skeleton` | AST-based file outline (functions, classes, methods) |
267
267
  | `find_usages` | Find all references to a symbol by name |
268
- | `describe_image` | Describe an image file with the configured vision model (`imageDescription.onDemand` overrides apply) |
268
+ | `describe_image` | Describe an image file with the configured vision model (`imageDescription.onDemand` overrides apply; paths outside the workspace are allowed) |
269
269
  | `make_decision` | Classify/route/score short text with the local tev1 decision model (only when `decision.enabled` is `true`) |
270
270
 
271
271
  Clients can configure the MCP server manually, or `opencode-rag init` auto-registers it.
@@ -7,6 +7,7 @@
7
7
  import path from "node:path";
8
8
  import { existsSync, readFileSync } from "node:fs";
9
9
  import { c, resolveCliContext, cleanupContext, logCliError, logCliInfo } from "../format.js";
10
+ import { resolveUserPath } from "../../core/paths.js";
10
11
  /**
11
12
  * Register the `describe-image` command on the given Commander program.
12
13
  *
@@ -30,7 +31,8 @@ export function registerDescribeImageCommand(program) {
30
31
  const ctx = await resolveCliContext(options, logFilePath);
31
32
  const { config } = ctx;
32
33
  logFilePath = ctx.logFilePath;
33
- const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
34
+ // Any readable image path is allowed — absolute, relative to cwd, or `~`-prefixed.
35
+ const resolvedPath = resolveUserPath(cwd, filePath);
34
36
  if (!existsSync(resolvedPath)) {
35
37
  logCliError(logFilePath, "describe-image", `\nFile not found: ${filePath}`, undefined);
36
38
  process.exit(1);
@@ -32,6 +32,17 @@ export interface AutoIndexConfig {
32
32
  /** Change-detection backend: "chokidar" (FS events, default) or "git" (poll-based). */
33
33
  watcher?: WatcherBackend;
34
34
  }
35
+ /** Handling of long-running shell commands in OpenCode sessions. */
36
+ export interface OpenCodeShellConfig {
37
+ /** Inject guidance telling the agent to background long commands (default true). */
38
+ backgroundGuidance?: boolean;
39
+ /** Threshold (ms) above which a command is "long" (default 30000). */
40
+ longRunningThresholdMs?: number;
41
+ /** Default foreground timeout (ms) to recommend for shell calls (default 120000). */
42
+ foregroundTimeoutMs?: number;
43
+ /** Record a quirk when a foreground command exceeds the threshold (default true). */
44
+ captureLongRunningQuirk?: boolean;
45
+ }
35
46
  /** Behavior when a read tool query returns no results. */
36
47
  export type ReadNoResultsBehavior = "hint" | "empty" | "error";
37
48
  /** Supported file-change watcher backends. */
@@ -604,6 +615,8 @@ export interface RagConfig {
604
615
  injectSystemPrompt?: boolean;
605
616
  /** Whether to grant the read-only RAG tools to the built-in `explore` agent (default true). */
606
617
  exploreAgentTools?: boolean;
618
+ /** Handling of long-running shell commands (backgrounding guidance + measurement). */
619
+ shell?: OpenCodeShellConfig;
607
620
  };
608
621
  /** Custom chunker module registrations. */
609
622
  chunkers?: ChunkerConfig[];
@@ -166,6 +166,12 @@ export const DEFAULT_CONFIG = {
166
166
  readOverride: true,
167
167
  injectSystemPrompt: true,
168
168
  exploreAgentTools: true,
169
+ shell: {
170
+ backgroundGuidance: true,
171
+ longRunningThresholdMs: 30000,
172
+ foregroundTimeoutMs: 120000,
173
+ captureLongRunningQuirk: true,
174
+ },
169
175
  autoIndex: {
170
176
  enabled: false,
171
177
  debounceMs: 2000,
@@ -510,6 +516,15 @@ export function validateConfig(config) {
510
516
  if (config.openCode.autoIndex?.watcher && !["chokidar", "git"].includes(config.openCode.autoIndex.watcher)) {
511
517
  warnings.push(`openCode.autoIndex.watcher "${config.openCode.autoIndex.watcher}" — expected "chokidar" or "git"`);
512
518
  }
519
+ const shellCfg = config.openCode.shell;
520
+ if (shellCfg) {
521
+ if (shellCfg.longRunningThresholdMs != null && shellCfg.longRunningThresholdMs < 0) {
522
+ warnings.push("openCode.shell.longRunningThresholdMs must be >= 0");
523
+ }
524
+ if (shellCfg.foregroundTimeoutMs != null && shellCfg.foregroundTimeoutMs <= 0) {
525
+ warnings.push("openCode.shell.foregroundTimeoutMs must be > 0");
526
+ }
527
+ }
513
528
  if (config.retrieval.contextOptimization) {
514
529
  const co = config.retrieval.contextOptimization;
515
530
  if (co.maxPerFile < 0)
@@ -674,6 +689,10 @@ export function loadConfig(filePath, validate = true) {
674
689
  ...base.autoIndex,
675
690
  ...(safeObj(user.autoIndex) ?? {}),
676
691
  },
692
+ shell: {
693
+ ...base.shell,
694
+ ...(safeObj(user.shell) ?? {}),
695
+ },
677
696
  };
678
697
  return merged;
679
698
  })(),
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @fileoverview Resolution helpers for user-supplied filesystem paths.
3
+ */
4
+ /**
5
+ * Expand a leading `~` to the current user's home directory.
6
+ *
7
+ * Only bare `~` and the `~/` / `~\` prefixes are expanded; `~otheruser` is
8
+ * returned unchanged (it has no portable meaning).
9
+ *
10
+ * @param inputPath - The path supplied by the user.
11
+ * @returns The path with `~` replaced by the home directory.
12
+ */
13
+ export declare function expandTilde(inputPath: string): string;
14
+ /**
15
+ * Resolve a user-supplied path against a base directory WITHOUT sandboxing it.
16
+ *
17
+ * Absolute paths (and `~`-prefixed paths) are used as-is; relative paths are
18
+ * resolved against `baseDir`. Use this for read-only tools that legitimately
19
+ * operate on files anywhere on disk (e.g. `describe_image` on a screenshot
20
+ * outside the workspace). Do NOT use it for the workspace-sandboxed `read`
21
+ * tool — that one must keep rejecting paths outside the workspace.
22
+ *
23
+ * @param baseDir - Directory used to resolve relative paths (usually the worktree).
24
+ * @param inputPath - The path supplied by the user.
25
+ * @returns An absolute path; no containment check is performed.
26
+ */
27
+ export declare function resolveUserPath(baseDir: string, inputPath: string): string;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @fileoverview Resolution helpers for user-supplied filesystem paths.
3
+ */
4
+ import path from "node:path";
5
+ import { homedir } from "node:os";
6
+ /**
7
+ * Expand a leading `~` to the current user's home directory.
8
+ *
9
+ * Only bare `~` and the `~/` / `~\` prefixes are expanded; `~otheruser` is
10
+ * returned unchanged (it has no portable meaning).
11
+ *
12
+ * @param inputPath - The path supplied by the user.
13
+ * @returns The path with `~` replaced by the home directory.
14
+ */
15
+ export function expandTilde(inputPath) {
16
+ if (inputPath === "~")
17
+ return homedir();
18
+ if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) {
19
+ return path.join(homedir(), inputPath.slice(2));
20
+ }
21
+ return inputPath;
22
+ }
23
+ /**
24
+ * Resolve a user-supplied path against a base directory WITHOUT sandboxing it.
25
+ *
26
+ * Absolute paths (and `~`-prefixed paths) are used as-is; relative paths are
27
+ * resolved against `baseDir`. Use this for read-only tools that legitimately
28
+ * operate on files anywhere on disk (e.g. `describe_image` on a screenshot
29
+ * outside the workspace). Do NOT use it for the workspace-sandboxed `read`
30
+ * tool — that one must keep rejecting paths outside the workspace.
31
+ *
32
+ * @param baseDir - Directory used to resolve relative paths (usually the worktree).
33
+ * @param inputPath - The path supplied by the user.
34
+ * @returns An absolute path; no containment check is performed.
35
+ */
36
+ export function resolveUserPath(baseDir, inputPath) {
37
+ const expanded = expandTilde(inputPath);
38
+ return path.isAbsolute(expanded)
39
+ ? path.resolve(expanded)
40
+ : path.resolve(baseDir, expanded);
41
+ }
42
+ //# sourceMappingURL=paths.js.map
@@ -98,7 +98,7 @@ export interface DescribeImageResult {
98
98
  /** Human-readable formatted output with metadata. */
99
99
  formatted: string;
100
100
  }
101
- /** Describe an image file using the configured vision provider (Ollama, OpenAI, Anthropic, Gemini, or OpenCode Zen). Honors `imageDescription.onDemand` overrides. */
101
+ /** Describe an image file using the configured vision provider (Ollama, OpenAI, Anthropic, Gemini, or OpenCode Zen). Honors `imageDescription.onDemand` overrides. The file may live anywhere on disk; relative paths resolve against `worktree`. */
102
102
  export declare function handleDescribeImage(params: DescribeImageParams, cfg: RagConfig, worktree: string, visionProvider?: ImageVisionProvider): Promise<DescribeImageResult>;
103
103
  /** Parameters for the make_decision MCP tool. */
104
104
  export interface MakeDecisionParams {
@@ -13,6 +13,7 @@ import { validateDecisionRequest } from "../decision/validate.js";
13
13
  import { formatDecisionAnswers } from "../decision/format.js";
14
14
  import { readFileSync } from "node:fs";
15
15
  import { resolve, isAbsolute, relative, sep as pathSep } from "node:path";
16
+ import { resolveUserPath } from "../core/paths.js";
16
17
  /**
17
18
  * Resolve a user-supplied file path against the worktree root, refusing to
18
19
  * escape the worktree. Absolute paths are accepted only if they already reside
@@ -136,11 +137,13 @@ export async function handleFileSkeleton(params, worktree, languageByExtension)
136
137
  const formatted = `${skeleton.length} structural elements (${summary || "—"})\n\n${formatSkeleton(skeleton)}`;
137
138
  return { elements: skeleton, formatted, summary };
138
139
  }
139
- /** Describe an image file using the configured vision provider (Ollama, OpenAI, Anthropic, Gemini, or OpenCode Zen). Honors `imageDescription.onDemand` overrides. */
140
+ /** Describe an image file using the configured vision provider (Ollama, OpenAI, Anthropic, Gemini, or OpenCode Zen). Honors `imageDescription.onDemand` overrides. The file may live anywhere on disk; relative paths resolve against `worktree`. */
140
141
  export async function handleDescribeImage(params, cfg, worktree, visionProvider) {
141
142
  const { existsSync, readFileSync } = await import("node:fs");
142
143
  const path = await import("node:path");
143
- const resolvedPath = resolveFilePath(params.filePath, worktree);
144
+ // Unlike the skeleton tools, image description is not sandboxed to the
145
+ // worktree: screenshots often live in the OS temp or home directory.
146
+ const resolvedPath = resolveUserPath(worktree, params.filePath);
144
147
  if (!existsSync(resolvedPath)) {
145
148
  throw new Error(`File not found: ${params.filePath}`);
146
149
  }
@@ -3,6 +3,7 @@
3
3
  * that is injected into both the runtime system prompt (via plugin.ts) and the AGENTS.md
4
4
  * directive (via init-helpers.ts).
5
5
  */
6
+ import type { OpenCodeShellConfig } from "../core/config.js";
6
7
  /** Sentinel marker that opens the managed section. */
7
8
  export declare const BEGIN_MARKER = "<!-- BEGIN opencode-rag -->";
8
9
  /** Sentinel marker that closes the managed section. */
@@ -29,10 +30,12 @@ export declare const DECISION_ROUTING_GUIDANCE_LINE = "- Before asking the user
29
30
  * Build the flat guidance lines array for the runtime system-prompt injector.
30
31
  * Returns a new array each call.
31
32
  */
33
+ export declare function buildShellBackgroundGuidanceLines(shell?: OpenCodeShellConfig): string[];
32
34
  export declare function buildSystemGuidanceLines(opts: {
33
35
  promptEnforcement: boolean;
34
36
  decisionEnabled?: boolean;
35
37
  routeBeforeAsking?: boolean;
38
+ shell?: OpenCodeShellConfig;
36
39
  }): string[];
37
40
  /**
38
41
  * Build the markdown-formatted AGENTS.md directive section, wrapped in sentinel
@@ -42,4 +45,5 @@ export declare function buildAgentsMdDirective(opts: {
42
45
  promptEnforcement: boolean;
43
46
  decisionEnabled?: boolean;
44
47
  routeBeforeAsking?: boolean;
48
+ shell?: OpenCodeShellConfig;
45
49
  }): string;
@@ -81,6 +81,20 @@ export const DECISION_ROUTING_GUIDANCE_LINE = "- Before asking the user to choos
81
81
  * Build the flat guidance lines array for the runtime system-prompt injector.
82
82
  * Returns a new array each call.
83
83
  */
84
+ export function buildShellBackgroundGuidanceLines(shell) {
85
+ if (shell?.backgroundGuidance === false)
86
+ return [];
87
+ const thresholdMs = shell?.longRunningThresholdMs ?? 30000;
88
+ const timeoutMs = shell?.foregroundTimeoutMs ?? 120000;
89
+ const thresholdSec = Math.max(1, Math.round(thresholdMs / 1000));
90
+ return [
91
+ "",
92
+ "Long-running commands:",
93
+ `- Any \`shell\` call expected to take more than ${thresholdSec}s MUST set \`background: true\` (returns immediately; the session is notified on completion) or set an explicit \`timeout\` (ms).`,
94
+ `- Default foreground timeout: ${timeoutMs}ms. Never run builds/tests/indexes in the foreground beyond ${thresholdSec}s; if a call is already running, press Ctrl+B to background it (OpenCode: \`session.background\`).`,
95
+ "- OpenCodeRAG measures foreground shell duration and records a quirk when a call exceeds the threshold, so repeated foreground runs become visible.",
96
+ ];
97
+ }
84
98
  export function buildSystemGuidanceLines(opts) {
85
99
  const lines = [...MANDATORY_GUIDANCE_LINES];
86
100
  if (opts.decisionEnabled) {
@@ -100,6 +114,7 @@ export function buildSystemGuidanceLines(opts) {
100
114
  if (opts.promptEnforcement) {
101
115
  lines.push(...QUIRK_ENFORCEMENT_LINES);
102
116
  }
117
+ lines.push(...buildShellBackgroundGuidanceLines(opts.shell));
103
118
  return lines;
104
119
  }
105
120
  /**
@@ -182,6 +197,10 @@ export function buildAgentsMdDirective(opts) {
182
197
  if (opts.promptEnforcement) {
183
198
  lines.push("", "### MANDATORY quirk capture rules — you MUST call `add_quirk` when", "- A build, test, or type-check command fails and you resolve it", "- You discover an undocumented library constraint, peer dep, or workaround", "- You learn an environment-specific requirement (OS, tool version, etc.)", "- You make a design decision that future sessions should remember", "- You resolve a gotcha that cost more than one attempt", "", "### MANDATORY quirk hygiene — you MUST call `update_quirk` or `delete_quirk` when", "- A stored quirk is outdated, wrong, or has been fixed — update it or delete it instead of adding a contradicting duplicate", "- NEVER finish a coding session without adding quirks for resolved errors.");
184
199
  }
200
+ const shellLines = buildShellBackgroundGuidanceLines(opts.shell);
201
+ if (shellLines.length > 0) {
202
+ lines.push("", "### Long-running commands", ...shellLines.filter((l) => l.trim().length > 0));
203
+ }
185
204
  lines.push(END_MARKER);
186
205
  return lines.join("\n");
187
206
  }
@@ -20,6 +20,7 @@ import { retrieve } from "../retriever/retriever.js";
20
20
  import { extractSkeleton, getExtension } from "../chunker/skeleton.js";
21
21
  import { readFileSync } from "node:fs";
22
22
  import { resolveWorkspacePath } from "./tool-args.js";
23
+ import { resolveUserPath } from "../core/paths.js";
23
24
  import { addQuirk, updateQuirk, removeQuirk, recallQuirks } from "../quirks/quirk-store.js";
24
25
  import { createDecisionProvider } from "../decision/factory.js";
25
26
  import { validateDecisionRequest } from "../decision/validate.js";
@@ -148,7 +149,9 @@ export function createDescribeImageTool(options) {
148
149
  "and returns a natural language description of what the image shows. " +
149
150
  "Optionally accepts a `systemPrompt` to steer the description toward specific features or details you care about " +
150
151
  "(e.g. colors, layout, accessibility, text content, specific UI elements). " +
151
- "Use when the user refers to a screenshot, diagram, mockup, or any image in the workspace.",
152
+ "The path may point anywhere on disk — outside the workspace too (e.g. a screenshot in the OS temp " +
153
+ "or home directory); relative paths resolve against the workspace root and `~` expands to the home directory. " +
154
+ "Use when the user refers to a screenshot, diagram, mockup, or any image.",
152
155
  args: {
153
156
  filePath: tool.schema.string().min(1, "An image file path is required."),
154
157
  systemPrompt: tool.schema.string().optional(),
@@ -157,7 +160,7 @@ export function createDescribeImageTool(options) {
157
160
  try {
158
161
  const { existsSync, readFileSync } = await import("node:fs");
159
162
  const path = await import("node:path");
160
- const resolvedPath = resolveWorkspacePath(worktree, args.filePath);
163
+ const resolvedPath = resolveUserPath(worktree, args.filePath);
161
164
  if (!existsSync(resolvedPath)) {
162
165
  return {
163
166
  title: "Describe image",
package/dist/plugin.js CHANGED
@@ -44,6 +44,7 @@ const MAX_SESSION_MAP_SIZE = 50;
44
44
  const MAX_SESSION_TOOL_RESULTS = 20;
45
45
  /** Pending tool-error quirk blocks older than this (ms) are dropped instead of injected. */
46
46
  const TOOL_ERROR_PENDING_TTL_MS = 120_000;
47
+ const SHELL_NUDGE_TTL_MS = 60_000;
47
48
  /** How long the tool-error quirk list is cached before it is re-read (ms). */
48
49
  const TOOL_GOTCHA_CACHE_MS = 30_000;
49
50
  /** Cache of loaded RAG configurations keyed by workspace directory. */
@@ -660,6 +661,10 @@ export function createRagHooks(options) {
660
661
  // Auto-capture maps: previous user request per session, tool results, and full transcript
661
662
  const sessionPrevUserReq = new Map();
662
663
  const sessionToolResults = new Map();
664
+ // Foreground shell-call timing for the long-running-command feature.
665
+ const sessionShellStart = new Map();
666
+ const sessionPendingShellNudge = new Map();
667
+ const sessionShellLongCount = new Map();
663
668
  const sessionTranscript = new Map();
664
669
  // Track quirk IDs already injected per session to avoid duplicate injection
665
670
  const sessionInjectedQuirks = new Map();
@@ -1261,10 +1266,73 @@ export function createRagHooks(options) {
1261
1266
  }
1262
1267
  },
1263
1268
  tool: tools,
1269
+ async "tool.execute.before"(input, output) {
1270
+ try {
1271
+ const toolName = String(input.tool ?? "").toLowerCase();
1272
+ if (toolName !== "shell" && toolName !== "bash")
1273
+ return;
1274
+ const args = (output?.args ?? {});
1275
+ const command = typeof args.command === "string" ? args.command : (typeof args.cmd === "string" ? args.cmd : "");
1276
+ sessionShellStart.set(String(input.callID), {
1277
+ sessionID: input.sessionID,
1278
+ start: Date.now(),
1279
+ command: command.slice(0, 200),
1280
+ });
1281
+ }
1282
+ catch {
1283
+ // Non-critical — must never throw
1284
+ }
1285
+ },
1264
1286
  async "tool.execute.after"(input, output) {
1265
1287
  try {
1266
1288
  const results = sessionToolResults.get(input.sessionID) ?? [];
1267
1289
  results.push({ tool: input.tool, output: output.output ?? "" });
1290
+ // Long-running shell command handling: measure foreground duration and,
1291
+ // when it exceeds the configured threshold, nudge the agent next turn
1292
+ // (and optionally record a quirk) so repeated foreground runs become
1293
+ // visible. True auto-backgrounding is an OpenCode-core feature; this is
1294
+ // the in-plugin approximation.
1295
+ try {
1296
+ const toolName = String(input.tool ?? "").toLowerCase();
1297
+ if (toolName === "shell" || toolName === "bash") {
1298
+ const startInfo = sessionShellStart.get(String(input.callID));
1299
+ sessionShellStart.delete(String(input.callID));
1300
+ const cfg = getEffectiveCfg();
1301
+ const shellCfg = cfg.openCode.shell;
1302
+ const thresholdMs = shellCfg?.longRunningThresholdMs ?? 30000;
1303
+ const durationMs = startInfo ? Date.now() - startInfo.start : undefined;
1304
+ if (durationMs != null && thresholdMs > 0 && durationMs >= thresholdMs) {
1305
+ const durSec = (durationMs / 1000).toFixed(1);
1306
+ const cmd = startInfo?.command || "(unknown command)";
1307
+ const nudgeText = `⚠ The previous foreground shell command took ${durSec}s ` +
1308
+ `(\`${cmd}\`). Prefer \`background: true\` or an explicit \`timeout\` for commands expected to exceed ` +
1309
+ `${Math.round(thresholdMs / 1000)}s; press Ctrl+B to background an already-running call.`;
1310
+ sessionPendingShellNudge.set(input.sessionID, { text: nudgeText, ts: Date.now() });
1311
+ if (shellCfg?.captureLongRunningQuirk !== false) {
1312
+ // Bound per-session recording to avoid runaway quirk spam.
1313
+ const counterKey = `shell-long:${input.sessionID}`;
1314
+ const current = (sessionShellLongCount.get(counterKey) ?? 0);
1315
+ if (current < 3) {
1316
+ sessionShellLongCount.set(counterKey, current + 1);
1317
+ const quirkDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
1318
+ void addQuirk(quirkDeps, {
1319
+ content: `A foreground shell command took ${durSec}s: \`${cmd}\`. Prefer \`background: true\` or an explicit \`timeout\` for long commands; press Ctrl+B to background a running call.`,
1320
+ quirkType: "gotcha",
1321
+ tags: ["tool:shell", "cause:long-foreground"],
1322
+ sourceRef: "opencode-rag:shell-auto-background",
1323
+ }).catch(() => { });
1324
+ }
1325
+ }
1326
+ appendDebugLog(options.logFilePath, {
1327
+ scope: "shell.long-running",
1328
+ message: `foreground shell took ${durSec}s (threshold ${thresholdMs}ms): ${cmd}`,
1329
+ });
1330
+ }
1331
+ }
1332
+ }
1333
+ catch {
1334
+ // Non-critical — must never throw
1335
+ }
1268
1336
  // Failed tool calls: feed the auto-capture pipeline (learning loop) and
1269
1337
  // recall matching quirks for injection into the next model request.
1270
1338
  // `output.error` is set by the V2 adapter's error branch; the status
@@ -1354,7 +1422,7 @@ export function createRagHooks(options) {
1354
1422
  // Non-critical — must never throw
1355
1423
  }
1356
1424
  if (injectGuidance) {
1357
- const guidance = buildSystemGuidanceLines({ promptEnforcement: !!cfg.memory?.promptEnforcement, decisionEnabled: !!cfg.decision?.enabled, routeBeforeAsking: !!cfg.decision?.routeBeforeAsking });
1425
+ const guidance = buildSystemGuidanceLines({ promptEnforcement: !!cfg.memory?.promptEnforcement, decisionEnabled: !!cfg.decision?.enabled, routeBeforeAsking: !!cfg.decision?.routeBeforeAsking, shell: cfg.openCode.shell });
1358
1426
  output.system.unshift(guidance.join("\n"));
1359
1427
  }
1360
1428
  // Inject a one-time update prompt so the agent asks the user to install.
@@ -1439,6 +1507,13 @@ export function createRagHooks(options) {
1439
1507
  }
1440
1508
  sessionPendingToolErrorQuirk.delete(sessionId);
1441
1509
  }
1510
+ const shellNudge = sessionPendingShellNudge.get(sessionId);
1511
+ if (shellNudge) {
1512
+ if (Date.now() - shellNudge.ts < SHELL_NUDGE_TTL_MS) {
1513
+ output.system.unshift(shellNudge.text);
1514
+ }
1515
+ sessionPendingShellNudge.delete(sessionId);
1516
+ }
1442
1517
  }
1443
1518
  }
1444
1519
  catch {
@@ -38,7 +38,7 @@ type V2ToolEditor = {
38
38
  };
39
39
  type V2ToolDomain = {
40
40
  transform(callback: (editor: V2ToolEditor) => void): Promise<V2Registration>;
41
- hook(name: "execute.after", callback: (event: V2ToolExecuteAfterEvent) => Promise<void> | void): Promise<V2Registration>;
41
+ hook(name: "execute.before" | "execute.after", callback: (event: V2ToolExecuteBeforeEvent | V2ToolExecuteAfterEvent) => Promise<void> | void): Promise<V2Registration>;
42
42
  };
43
43
  type V2SessionDomain = {
44
44
  hook(name: "prompt", callback: (event: V2PromptHookEvent) => Promise<void> | void): Promise<V2Registration>;
@@ -104,6 +104,13 @@ type V2Tool = {
104
104
  metadata?: Record<string, unknown>;
105
105
  }>;
106
106
  };
107
+ /** V2 `execute.before` hook event — fires before a tool runs. */
108
+ type V2ToolExecuteBeforeEvent = {
109
+ tool: string;
110
+ sessionID: string;
111
+ id: unknown;
112
+ input?: unknown;
113
+ };
107
114
  /** V2 `execute.after` hook event — fires for BOTH the completed and the error branch. */
108
115
  type V2ToolExecuteAfterEvent = {
109
116
  tool: string;
@@ -316,6 +316,26 @@ export async function registerRagPluginV2(ctx) {
316
316
  });
317
317
  registrations.push(registration);
318
318
  }
319
+ // ── tool.execute.before ──────────────────────────────────────────────────
320
+ // Forwards the V1 `tool.execute.before` hook so the plugin can observe tool
321
+ // inputs (and, e.g., time a call) before it runs. Previously dropped.
322
+ const toolBeforeHook = hooks["tool.execute.before"];
323
+ if (toolBeforeHook) {
324
+ const registration = await ctx.tool.hook("execute.before", async (event) => {
325
+ try {
326
+ const ev = event;
327
+ await toolBeforeHook({
328
+ sessionID: ev.sessionID,
329
+ tool: ev.tool,
330
+ callID: ev.id,
331
+ }, { args: (ev.input ?? {}) });
332
+ }
333
+ catch {
334
+ // Non-critical — must never throw
335
+ }
336
+ });
337
+ registrations.push(registration);
338
+ }
319
339
  // ── tool.execute.after ───────────────────────────────────────────────────
320
340
  // Forwards BOTH branches: completed calls keep the existing contract, error
321
341
  // calls additionally carry `input.status = "error"` and `output.error`, so
@@ -325,8 +345,9 @@ export async function registerRagPluginV2(ctx) {
325
345
  if (toolAfterHook) {
326
346
  const registration = await ctx.tool.hook("execute.after", async (event) => {
327
347
  try {
328
- const isError = event.status === "error";
329
- const result = event.result;
348
+ const ev = event;
349
+ const isError = ev.status === "error";
350
+ const result = ev.result;
330
351
  // The COMPLETED branch carries its text as an ARRAY of content parts
331
352
  // (measured live 2026-10-21: the shell tool returns one text part
332
353
  // per line plus a separate `Exited with code N` part). Reading only
@@ -334,14 +355,14 @@ export async function registerRagPluginV2(ctx) {
334
355
  // — a JSON blob that does NOT contain the failure marker, so nothing
335
356
  // downstream could see it. Join the text parts instead.
336
357
  const outputText = isError
337
- ? extractToolErrorText(event)
358
+ ? extractToolErrorText(ev)
338
359
  : extractContentText(result?.content) ??
339
360
  extractStructuredOutput(result?.output) ??
340
361
  (result?.output !== undefined ? JSON.stringify(result.output) : "");
341
362
  await toolAfterHook({
342
- sessionID: event.sessionID,
343
- tool: event.tool,
344
- callID: event.id,
363
+ sessionID: ev.sessionID,
364
+ tool: ev.tool,
365
+ callID: ev.id,
345
366
  status: isError ? "error" : "completed",
346
367
  }, {
347
368
  output: outputText,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-rag-plugin",
3
- "version": "2.9.1",
3
+ "version": "2.9.3",
4
4
  "description": "OpenCode plugin for local-first RAG-based semantic code search",
5
5
  "type": "module",
6
6
  "main": "./dist/plugin-entry.js",