opencode-rag-plugin 2.12.0 → 2.12.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.
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @fileoverview Global OpenCode plugin installation.
3
+ *
4
+ * OpenCode 2 loads plugins from `~/.config/opencode/plugins/` as well as from
5
+ * a workspace's `.opencode/plugins/`. Installing the RAG plugin once in the
6
+ * global directory removes the per-repository plugin entries, the
7
+ * `.opencode/node_modules` junction and the workspace `package.json`:
8
+ *
9
+ * ```
10
+ * ~/.config/opencode/plugins/opencode-rag/index.js (server role)
11
+ * ~/.config/opencode/plugins/opencode-rag/tui.js (TUI role)
12
+ * ```
13
+ *
14
+ * Both files re-export the plugin from the global runtime
15
+ * (`~/.opencode/node_modules/opencode-rag-plugin/dist/…`) via a relative
16
+ * path, so the install keeps working when the home directory moves. The
17
+ * vector store is NOT affected: `vectorStore.path` is resolved against the
18
+ * workspace, so every repository keeps its own local LanceDB.
19
+ */
20
+ import path from "node:path";
21
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
22
+ import { globalConfigPath } from "./config.js";
23
+ import { getRuntimeDir } from "./setup-runtime.js";
24
+ /** npm package name of the plugin. */
25
+ const PLUGIN_NAME = "opencode-rag-plugin";
26
+ /** Directory name used inside OpenCode's plugin directory. */
27
+ const GLOBAL_PLUGIN_ID = "opencode-rag";
28
+ /** OpenCode's global plugin directory (`<config>/plugins`). */
29
+ export function getGlobalPluginsRoot() {
30
+ return path.join(path.dirname(globalConfigPath()), "plugins");
31
+ }
32
+ /** Our directory inside OpenCode's global plugin directory. */
33
+ export function getGlobalPluginDir() {
34
+ return path.join(getGlobalPluginsRoot(), GLOBAL_PLUGIN_ID);
35
+ }
36
+ /** Dist directory of the plugin inside the runtime cache. */
37
+ export function getRuntimePluginDist() {
38
+ return path.join(getRuntimeDir(), "node_modules", PLUGIN_NAME, "dist");
39
+ }
40
+ /** Render an import specifier relative to the global plugin directory. */
41
+ function relativeImport(fromDir, target) {
42
+ const relative = path.relative(fromDir, target).split(path.sep).join("/");
43
+ return relative.startsWith(".") ? relative : `./${relative}`;
44
+ }
45
+ /** Entry file content for one role. */
46
+ function entryContent(fromDir, distFile) {
47
+ return [
48
+ `import plugin from "${relativeImport(fromDir, path.join(getRuntimePluginDist(), distFile))}";`,
49
+ `export default plugin;`,
50
+ "",
51
+ ].join("\n");
52
+ }
53
+ /** Write a file only when its content changed (or `force`). */
54
+ function writeIfChanged(filePath, content, force) {
55
+ if (!force && existsSync(filePath)) {
56
+ try {
57
+ if (readFileSync(filePath, "utf-8") === content)
58
+ return false;
59
+ }
60
+ catch {
61
+ // Fall through to the write.
62
+ }
63
+ }
64
+ writeFileSync(filePath, content, "utf-8");
65
+ return true;
66
+ }
67
+ /**
68
+ * Install (or refresh) the global plugin entrypoints.
69
+ *
70
+ * @throws When the runtime plugin dist is missing (run the runtime step first).
71
+ */
72
+ export function installGlobalPlugin(options = {}) {
73
+ const dist = getRuntimePluginDist();
74
+ const serverEntry = path.join(dist, "plugin-entry.js");
75
+ const tuiEntry = path.join(dist, "tui.js");
76
+ if (!existsSync(serverEntry) || !existsSync(tuiEntry)) {
77
+ throw new Error(`Plugin runtime not found at ${dist}. Run 'opencode-rag setup' first.`);
78
+ }
79
+ const dir = getGlobalPluginDir();
80
+ mkdirSync(dir, { recursive: true });
81
+ const written = [];
82
+ const files = [
83
+ ["index.js", entryContent(dir, "plugin-entry.js")],
84
+ ["tui.js", entryContent(dir, "tui.js")],
85
+ ];
86
+ for (const [name, content] of files) {
87
+ const target = path.join(dir, name);
88
+ if (writeIfChanged(target, content, options.force ?? false))
89
+ written.push(target);
90
+ }
91
+ return { dir, written };
92
+ }
93
+ /** Whether both global entrypoints exist. */
94
+ export function isGlobalPluginInstalled() {
95
+ const dir = getGlobalPluginDir();
96
+ return existsSync(path.join(dir, "index.js")) && existsSync(path.join(dir, "tui.js"));
97
+ }
98
+ /** Remove the global plugin entrypoints. Returns `true` when something was removed. */
99
+ export function removeGlobalPlugin() {
100
+ const dir = getGlobalPluginDir();
101
+ if (!existsSync(dir))
102
+ return false;
103
+ rmSync(dir, { recursive: true, force: true });
104
+ return true;
105
+ }
106
+ /** Workspace-local plugin directory (legacy/per-repo mode). */
107
+ export function getWorkspacePluginDir(workspaceDir) {
108
+ return path.join(workspaceDir, ".opencode", "plugins", GLOBAL_PLUGIN_ID);
109
+ }
110
+ /** Whether a workspace still uses the per-repository plugin entries. */
111
+ export function isWorkspacePluginInstalled(workspaceDir) {
112
+ return existsSync(path.join(getWorkspacePluginDir(workspaceDir), "index.js"));
113
+ }
114
+ //# sourceMappingURL=global-plugin.js.map
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
2
  import os from "node:os";
3
+ import { createRequire } from "node:module";
3
4
  import { existsSync, mkdirSync, rmSync, writeFileSync, readFileSync, symlinkSync, lstatSync, } from "node:fs";
4
5
  import { execSync } from "node:child_process";
5
6
  import { bestAvailablePackageManager, globalInstallCommand, installHint, resolveGlobalInstall, } from "./package-manager.js";
@@ -156,31 +157,44 @@ export async function setupRuntime(options) {
156
157
  const { cpSync } = await import("node:fs");
157
158
  cpSync(globalPluginDir, runtimePluginDir, { recursive: true });
158
159
  }
159
- // Ensure the @opencode-ai/plugin SDK is available globally.
160
- // We must NOT run a package install inside the runtime dir because the
161
- // package manager re-resolves all of node_modules/ and replaces the plugin
162
- // junction with the published npm version (corrupting the local link).
163
- if (!existsSync(globalSdkPluginDir)) {
164
- const sdkPm = install.pm ?? bestAvailablePackageManager();
165
- if (!sdkPm) {
166
- errors.push("No package manager (npm/pnpm/yarn/bun) found on PATH — cannot install the @opencode-ai/plugin SDK globally.");
167
- return { success: false, errors };
168
- }
169
- const sdkInstallCommand = globalInstallCommand(sdkPm, "@opencode-ai/plugin");
170
- try {
171
- execSync(sdkInstallCommand, {
172
- stdio: "pipe",
173
- timeout: 60_000,
174
- windowsHide: true,
175
- });
176
- }
177
- catch (cause) {
178
- errors.push(`Failed to install @opencode-ai/plugin SDK globally (${sdkInstallCommand}): ${cause.message}`);
179
- return { success: false, errors };
160
+ // Ensure the @opencode-ai/plugin SDK is resolvable from the plugin itself.
161
+ // It is a peer dependency: npm installs it automatically next to the global
162
+ // package, so the common path needs no extra install. Only fall back to a
163
+ // global install + junction when resolution actually fails (pnpm/yarn/bun).
164
+ let sdkResolvable = false;
165
+ try {
166
+ const requireFromPlugin = createRequire(path.join(globalPluginDir, "package.json"));
167
+ requireFromPlugin.resolve("@opencode-ai/plugin/tool");
168
+ sdkResolvable = true;
169
+ }
170
+ catch {
171
+ // Fall through to the global install.
172
+ }
173
+ if (!sdkResolvable) {
174
+ if (!existsSync(globalSdkPluginDir)) {
175
+ const sdkPm = install.pm ?? bestAvailablePackageManager();
176
+ if (!sdkPm) {
177
+ errors.push("No package manager (npm/pnpm/yarn/bun) found on PATH — cannot install the @opencode-ai/plugin SDK globally.");
178
+ return { success: false, errors };
179
+ }
180
+ const sdkInstallCommand = globalInstallCommand(sdkPm, "@opencode-ai/plugin");
181
+ try {
182
+ execSync(sdkInstallCommand, {
183
+ stdio: "pipe",
184
+ timeout: 60_000,
185
+ windowsHide: true,
186
+ });
187
+ }
188
+ catch (cause) {
189
+ errors.push(`Failed to install @opencode-ai/plugin SDK globally (${sdkInstallCommand}): ${cause.message}`);
190
+ return { success: false, errors };
191
+ }
180
192
  }
181
193
  }
182
- // Create junction from global SDK to runtime (same pattern as plugin above)
183
- if (existsSync(globalSdkPluginDir)) {
194
+ // Create junction from global SDK to runtime (same pattern as plugin above).
195
+ // Skipped when the peer already resolves from the plugin's own install.
196
+ const needsSdkJunction = !sdkResolvable;
197
+ if (needsSdkJunction && existsSync(globalSdkPluginDir)) {
184
198
  removeIfExists(runtimeSdkPluginDir);
185
199
  retries = 3;
186
200
  while (retries > 0 && existsSync(runtimeSdkPluginDir)) {
@@ -211,7 +225,7 @@ export async function setupRuntime(options) {
211
225
  cpSync(globalSdkPluginDir, runtimeSdkPluginDir, { recursive: true });
212
226
  }
213
227
  }
214
- else {
228
+ else if (needsSdkJunction) {
215
229
  errors.push(`@opencode-ai/plugin SDK not available after global install`);
216
230
  return { success: false, errors };
217
231
  }
@@ -220,13 +234,13 @@ export async function setupRuntime(options) {
220
234
  const cliEntry = path.join(runtimePluginDir, "dist", "cli.js");
221
235
  const pluginEntry = path.join(runtimePluginDir, "dist", "plugin-entry.js");
222
236
  const sdkPkg = path.join(runtimeSdkPluginDir, "package.json");
223
- const success = existsSync(cliEntry) && existsSync(pluginEntry) && existsSync(sdkPkg);
237
+ const success = existsSync(cliEntry) && existsSync(pluginEntry) && (sdkResolvable || existsSync(sdkPkg));
224
238
  if (!success) {
225
239
  if (!existsSync(cliEntry))
226
240
  errors.push(`CLI entry missing: ${cliEntry}`);
227
241
  if (!existsSync(pluginEntry))
228
242
  errors.push(`Plugin entry missing: ${pluginEntry}`);
229
- if (!existsSync(sdkPkg))
243
+ if (!sdkResolvable && !existsSync(sdkPkg))
230
244
  errors.push(`Plugin SDK missing: ${sdkPkg}`);
231
245
  }
232
246
  return { success, errors };
@@ -205,7 +205,14 @@ async function checkOpenAiEmbed(baseUrl, model, apiKey, timeoutMs, proxy) {
205
205
  return { provider: "openai", model, type: "embedding", status: "ok" };
206
206
  }
207
207
  if (response.status === 401 || response.status === 403) {
208
- return { provider: "openai", model, type: "embedding", status: "error", error: `Invalid API key (HTTP ${response.status})` };
208
+ const detail = await summarizeAuthError(response);
209
+ return {
210
+ provider: "openai",
211
+ model,
212
+ type: "embedding",
213
+ status: "error",
214
+ error: `Invalid API key (HTTP ${response.status})${detail ? `: ${detail}` : ""}`,
215
+ };
209
216
  }
210
217
  const body = await response.text();
211
218
  return { provider: "openai", model, type: "embedding", status: "error", error: `HTTP ${response.status}: ${body.slice(0, 200)}` };
@@ -215,6 +222,34 @@ async function checkOpenAiEmbed(baseUrl, model, apiKey, timeoutMs, proxy) {
215
222
  return { provider: "openai", model, type: "embedding", status: "error", error: msg.slice(0, 200) };
216
223
  }
217
224
  }
225
+ /** Summarize a provider auth error body (OpenAI-compatible JSON or plain text). */
226
+ async function summarizeAuthError(response) {
227
+ const body = await response.text().catch(() => "");
228
+ const trimmed = body.trim();
229
+ if (!trimmed)
230
+ return undefined;
231
+ try {
232
+ const parsed = JSON.parse(trimmed);
233
+ const error = parsed.error;
234
+ if (error && typeof error === "object") {
235
+ const entry = error;
236
+ const code = typeof entry.code === "string" ? entry.code : undefined;
237
+ const message = typeof entry.message === "string" ? entry.message : undefined;
238
+ if (code && message)
239
+ return `${code} — ${message}`.replace(/\s+/g, " ").slice(0, 220);
240
+ if (message)
241
+ return message.replace(/\s+/g, " ").slice(0, 220);
242
+ if (code)
243
+ return code;
244
+ }
245
+ if (typeof parsed.message === "string")
246
+ return parsed.message.replace(/\s+/g, " ").slice(0, 220);
247
+ }
248
+ catch {
249
+ // Not JSON — fall through to the plain-text summary.
250
+ }
251
+ return trimmed.replace(/\s+/g, " ").slice(0, 220);
252
+ }
218
253
  /** Check OpenAI-compatible chat endpoint via the /models endpoint. */
219
254
  async function checkOpenAiChat(baseUrl, model, apiKey, timeoutMs, proxy, type = "description") {
220
255
  if (!apiKey) {
@@ -230,7 +265,14 @@ async function checkOpenAiChat(baseUrl, model, apiKey, timeoutMs, proxy, type =
230
265
  return { provider: "openai", model, type, status: "ok" };
231
266
  }
232
267
  if (response.status === 401 || response.status === 403) {
233
- return { provider: "openai", model, type, status: "error", error: `Invalid API key (HTTP ${response.status})` };
268
+ const detail = await summarizeAuthError(response);
269
+ return {
270
+ provider: "openai",
271
+ model,
272
+ type,
273
+ status: "error",
274
+ error: `Invalid API key (HTTP ${response.status})${detail ? `: ${detail}` : ""}`,
275
+ };
234
276
  }
235
277
  const body = await response.text();
236
278
  return { provider: "openai", model, type, status: "error", error: `HTTP ${response.status}: ${body.slice(0, 200)}` };
@@ -34,6 +34,7 @@
34
34
  * - The read-tool override keeps its V1 execute contract (args + sessionID).
35
35
  */
36
36
  import { loadWorkspaceConfig, resolveConfigPaths } from "../core/config.js";
37
+ import { autoScaffoldWorkspace } from "../core/auto-scaffold.js";
37
38
  import { ragPlugin, RAG_TOOL_NAMES } from "../plugin.js";
38
39
  import { createShellGuardForDirectory, formatShellGuardReason, isShellToolName, } from "../safety/shell-guard.js";
39
40
  /**
@@ -266,6 +267,14 @@ export async function installShellGuard(ctx, guard) {
266
267
  * disposes every registration and aborts the event subscription.
267
268
  */
268
269
  export async function registerRagPluginV2(ctx) {
270
+ // Global-plugin mode: make a fresh repository usable without a CLI run.
271
+ // Create-only, never overwrites, respects `setup.autoScaffold`.
272
+ try {
273
+ autoScaffoldWorkspace(ctx.location.directory);
274
+ }
275
+ catch {
276
+ // Plugin load must never fail because scaffolding did.
277
+ }
269
278
  // The V1 factory only consumes `input.directory`; project/client/$ are unused.
270
279
  const hooks = (await ragPlugin({ directory: ctx.location.directory }, ctx.options));
271
280
  // Tool exposure: default to DIRECT tools (`codemode: false`), matching the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-rag-plugin",
3
- "version": "2.12.0",
3
+ "version": "2.12.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",
@@ -43,7 +43,8 @@
43
43
  "LICENSE"
44
44
  ],
45
45
  "bin": {
46
- "opencode-rag": "./dist/cli/index.js"
46
+ "opencode-rag": "./dist/cli/index.js",
47
+ "opencode-rag-plugin": "./dist/cli/index.js"
47
48
  },
48
49
  "scripts": {
49
50
  "build": "tsc -p tsconfig.build.json && vite build --config src/web/ui/vite.config.ts",
@@ -59,9 +59,11 @@ node "%dp0%\\node_modules\\opencode-rag-plugin\\dist\\cli\\index.js" %*
59
59
 
60
60
  // ── Runtime setup ────────────────────────────────────────────────
61
61
  let setupRuntime;
62
+ let installGlobalPlugin;
62
63
  try {
63
64
  const mod = await import("../dist/core/setup-runtime.js");
64
65
  setupRuntime = mod.setupRuntime;
66
+ ({ installGlobalPlugin } = await import("../dist/core/global-plugin.js"));
65
67
  } catch {
66
68
  console.error("OpenCodeRAG: could not find runtime setup module.");
67
69
  console.error("Run `opencode-rag setup` manually after install.");
@@ -79,4 +81,18 @@ if (!result.success) {
79
81
  console.error("");
80
82
  console.error("Run `opencode-rag setup` manually to retry.");
81
83
  console.error("");
84
+ } else {
85
+ // Install the plugin once into OpenCode's global plugin directory. This is
86
+ // what removes the per-repository plugin files; `opencode-rag setup` then
87
+ // only writes the workspace config, skills and AGENTS.md.
88
+ try {
89
+ const plugin = installGlobalPlugin();
90
+ console.error(`OpenCodeRAG: plugin installed at ${plugin.dir}`);
91
+ } catch (err) {
92
+ console.error(`OpenCodeRAG: could not install the global plugin (${err.message}).`);
93
+ console.error("Run `opencode-rag setup` in your project to finish.");
94
+ }
95
+ console.error("");
96
+ console.error("OpenCodeRAG: next step — cd <your-project> && opencode-rag setup");
97
+ console.error("");
82
98
  }