opencode-rag-plugin 2.11.1 → 2.12.0

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.
Files changed (38) hide show
  1. package/ReadMe.md +305 -207
  2. package/dist/cli/commands/backend-detect.d.ts +1 -1
  3. package/dist/cli/commands/backend-detect.js +1 -1
  4. package/dist/cli/commands/index.d.ts +0 -1
  5. package/dist/cli/commands/index.js +0 -1
  6. package/dist/cli/commands/setup.js +271 -85
  7. package/dist/cli/commands/{init-helpers.d.ts → workspace-helpers.d.ts} +10 -7
  8. package/dist/cli/commands/{init-helpers.js → workspace-helpers.js} +12 -62
  9. package/dist/cli/index.js +1 -2
  10. package/dist/cli/prompt.d.ts +84 -0
  11. package/dist/cli/prompt.js +247 -0
  12. package/dist/cli/types.d.ts +16 -17
  13. package/dist/cli/wizard/apply.d.ts +58 -0
  14. package/dist/cli/wizard/apply.js +234 -0
  15. package/dist/cli/wizard/flow.d.ts +83 -0
  16. package/dist/cli/wizard/flow.js +759 -0
  17. package/dist/cli/wizard/model-catalog.d.ts +80 -0
  18. package/dist/cli/wizard/model-catalog.js +414 -0
  19. package/dist/cli/wizard/types.d.ts +94 -0
  20. package/dist/cli/wizard/types.js +5 -0
  21. package/dist/cli/workspace.d.ts +40 -0
  22. package/dist/cli/workspace.js +322 -0
  23. package/dist/cli.d.ts +1 -1
  24. package/dist/cli.js +1 -1
  25. package/dist/core/config.d.ts +2 -2
  26. package/dist/core/config.js +2 -2
  27. package/dist/core/provider-defaults.d.ts +2 -0
  28. package/dist/core/provider-defaults.js +4 -0
  29. package/dist/eval/fast-index.js +1 -1
  30. package/dist/opencode/system-guidance.d.ts +1 -1
  31. package/dist/opencode/system-guidance.js +1 -1
  32. package/dist/plugin.d.ts +13 -0
  33. package/dist/plugin.js +77 -8
  34. package/dist/tui.d.ts +11 -0
  35. package/dist/tui.js +12 -1
  36. package/package.json +1 -1
  37. package/dist/cli/commands/init.d.ts +0 -51
  38. package/dist/cli/commands/init.js +0 -508
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @fileoverview Auto-detect the Ollama backend (CPU vs GPU) during `init` and
2
+ * @fileoverview Auto-detect the Ollama backend (CPU vs GPU) during `setup` and
3
3
  * pick embedding batch settings tuned for the detected backend.
4
4
  */
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @fileoverview Auto-detect the Ollama backend (CPU vs GPU) during `init` and
2
+ * @fileoverview Auto-detect the Ollama backend (CPU vs GPU) during `setup` and
3
3
  * pick embedding batch settings tuned for the detected backend.
4
4
  */
5
5
  /**
@@ -8,7 +8,6 @@ export { registerStatusCommand } from "./status.js";
8
8
  export { registerListCommand } from "./list.js";
9
9
  export { registerShowCommand } from "./show.js";
10
10
  export { registerDumpCommand } from "./dump.js";
11
- export { registerInitCommand } from "./init.js";
12
11
  export { registerClickHouseCommand } from "./clickhouse.js";
13
12
  export { registerUiCommand } from "./ui.js";
14
13
  export { registerMcpCommand } from "./mcp.js";
@@ -8,7 +8,6 @@ export { registerStatusCommand } from "./status.js";
8
8
  export { registerListCommand } from "./list.js";
9
9
  export { registerShowCommand } from "./show.js";
10
10
  export { registerDumpCommand } from "./dump.js";
11
- export { registerInitCommand } from "./init.js";
12
11
  export { registerClickHouseCommand } from "./clickhouse.js";
13
12
  export { registerUiCommand } from "./ui.js";
14
13
  export { registerMcpCommand } from "./mcp.js";
@@ -1,12 +1,19 @@
1
1
  import path from "node:path";
2
- import { existsSync, lstatSync, rmSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { execSync } from "node:child_process";
4
4
  import { c } from "../format.js";
5
5
  import { getPackageMetadata } from "../helpers.js";
6
6
  import { getRuntimeDir, getVersionFile, readVersionFile, setupRuntime, } from "../../core/setup-runtime.js";
7
7
  import { compareVersions, getCurrentVersion, installLatestUpdate } from "../../core/version-check.js";
8
8
  import { bestAvailablePackageManager, globalUninstallCommand } from "../../core/package-manager.js";
9
- import { isLikelyProjectRoot, isWorkspaceInitialized, runWorkspaceInit } from "./init.js";
9
+ import { globalConfigPath, loadWorkspaceRawConfig, migrateLegacyProjectConfig, findConfigFile, projectConfigPath, } from "../../core/config.js";
10
+ import { createPrompter } from "../prompt.js";
11
+ import { hasExplicitSetupFlags, answersFromFlags, runSetupWizard, } from "../wizard/flow.js";
12
+ import { buildConfigPatch, findShadowingProviderKeys, readJsonObjectSafe, removeConfigPaths, writeConfigPatch, } from "../wizard/apply.js";
13
+ import { generateDefaultConfigJson } from "./workspace-helpers.js";
14
+ import { detectOllamaBackend } from "./backend-detect.js";
15
+ import { isLikelyProjectRoot, runWorkspaceHealthCheck, scaffoldWorkspace, } from "../workspace.js";
16
+ import { destroyAllPooledConnections } from "../../embedder/http.js";
10
17
  const PLUGIN_NAME = "opencode-rag-plugin";
11
18
  function removeIfExists(targetPath) {
12
19
  if (existsSync(targetPath)) {
@@ -35,79 +42,170 @@ function checkOpenCodeRunning() {
35
42
  }
36
43
  }
37
44
  catch {
38
- // OpenCode not found or tools unavailable
45
+ // OpenCode not found or tools unavailable.
39
46
  }
40
47
  }
48
+ /**
49
+ * Whether the effective raw config already selects an embedding model.
50
+ *
51
+ * The wizard only runs when this is false (or `--reconfigure` is passed), so
52
+ * re-running `setup` after an update never re-asks the same questions.
53
+ */
54
+ function hasConfiguredEmbedding(config) {
55
+ const embedding = config.embedding;
56
+ if (!embedding || typeof embedding !== "object" || Array.isArray(embedding))
57
+ return false;
58
+ const section = embedding;
59
+ return typeof section.model === "string" || typeof section.provider === "string";
60
+ }
41
61
  export function registerSetupCommand(program) {
42
62
  program
43
63
  .command("setup")
44
- .description("Install/update the OpenCodeRAG runtime and initialize the current workspace")
64
+ .description("Set up OpenCodeRAG: runtime, workspace files and the model configuration wizard")
45
65
  .addHelpText("after", "\nUse cases:\n" +
46
- " - First-time install: run once per machine to install the plugin runtime\n" +
47
- " into ~/.opencode/ so OpenCode can discover the RAG plugin. When\n" +
48
- " outdated, fetches and installs the latest published version from npm.\n" +
49
- " - Workspace setup: run inside a project to also initialize .opencode/,\n" +
50
- " the skill file and opencode-rag.json for this workspace.\n" +
66
+ " - First-time install: installs the plugin runtime into ~/.opencode/, scaffolds the\n" +
67
+ " current workspace (.opencode/, plugin entries, skills, AGENTS.md) and asks for the\n" +
68
+ " provider, host URL and models (embedding, description, vision, decision).\n" +
69
+ " - Re-running: syncs the runtime and workspace files without asking questions.\n" +
70
+ " Use --reconfigure to re-open the wizard, or pass flags for scripted setups.\n" +
51
71
  " - Updating: use 'opencode-rag update' to install a newer release.\n" +
52
72
  " - Troubleshooting: use --check to inspect the runtime, or --force to reinstall.\n" +
53
- "\nMachine + workspace step: run 'opencode-rag init' only when you need to re-sync\nan already initialized workspace.\n")
73
+ "\nProvider/model settings are written to the global config\n" +
74
+ "(~/.config/opencode/opencode-rag.json); feature toggles to the workspace\n" +
75
+ "config (.opencode/opencode-rag.json).\n")
54
76
  .option("--uninstall", "remove the runtime and cleanup")
55
77
  .option("-f, --force", "force re-setup even if up-to-date")
56
78
  .option("--check", "check whether the runtime is correctly installed")
79
+ .option("--reconfigure", "re-open the model configuration wizard")
80
+ .option("-y, --yes", "non-interactive: never prompt, keep the existing configuration")
81
+ .option("--provider <name>", "provider id: ollama | openai | cohere | anthropic | google")
82
+ .option("--base-url <url>", "provider base URL")
83
+ .option("--api-key <key>", "provider API key (or env:NAME to read an environment variable)")
84
+ .option("--embedding-model <model>", "embedding model id")
85
+ .option("--description-model <model>", "enable chunk descriptions with this model")
86
+ .option("--vision-model <model>", "enable image descriptions with this vision model")
87
+ .option("--decision-model <model>", "enable make_decision with this tev1 model")
88
+ .option("--description [on|off]", "enable or disable chunk descriptions")
89
+ .option("--vision [on|off]", "enable or disable image descriptions")
90
+ .option("--decision [on|off]", "enable or disable the decision model")
91
+ .option("--reranking [on|off]", "enable or disable reranking")
92
+ .option("--shell-guard [on|off]", "enable or disable the shell-command guard")
93
+ .option("--memory-capture [on|off]", "enable or disable automatic quirk capture")
94
+ .option("--vector-store <provider>", "vector store backend: lancedb | clickhouse")
95
+ .option("--clickhouse-url <url>", "ClickHouse endpoint (default http://localhost:8123)")
96
+ .option("--clickhouse-database <name>", "ClickHouse database (default OpenCodeRAG)")
97
+ .option("--clickhouse-user <name>", "ClickHouse user (default default)")
98
+ .option("--clickhouse-password-env <name>", "env var holding the ClickHouse password")
99
+ .option("--clickhouse-namespace <name>", "project namespace / table suffix")
100
+ .option("--skip-install", "skip linking workspace-local plugin dependencies")
101
+ .option("--skip-health-check", "skip provider connectivity and model availability check")
102
+ .option("--skip-runtime", "skip the machine-level runtime install (workspace setup only)")
57
103
  .action(async (options) => {
58
- const pkg = getPackageMetadata();
59
- const pluginVersion = pkg.version;
60
- const runtimeDir = getRuntimeDir();
61
- const versionFile = getVersionFile(runtimeDir);
62
- const runtimePluginDir = path.join(runtimeDir, "node_modules", PLUGIN_NAME);
63
- const runtimeSdkDir = path.join(runtimeDir, "node_modules", "@opencode-ai");
64
- const runtimeSdkPluginDir = path.join(runtimeSdkDir, "plugin");
65
- // --- check status ---
66
- if (options.check) {
67
- console.log(`\n${c.heading("OpenCodeRAG Runtime Status")}\n`);
68
- const runtimeDist = path.join(runtimePluginDir, "dist");
69
- if (existsSync(runtimeDist)) {
70
- console.log(` ${c.label("Runtime:")} ${c.success("installed")} at ${c.file(runtimeDir)}`);
71
- const installedVersion = readVersionFile(versionFile);
72
- console.log(` ${c.label("Installed:")} ${c.value(installedVersion ?? "?")}`);
73
- if (installedVersion !== pluginVersion) {
74
- console.log(` ${c.label("Published:")} ${c.value(pluginVersion)} ${c.warn("(update available — run `opencode-rag setup` to sync)")}`);
75
- }
76
- console.log(` ${c.label("Plugin:")} ${existsSync(runtimePluginDir) ? (() => {
77
- try {
78
- const stat = lstatSync(runtimePluginDir);
79
- return stat.isSymbolicLink() ? "junction" : "directory";
80
- }
81
- catch {
82
- return "?";
83
- }
84
- })() : "missing"}`);
85
- console.log(` ${c.label("SDK:")} ${existsSync(runtimeSdkPluginDir) ? "present" : "missing"}`);
86
- }
87
- else {
88
- console.log(` ${c.label("Runtime:")} ${c.warn("not installed")}`);
89
- console.log(` ${c.label("Run:")} ${c.file("opencode-rag setup")} to install`);
104
+ await runSetup(options);
105
+ });
106
+ }
107
+ /** Parse a Commander optional boolean (`--x`, `--x on`, `--x off`). */
108
+ function parseToggle(value) {
109
+ if (value === undefined)
110
+ return undefined;
111
+ if (typeof value === "boolean")
112
+ return value;
113
+ if (typeof value !== "string")
114
+ return undefined;
115
+ const normalized = value.trim().toLowerCase();
116
+ if (normalized === "on" || normalized === "true" || normalized === "yes" || normalized === "1")
117
+ return true;
118
+ if (normalized === "off" || normalized === "false" || normalized === "no" || normalized === "0")
119
+ return false;
120
+ return undefined;
121
+ }
122
+ /** Normalize the raw Commander options into the wizard flag shape. */
123
+ function normalizeFlags(options) {
124
+ return {
125
+ ...options,
126
+ description: parseToggle(options.description),
127
+ vision: parseToggle(options.vision),
128
+ decision: parseToggle(options.decision),
129
+ reranking: parseToggle(options.reranking),
130
+ shellGuard: parseToggle(options.shellGuard),
131
+ memoryCapture: parseToggle(options.memoryCapture),
132
+ };
133
+ }
134
+ /** Write the baseline workspace config (with Ollama batch tuning when available). */
135
+ async function writeDefaultWorkspaceConfig(configPath, configLabel) {
136
+ let tuning;
137
+ try {
138
+ const info = await detectOllamaBackend();
139
+ tuning = info.tuning;
140
+ const icon = info.backend === "gpu" ? c.success("GPU:") : info.backend === "cpu" ? c.warn("CPU:") : c.dim("Backend:");
141
+ console.log(`\n ${icon} ${info.message}`);
142
+ }
143
+ catch {
144
+ tuning = undefined;
145
+ }
146
+ mkdirSync(path.dirname(configPath), { recursive: true });
147
+ writeFileSync(configPath, generateDefaultConfigJson(tuning), "utf-8");
148
+ console.log(`\n ${c.created("Created:")} ${c.file(configLabel)}`);
149
+ }
150
+ /** The `setup` action body. */
151
+ async function runSetup(rawOptions) {
152
+ const options = normalizeFlags(rawOptions);
153
+ const pkg = getPackageMetadata();
154
+ const pluginVersion = pkg.version;
155
+ const runtimeDir = getRuntimeDir();
156
+ const versionFile = getVersionFile(runtimeDir);
157
+ const runtimePluginDir = path.join(runtimeDir, "node_modules", PLUGIN_NAME);
158
+ const runtimeSdkDir = path.join(runtimeDir, "node_modules", "@opencode-ai");
159
+ const runtimeSdkPluginDir = path.join(runtimeSdkDir, "plugin");
160
+ // --- check status ---
161
+ if (options.check) {
162
+ console.log(`\n${c.heading("OpenCodeRAG Runtime Status")}\n`);
163
+ const runtimeDist = path.join(runtimePluginDir, "dist");
164
+ if (existsSync(runtimeDist)) {
165
+ console.log(` ${c.label("Runtime:")} ${c.success("installed")} at ${c.file(runtimeDir)}`);
166
+ const installedVersion = readVersionFile(versionFile);
167
+ console.log(` ${c.label("Installed:")} ${c.value(installedVersion ?? "?")}`);
168
+ if (installedVersion !== pluginVersion) {
169
+ console.log(` ${c.label("Published:")} ${c.value(pluginVersion)} ${c.warn("(update available — run `opencode-rag setup` to sync)")}`);
90
170
  }
91
- console.log();
92
- return;
171
+ console.log(` ${c.label("Plugin:")} ${existsSync(runtimePluginDir) ? (() => {
172
+ try {
173
+ const stat = lstatSync(runtimePluginDir);
174
+ return stat.isSymbolicLink() ? "junction" : "directory";
175
+ }
176
+ catch {
177
+ return "?";
178
+ }
179
+ })() : "missing"}`);
180
+ console.log(` ${c.label("SDK:")} ${existsSync(runtimeSdkPluginDir) ? "present" : "missing"}`);
93
181
  }
94
- // --- uninstall ---
95
- if (options.uninstall) {
96
- console.log(`\n${c.heading("Removing OpenCodeRAG runtime...")}\n`);
97
- removeIfExists(runtimePluginDir);
98
- // Only remove the @opencode-ai/plugin SDK package — the scope dir may
99
- // be shared with other OpenCode plugins/tools.
100
- removeIfExists(runtimeSdkPluginDir);
101
- removeIfExists(versionFile);
102
- console.log(` ${c.updated("Removed:")} ${c.file(runtimePluginDir)}`);
103
- console.log(` ${c.updated("Removed:")} ${c.file(runtimeSdkPluginDir)}`);
104
- const uninstallPm = bestAvailablePackageManager() ?? "npm";
105
- console.log(`\n ${c.success("Done.")} Run ${c.file(globalUninstallCommand(uninstallPm, PLUGIN_NAME))} to remove the global package.\n`);
106
- return;
182
+ else {
183
+ console.log(` ${c.label("Runtime:")} ${c.warn("not installed")}`);
184
+ console.log(` ${c.label("Run:")} ${c.file("opencode-rag setup")} to install`);
107
185
  }
108
- // --- install ---
186
+ console.log();
187
+ return;
188
+ }
189
+ // --- uninstall ---
190
+ if (options.uninstall) {
191
+ console.log(`\n${c.heading("Removing OpenCodeRAG runtime...")}\n`);
192
+ removeIfExists(runtimePluginDir);
193
+ // Only remove the @opencode-ai/plugin SDK package — the scope dir may be
194
+ // shared with other OpenCode plugins/tools.
195
+ removeIfExists(runtimeSdkPluginDir);
196
+ removeIfExists(versionFile);
197
+ console.log(` ${c.updated("Removed:")} ${c.file(runtimePluginDir)}`);
198
+ console.log(` ${c.updated("Removed:")} ${c.file(runtimeSdkPluginDir)}`);
199
+ const uninstallPm = bestAvailablePackageManager() ?? "npm";
200
+ console.log(`\n ${c.success("Done.")} Run ${c.file(globalUninstallCommand(uninstallPm, PLUGIN_NAME))} to remove the global package.\n`);
201
+ return;
202
+ }
203
+ // --- install runtime ---
204
+ if (options.skipRuntime) {
205
+ console.log(`\n ${c.exists("Skipped:")} runtime install (--skip-runtime)`);
206
+ }
207
+ else {
109
208
  console.log(`\n${c.heading("Setting up OpenCodeRAG runtime...")}\n`);
110
- // Check if already installed and up-to-date
111
209
  const installedVersion = readVersionFile(versionFile);
112
210
  const runtimeDist = path.join(runtimePluginDir, "dist");
113
211
  const alreadyInstalled = existsSync(runtimeDist);
@@ -128,31 +226,121 @@ export function registerSetupCommand(program) {
128
226
  console.error(` ${c.error("✗")} ${err}`);
129
227
  }
130
228
  console.error(`\n ${c.error("Setup failed. Please check the errors above or run with --force.\n")}`);
131
- process.exit(1);
132
- }
133
- // --- workspace step: automatically initialize the current workspace ---
134
- const cwd = process.cwd();
135
- console.log(`\n${c.heading("Workspace")}`);
136
- if (isLikelyProjectRoot(cwd)) {
137
- if (isWorkspaceInitialized(cwd)) {
138
- console.log(` ${c.exists("Exists:")} OpenCodeRAG already initialized in ${c.file(cwd)}`);
139
- console.log(` ${c.dim("Run `opencode-rag init` to re-sync workspace files when needed.\n")}`);
229
+ process.exitCode = 1;
230
+ return;
231
+ }
232
+ }
233
+ // --- workspace ---
234
+ const cwd = process.cwd();
235
+ const prompter = createPrompter(!options.yes);
236
+ try {
237
+ if (!isLikelyProjectRoot(cwd)) {
238
+ console.log(`\n${c.heading("Workspace")}`);
239
+ console.log(` ${c.dim("This directory does not look like a project root.")}`);
240
+ const proceed = prompter.interactive
241
+ ? await prompter.confirm({ message: "Initialize it as an OpenCodeRAG workspace anyway?", defaultValue: false })
242
+ : false;
243
+ if (!proceed) {
244
+ console.log(` ${c.warn("Skipped workspace setup.")} Run setup inside a project directory.\n`);
245
+ return;
246
+ }
247
+ }
248
+ migrateLegacyProjectConfig(cwd);
249
+ const configPath = findConfigFile(cwd) ?? projectConfigPath(cwd);
250
+ const configLabel = path.relative(cwd, configPath).replace(/\\/g, "/");
251
+ const existing = loadWorkspaceRawConfig(cwd);
252
+ const configured = hasConfiguredEmbedding(existing);
253
+ const explicitFlags = hasExplicitSetupFlags(options);
254
+ let answers;
255
+ if (prompter.interactive && (options.reconfigure || !configured)) {
256
+ const existingEmbedding = existing.embedding;
257
+ const proxy = existingEmbedding && typeof existingEmbedding === "object" && !Array.isArray(existingEmbedding)
258
+ ? existingEmbedding.proxy
259
+ : undefined;
260
+ answers = await runSetupWizard({
261
+ ...options,
262
+ prompter,
263
+ existing,
264
+ proxy: proxy,
265
+ });
266
+ if (answers === undefined) {
267
+ console.log(`\n ${c.warn("Setup cancelled.")} No configuration was changed.\n`);
268
+ return;
269
+ }
270
+ }
271
+ else if (explicitFlags) {
272
+ answers = answersFromFlags(options, existing);
273
+ }
274
+ if (answers) {
275
+ // A wizard/flag run still needs the baseline template (indexing tuning,
276
+ // chunking, retrieval defaults) before the sparse patch is merged in.
277
+ if (!existsSync(configPath)) {
278
+ await writeDefaultWorkspaceConfig(configPath, configLabel);
279
+ }
280
+ const patch = buildConfigPatch(answers);
281
+ const globalPath = globalConfigPath();
282
+ if (!writeConfigPatch(globalPath, patch.global)) {
283
+ console.log(` ${c.warn("Could not write the global config.")} Check permissions for ${c.file(globalPath)}.`);
140
284
  }
141
285
  else {
142
- await runWorkspaceInit({});
286
+ console.log(`\n ${c.updated("Updated:")} ${c.file(globalPath)} ${c.dim("(provider/model settings)")}`);
287
+ }
288
+ // Strip stale provider keys that the old `init` template wrote into the
289
+ // workspace file: the global layer is a base layer, so those copies
290
+ // would shadow the models just chosen.
291
+ const workspaceRaw = readJsonObjectSafe(configPath);
292
+ const shadowing = findShadowingProviderKeys(workspaceRaw);
293
+ if (shadowing.length > 0) {
294
+ const remove = prompter.interactive
295
+ ? await prompter.confirm({
296
+ message: `Remove ${shadowing.length} stale provider setting(s) from ${configLabel}? They would override the global config.`,
297
+ defaultValue: true,
298
+ })
299
+ : true;
300
+ if (remove) {
301
+ removeConfigPaths(workspaceRaw, shadowing);
302
+ writeFileSync(`${configPath}.bak`, readFileSync(configPath, "utf-8"), "utf-8");
303
+ writeFileSync(configPath, `${JSON.stringify(workspaceRaw, null, 2)}\n`, "utf-8");
304
+ console.log(` ${c.updated("Cleaned:")} ${c.file(configLabel)} ${c.dim("(provider keys moved to the global config)")}`);
305
+ }
306
+ }
307
+ if (!writeConfigPatch(configPath, patch.workspace)) {
308
+ console.log(` ${c.warn("Could not write the workspace config.")} Check permissions for ${c.file(configPath)}.`);
309
+ }
310
+ else {
311
+ console.log(` ${c.updated("Updated:")} ${c.file(configLabel)} ${c.dim("(feature toggles)")}`);
143
312
  }
144
313
  }
314
+ else if (!existsSync(configPath)) {
315
+ // Non-interactive first run without flags: write the default template.
316
+ await writeDefaultWorkspaceConfig(configPath, configLabel);
317
+ }
145
318
  else {
146
- console.log(` ${c.dim("Current directory is not a project root - skipping workspace initialization.")}`);
147
- console.log(` ${c.dim("Run `opencode-rag init` inside the workspace when needed.\n")}`);
148
- }
149
- console.log(`\n${c.success("Setup complete.")}`);
150
- console.log(`\n ${c.dim("Next steps:")}`);
151
- console.log(` ${c.dim(" 1. Restart OpenCode if it is running")}`);
152
- console.log(` ${c.dim(" 2. Run `opencode-rag index` to build the search index")}`);
153
- checkOpenCodeRunning();
154
- console.log();
155
- });
319
+ console.log(`\n ${c.exists("Using:")} ${c.file(configLabel)} ${c.dim("(run setup --reconfigure to change providers)")}`);
320
+ }
321
+ await scaffoldWorkspace({
322
+ force: options.force,
323
+ skipInstall: options.skipInstall,
324
+ configPath,
325
+ });
326
+ if (!options.skipHealthCheck) {
327
+ await runWorkspaceHealthCheck(cwd, prompter);
328
+ }
329
+ }
330
+ catch (err) {
331
+ console.error(`\n ${c.error("Setup failed:")} ${err.message}`);
332
+ process.exitCode = 1;
333
+ }
334
+ finally {
335
+ prompter.close();
336
+ destroyAllPooledConnections();
337
+ }
338
+ console.log(`\n${c.success("Setup complete.")}`);
339
+ console.log(`\n ${c.dim("Next steps:")}`);
340
+ console.log(` ${c.dim(" 1. Restart OpenCode if it is running")}`);
341
+ console.log(` ${c.dim(" 2. Run `opencode-rag index` to build the search index")}`);
342
+ checkOpenCodeRunning();
343
+ console.log();
156
344
  }
157
345
  /**
158
346
  * Self-update: when this OpenCodeRAG build is outdated compared to the latest
@@ -181,9 +369,11 @@ async function ensureUpToDate() {
181
369
  if (!updated.success) {
182
370
  console.error(` ${c.error("✗-")} ${updated.message}`);
183
371
  console.error(` ${c.dim("You can retry later with `opencode-rag update`.\n")}`);
184
- process.exit(1);
372
+ process.exitCode = 1;
373
+ }
374
+ else {
375
+ console.log(` ${c.success("✓")} ${updated.message}`);
185
376
  }
186
- console.log(` ${c.success("✓")} ${updated.message}`);
187
377
  }
188
378
  /**
189
379
  * Query the npm registry for the latest published version of the plugin.
@@ -195,14 +385,10 @@ async function ensureUpToDate() {
195
385
  *
196
386
  * Best-effort: returns `null` when every endpoint lookup fails (offline,
197
387
  * mirror without the endpoint, malformed response).
198
- *
199
- * @returns The latest version string, or `null` on failure.
200
388
  */
201
389
  async function getLatestNpmVersion() {
202
390
  const registry = (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
203
391
  const pkgPath = PLUGIN_NAME.includes("/") ? PLUGIN_NAME.replace("/", "%2F") : PLUGIN_NAME;
204
- // Prefer the lightweight dist-tags endpoint; fall back to the version
205
- // document for mirrors that do not implement it.
206
392
  const urls = [
207
393
  `${registry}/-/package/${pkgPath}/dist-tags`,
208
394
  `${registry}/${pkgPath}/latest`,
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @fileoverview Helper functions for the init command — file generation, config building, dependency linking, and gitignore merging.
2
+ * @fileoverview Helper functions for `opencode-rag setup` — file generation, config building, dependency linking, and gitignore merging.
3
3
  */
4
4
  /**
5
- * Helper functions for the `init` command — file generation, config building,
5
+ * Helper functions for the `setup` command — file generation, config building,
6
6
  * dependency installation, and gitignore merging.
7
7
  */
8
8
  import type { PackageMetadata } from "../types.js";
@@ -170,13 +170,16 @@ export declare function getRuntimeDir(): string;
170
170
  */
171
171
  export declare function installPluginFromGlobal(opencodeDir: string, packageName: string, skipInstall: boolean): Promise<void>;
172
172
  /**
173
- * Generate the default `opencode-rag.json` configuration content.
173
+ * Generate the default workspace `opencode-rag.json` configuration content.
174
+ *
175
+ * Provider-scoped keys (`provider`, `model`, `baseUrl`, `apiKey`,
176
+ * `vectorDimension`) are deliberately NOT emitted: they describe the machine
177
+ * and live in the global config, which is the BASE layer. A workspace copy
178
+ * would shadow the global choice (and could commit an API key), so only
179
+ * repository-scoped keys and feature toggles are written here.
174
180
  *
175
181
  * @param tuning - Optional embedding batch tuning (auto-detected from the
176
182
  * Ollama backend). Falls back to `DEFAULT_CONFIG` for any omitted field.
177
- * @param existingConfigRaw - Optional raw text of the config file that is about
178
- * to be replaced. Its `apiKey` and `vectorDimension` are carried over: a
179
- * reset must not silently change the store schema or drop provider auth.
180
183
  * @returns A pretty-printed JSON string with all default configuration values.
181
184
  */
182
- export declare function generateDefaultConfigJson(tuning?: Partial<IndexingTuning>, existingConfigRaw?: string): string;
185
+ export declare function generateDefaultConfigJson(tuning?: Partial<IndexingTuning>): string;
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @fileoverview Helper functions for the init command — file generation, config building, dependency linking, and gitignore merging.
2
+ * @fileoverview Helper functions for `opencode-rag setup` — file generation, config building, dependency linking, and gitignore merging.
3
3
  */
4
4
  /**
5
- * Helper functions for the `init` command — file generation, config building,
5
+ * Helper functions for the `setup` command — file generation, config building,
6
6
  * dependency installation, and gitignore merging.
7
7
  */
8
8
  import path from "node:path";
@@ -514,7 +514,7 @@ export async function installPluginFromGlobal(opencodeDir, packageName, skipInst
514
514
  }
515
515
  // Create directory junction from workspace → global runtime.
516
516
  // Junction creation can throw (EPERM, cross-drive on Windows) — fall back
517
- // to a copy instead of aborting `init`.
517
+ // to a copy instead of aborting `setup`.
518
518
  console.log(` ${c.created("Linking:")} ${packageName} from global cache...`);
519
519
  mkdirSync(path.dirname(workspaceTarget), { recursive: true });
520
520
  try {
@@ -545,61 +545,20 @@ export async function installPluginFromGlobal(opencodeDir, packageName, skipInst
545
545
  }
546
546
  }
547
547
  /**
548
- * `embedding` keys that the default template does not model but that MUST
549
- * survive a rewrite. Losing `vectorDimension` makes the next run fall back to
550
- * the 384 default (and corrupts a rebuild against a store whose schema is
551
- * 4096), and `apiKey` is provider auth the template never carries — both are
552
- * invisible data loss when a user confirms "Overwrite with default config?".
553
- */
554
- const PRESERVED_EMBEDDING_KEYS = ["apiKey", "vectorDimension"];
555
- /**
556
- * Pick the identity-critical `embedding` keys out of an existing config file so
557
- * the generated defaults can re-apply them. Malformed input simply yields an
558
- * empty set (the pure default template).
559
- */
560
- function preservedEmbeddingKeys(existingConfigRaw) {
561
- if (!existingConfigRaw)
562
- return {};
563
- try {
564
- const raw = existingConfigRaw.charCodeAt(0) === 0xfeff
565
- ? existingConfigRaw.slice(1)
566
- : existingConfigRaw;
567
- const parsed = JSON.parse(raw);
568
- const embedding = parsed?.embedding;
569
- if (!embedding || typeof embedding !== "object")
570
- return {};
571
- const preserved = {};
572
- for (const key of PRESERVED_EMBEDDING_KEYS) {
573
- const value = embedding[key];
574
- if (value !== undefined && value !== null && value !== "") {
575
- preserved[key] = value;
576
- }
577
- }
578
- return preserved;
579
- }
580
- catch {
581
- return {};
582
- }
583
- }
584
- /**
585
- * Generate the default `opencode-rag.json` configuration content.
548
+ * Generate the default workspace `opencode-rag.json` configuration content.
549
+ *
550
+ * Provider-scoped keys (`provider`, `model`, `baseUrl`, `apiKey`,
551
+ * `vectorDimension`) are deliberately NOT emitted: they describe the machine
552
+ * and live in the global config, which is the BASE layer. A workspace copy
553
+ * would shadow the global choice (and could commit an API key), so only
554
+ * repository-scoped keys and feature toggles are written here.
586
555
  *
587
556
  * @param tuning - Optional embedding batch tuning (auto-detected from the
588
557
  * Ollama backend). Falls back to `DEFAULT_CONFIG` for any omitted field.
589
- * @param existingConfigRaw - Optional raw text of the config file that is about
590
- * to be replaced. Its `apiKey` and `vectorDimension` are carried over: a
591
- * reset must not silently change the store schema or drop provider auth.
592
558
  * @returns A pretty-printed JSON string with all default configuration values.
593
559
  */
594
- export function generateDefaultConfigJson(tuning, existingConfigRaw) {
560
+ export function generateDefaultConfigJson(tuning) {
595
561
  return JSON.stringify({
596
- embedding: {
597
- provider: DEFAULT_CONFIG.embedding.provider,
598
- baseUrl: DEFAULT_CONFIG.embedding.baseUrl,
599
- model: DEFAULT_CONFIG.embedding.model,
600
- timeoutMs: DEFAULT_CONFIG.embedding.timeoutMs,
601
- ...preservedEmbeddingKeys(existingConfigRaw),
602
- },
603
562
  indexing: {
604
563
  includeExtensions: DEFAULT_CONFIG.indexing.includeExtensions,
605
564
  excludeDirs: DEFAULT_CONFIG.indexing.excludeDirs,
@@ -641,18 +600,12 @@ export function generateDefaultConfigJson(tuning, existingConfigRaw) {
641
600
  },
642
601
  imageDescription: {
643
602
  enabled: DEFAULT_CONFIG.imageDescription.enabled,
644
- provider: DEFAULT_CONFIG.imageDescription.provider,
645
- model: DEFAULT_CONFIG.imageDescription.model,
646
- baseUrl: DEFAULT_CONFIG.imageDescription.baseUrl,
647
603
  timeoutMs: DEFAULT_CONFIG.imageDescription.timeoutMs,
648
604
  think: DEFAULT_CONFIG.imageDescription.think,
649
605
  numCtx: DEFAULT_CONFIG.imageDescription.numCtx,
650
606
  },
651
607
  decision: {
652
608
  enabled: DEFAULT_CONFIG.decision.enabled,
653
- provider: DEFAULT_CONFIG.decision.provider,
654
- baseUrl: DEFAULT_CONFIG.decision.baseUrl,
655
- model: DEFAULT_CONFIG.decision.model,
656
609
  timeoutMs: DEFAULT_CONFIG.decision.timeoutMs,
657
610
  keepAlive: DEFAULT_CONFIG.decision.keepAlive,
658
611
  routeBeforeAsking: DEFAULT_CONFIG.decision.routeBeforeAsking,
@@ -666,9 +619,6 @@ export function generateDefaultConfigJson(tuning, existingConfigRaw) {
666
619
  },
667
620
  description: {
668
621
  enabled: DEFAULT_CONFIG.description.enabled,
669
- provider: DEFAULT_CONFIG.description.provider,
670
- baseUrl: DEFAULT_CONFIG.description.baseUrl,
671
- model: DEFAULT_CONFIG.description.model,
672
622
  think: DEFAULT_CONFIG.description.think,
673
623
  numCtx: DEFAULT_CONFIG.description.numCtx,
674
624
  timeoutMs: DEFAULT_CONFIG.description.timeoutMs,
@@ -686,4 +636,4 @@ export function generateDefaultConfigJson(tuning, existingConfigRaw) {
686
636
  },
687
637
  }, null, 2) + "\n";
688
638
  }
689
- //# sourceMappingURL=init-helpers.js.map
639
+ //# sourceMappingURL=workspace-helpers.js.map
package/dist/cli/index.js CHANGED
@@ -15,7 +15,7 @@ import { realpathSync } from "node:fs";
15
15
  import { basename, dirname } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { getPackageMetadata } from "./helpers.js";
18
- import { registerIndexCommand, registerQueryCommand, registerClearCommand, registerStatusCommand, registerListCommand, registerShowCommand, registerDumpCommand, registerInitCommand, registerClickHouseCommand, registerUiCommand, registerMcpCommand, registerSetupCommand, registerUpdateCommand, registerEvalSessionsCommand, registerEvalAnalyzeCommand, registerEvalCompareCommand, registerEvalGateCommand, registerEvalDecideCommand, registerEvalTuneCommand, registerDescribeImageCommand, registerDecideCommand, registerQuirkCommand, } from "./commands/index.js";
18
+ import { registerIndexCommand, registerQueryCommand, registerClearCommand, registerStatusCommand, registerListCommand, registerShowCommand, registerDumpCommand, registerClickHouseCommand, registerUiCommand, registerMcpCommand, registerSetupCommand, registerUpdateCommand, registerEvalSessionsCommand, registerEvalAnalyzeCommand, registerEvalCompareCommand, registerEvalGateCommand, registerEvalDecideCommand, registerEvalTuneCommand, registerDescribeImageCommand, registerDecideCommand, registerQuirkCommand, } from "./commands/index.js";
19
19
  /**
20
20
  * The top-level Commander program instance that defines the `opencode-rag` CLI.
21
21
  *
@@ -57,7 +57,6 @@ registerEvalCompareCommand(program);
57
57
  registerEvalGateCommand(program);
58
58
  registerEvalDecideCommand(program);
59
59
  registerEvalTuneCommand(program);
60
- registerInitCommand(program);
61
60
  registerClickHouseCommand(program);
62
61
  registerQuirkCommand(program);
63
62
  // ── Auto-run detection ──────────────────────────────────────────