opencode-rag-plugin 2.11.2 → 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.
Files changed (50) hide show
  1. package/ReadMe.md +386 -222
  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 +344 -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} +15 -62
  9. package/dist/cli/index.js +1 -2
  10. package/dist/cli/ollama.d.ts +12 -0
  11. package/dist/cli/ollama.js +26 -0
  12. package/dist/cli/prompt.d.ts +121 -0
  13. package/dist/cli/prompt.js +309 -0
  14. package/dist/cli/types.d.ts +31 -19
  15. package/dist/cli/wizard/apply.d.ts +60 -0
  16. package/dist/cli/wizard/apply.js +243 -0
  17. package/dist/cli/wizard/flow.d.ts +121 -0
  18. package/dist/cli/wizard/flow.js +904 -0
  19. package/dist/cli/wizard/model-catalog.d.ts +80 -0
  20. package/dist/cli/wizard/model-catalog.js +414 -0
  21. package/dist/cli/wizard/presets.d.ts +55 -0
  22. package/dist/cli/wizard/presets.js +70 -0
  23. package/dist/cli/wizard/repair.d.ts +54 -0
  24. package/dist/cli/wizard/repair.js +266 -0
  25. package/dist/cli/wizard/types.d.ts +99 -0
  26. package/dist/cli/wizard/types.js +5 -0
  27. package/dist/cli/workspace.d.ts +57 -0
  28. package/dist/cli/workspace.js +407 -0
  29. package/dist/cli.d.ts +1 -1
  30. package/dist/cli.js +1 -1
  31. package/dist/core/auto-scaffold.d.ts +21 -0
  32. package/dist/core/auto-scaffold.js +80 -0
  33. package/dist/core/config.d.ts +13 -2
  34. package/dist/core/config.js +13 -3
  35. package/dist/core/global-plugin.d.ts +48 -0
  36. package/dist/core/global-plugin.js +114 -0
  37. package/dist/core/provider-defaults.d.ts +2 -0
  38. package/dist/core/provider-defaults.js +4 -0
  39. package/dist/core/setup-runtime.js +40 -26
  40. package/dist/embedder/health.js +44 -2
  41. package/dist/eval/fast-index.js +1 -1
  42. package/dist/opencode/system-guidance.d.ts +1 -1
  43. package/dist/opencode/system-guidance.js +1 -1
  44. package/dist/tui.d.ts +11 -0
  45. package/dist/tui.js +12 -1
  46. package/dist/v2/v2-adapter.js +9 -0
  47. package/package.json +3 -2
  48. package/scripts/postinstall-setup.js +16 -0
  49. package/dist/cli/commands/init.d.ts +0 -51
  50. 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,21 @@
1
1
  import path from "node:path";
2
- import { existsSync, lstatSync, rmSync } from "node:fs";
3
- import { execSync } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { execFileSync, 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 { offerHealthRepairs } from "../wizard/repair.js";
14
+ import { generateDefaultConfigJson } from "./workspace-helpers.js";
15
+ import { detectOllamaBackend } from "./backend-detect.js";
16
+ import { isLikelyProjectRoot, runWorkspaceHealthCheck, scaffoldWorkspace, } from "../workspace.js";
17
+ import { destroyAllPooledConnections } from "../../embedder/http.js";
18
+ import { getGlobalPluginDir, installGlobalPlugin, isGlobalPluginInstalled, isWorkspacePluginInstalled, removeGlobalPlugin, } from "../../core/global-plugin.js";
10
19
  const PLUGIN_NAME = "opencode-rag-plugin";
11
20
  function removeIfExists(targetPath) {
12
21
  if (existsSync(targetPath)) {
@@ -35,79 +44,210 @@ function checkOpenCodeRunning() {
35
44
  }
36
45
  }
37
46
  catch {
38
- // OpenCode not found or tools unavailable
47
+ // OpenCode not found or tools unavailable.
39
48
  }
40
49
  }
50
+ /**
51
+ * Whether the effective raw config already selects an embedding model.
52
+ *
53
+ * The wizard only runs when this is false (or `--reconfigure` is passed), so
54
+ * re-running `setup` after an update never re-asks the same questions.
55
+ */
56
+ function hasConfiguredEmbedding(config) {
57
+ const embedding = config.embedding;
58
+ if (!embedding || typeof embedding !== "object" || Array.isArray(embedding))
59
+ return false;
60
+ const section = embedding;
61
+ return typeof section.model === "string" || typeof section.provider === "string";
62
+ }
41
63
  export function registerSetupCommand(program) {
42
64
  program
43
65
  .command("setup")
44
- .description("Install/update the OpenCodeRAG runtime and initialize the current workspace")
66
+ .description("Set up OpenCodeRAG: runtime, workspace files and the model configuration wizard")
45
67
  .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" +
68
+ " - First-time install: installs the plugin runtime into ~/.opencode/, scaffolds the\n" +
69
+ " current workspace (.opencode/, plugin entries, skills, AGENTS.md) and asks for the\n" +
70
+ " provider, host URL and models (embedding, description, vision, decision).\n" +
71
+ " - Re-running: syncs the runtime and workspace files without asking questions.\n" +
72
+ " Use --reconfigure to re-open the wizard, or pass flags for scripted setups.\n" +
51
73
  " - Updating: use 'opencode-rag update' to install a newer release.\n" +
52
74
  " - 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")
75
+ "\nProvider/model settings are written to the global config\n" +
76
+ "(~/.config/opencode/opencode-rag.json); feature toggles to the workspace\n" +
77
+ "config (.opencode/opencode-rag.json).\n")
54
78
  .option("--uninstall", "remove the runtime and cleanup")
55
79
  .option("-f, --force", "force re-setup even if up-to-date")
56
80
  .option("--check", "check whether the runtime is correctly installed")
81
+ .option("--reconfigure", "re-open the model configuration wizard")
82
+ .option("-y, --yes", "non-interactive: never prompt, keep the existing configuration")
83
+ .option("--provider <name>", "provider id: ollama | openai | cohere | anthropic | google")
84
+ .option("--base-url <url>", "provider base URL")
85
+ .option("--api-key <key>", "provider API key (or env:NAME to read an environment variable)")
86
+ .option("--embedding-model <model>", "embedding model id")
87
+ .option("--description-model <model>", "enable chunk descriptions with this model")
88
+ .option("--vision-model <model>", "enable image descriptions with this vision model")
89
+ .option("--decision-model <model>", "enable make_decision with this tev1 model")
90
+ .option("--description [on|off]", "enable or disable chunk descriptions")
91
+ .option("--vision [on|off]", "enable or disable image descriptions")
92
+ .option("--decision [on|off]", "enable or disable the decision model")
93
+ .option("--reranking [on|off]", "enable or disable reranking")
94
+ .option("--shell-guard [on|off]", "enable or disable the shell-command guard")
95
+ .option("--memory-capture [on|off]", "enable or disable automatic quirk capture")
96
+ .option("--vector-store <provider>", "vector store backend: lancedb | clickhouse")
97
+ .option("--clickhouse-url <url>", "ClickHouse endpoint (default http://localhost:8123)")
98
+ .option("--clickhouse-database <name>", "ClickHouse database (default OpenCodeRAG)")
99
+ .option("--clickhouse-user <name>", "ClickHouse user (default default)")
100
+ .option("--clickhouse-password-env <name>", "env var holding the ClickHouse password")
101
+ .option("--clickhouse-namespace <name>", "project namespace / table suffix")
102
+ .option("--skip-install [on|off]", "skip linking workspace-local plugin dependencies")
103
+ .option("--skip-health-check [on|off]", "skip provider connectivity and model availability check")
104
+ .option("--skip-runtime [on|off]", "skip the machine-level runtime install (workspace setup only)")
105
+ .option("--workspace-plugin", "install the plugin into this workspace instead of the global config")
106
+ .option("--no-index", "do not offer to build the search index after setup")
57
107
  .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"}`);
108
+ await runSetup(options);
109
+ });
110
+ }
111
+ /** Parse a Commander optional boolean (`--x`, `--x on`, `--x off`). */
112
+ function parseToggle(value) {
113
+ if (value === undefined)
114
+ return undefined;
115
+ if (typeof value === "boolean")
116
+ return value;
117
+ if (typeof value !== "string")
118
+ return undefined;
119
+ const normalized = value.trim().toLowerCase();
120
+ if (normalized === "on" || normalized === "true" || normalized === "yes" || normalized === "1")
121
+ return true;
122
+ if (normalized === "off" || normalized === "false" || normalized === "no" || normalized === "0")
123
+ return false;
124
+ return undefined;
125
+ }
126
+ /** Normalize the raw Commander options into the wizard flag shape. */
127
+ function normalizeFlags(options) {
128
+ return {
129
+ ...options,
130
+ description: parseToggle(options.description),
131
+ vision: parseToggle(options.vision),
132
+ decision: parseToggle(options.decision),
133
+ reranking: parseToggle(options.reranking),
134
+ shellGuard: parseToggle(options.shellGuard),
135
+ memoryCapture: parseToggle(options.memoryCapture),
136
+ // Optional-value booleans: `--skip-x`, `--skip-x=false`, `--skip-x off`.
137
+ skipInstall: parseToggle(options.skipInstall),
138
+ skipHealthCheck: parseToggle(options.skipHealthCheck),
139
+ skipRuntime: parseToggle(options.skipRuntime),
140
+ };
141
+ }
142
+ /** Write the baseline workspace config (with Ollama batch tuning when available). */
143
+ async function writeDefaultWorkspaceConfig(configPath, configLabel) {
144
+ let tuning;
145
+ try {
146
+ const info = await detectOllamaBackend();
147
+ tuning = info.tuning;
148
+ const icon = info.backend === "gpu" ? c.success("GPU:") : info.backend === "cpu" ? c.warn("CPU:") : c.dim("Backend:");
149
+ console.log(`\n ${icon} ${info.message}`);
150
+ }
151
+ catch {
152
+ tuning = undefined;
153
+ }
154
+ mkdirSync(path.dirname(configPath), { recursive: true });
155
+ writeFileSync(configPath, generateDefaultConfigJson(tuning), "utf-8");
156
+ console.log(`\n ${c.created("Created:")} ${c.file(configLabel)}`);
157
+ }
158
+ /**
159
+ * Run `opencode-rag index` in a child process so setup can finish with a
160
+ * ready-to-query index instead of requiring a second command.
161
+ */
162
+ function buildIndexNow() {
163
+ const entry = process.argv[1];
164
+ if (!entry)
165
+ return;
166
+ try {
167
+ console.log(`\n${c.heading("Building the search index...")}\n`);
168
+ execFileSync(process.execPath, [...process.execArgv, entry, "index"], {
169
+ stdio: "inherit",
170
+ windowsHide: true,
171
+ });
172
+ }
173
+ catch {
174
+ console.log(`\n ${c.warn("Indexing did not finish.")} Run \`opencode-rag index\` to retry.`);
175
+ }
176
+ }
177
+ /** The `setup` action body. */
178
+ async function runSetup(rawOptions) {
179
+ const options = normalizeFlags(rawOptions);
180
+ const pkg = getPackageMetadata();
181
+ const pluginVersion = pkg.version;
182
+ const runtimeDir = getRuntimeDir();
183
+ const versionFile = getVersionFile(runtimeDir);
184
+ const runtimePluginDir = path.join(runtimeDir, "node_modules", PLUGIN_NAME);
185
+ const runtimeSdkDir = path.join(runtimeDir, "node_modules", "@opencode-ai");
186
+ const runtimeSdkPluginDir = path.join(runtimeSdkDir, "plugin");
187
+ // --- check status ---
188
+ if (options.check) {
189
+ console.log(`\n${c.heading("OpenCodeRAG Runtime Status")}\n`);
190
+ const runtimeDist = path.join(runtimePluginDir, "dist");
191
+ if (existsSync(runtimeDist)) {
192
+ console.log(` ${c.label("Runtime:")} ${c.success("installed")} at ${c.file(runtimeDir)}`);
193
+ const installedVersion = readVersionFile(versionFile);
194
+ console.log(` ${c.label("Installed:")} ${c.value(installedVersion ?? "?")}`);
195
+ if (installedVersion !== pluginVersion) {
196
+ console.log(` ${c.label("Published:")} ${c.value(pluginVersion)} ${c.warn("(update available — run `opencode-rag setup` to sync)")}`);
86
197
  }
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`);
198
+ console.log(` ${c.label("Plugin:")} ${existsSync(runtimePluginDir) ? (() => {
199
+ try {
200
+ const stat = lstatSync(runtimePluginDir);
201
+ return stat.isSymbolicLink() ? "junction" : "directory";
202
+ }
203
+ catch {
204
+ return "?";
205
+ }
206
+ })() : "missing"}`);
207
+ console.log(` ${c.label("SDK:")} ${existsSync(runtimeSdkPluginDir) ? "present" : "missing"}`);
208
+ {
209
+ const globalDir = getGlobalPluginDir();
210
+ if (isGlobalPluginInstalled()) {
211
+ console.log(` ${c.label("Plugin mode:")} ${c.success("global")} at ${c.file(globalDir)}`);
212
+ }
213
+ else if (isWorkspacePluginInstalled(process.cwd())) {
214
+ console.log(` ${c.label("Plugin mode:")} ${c.value("workspace")} (legacy layout in this project)`);
215
+ }
216
+ else {
217
+ console.log(` ${c.label("Plugin mode:")} ${c.warn("not installed")} — run \`opencode-rag setup\``);
218
+ }
90
219
  }
91
- console.log();
92
- return;
93
220
  }
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;
221
+ else {
222
+ console.log(` ${c.label("Runtime:")} ${c.warn("not installed")}`);
223
+ console.log(` ${c.label("Run:")} ${c.file("opencode-rag setup")} to install`);
224
+ }
225
+ console.log();
226
+ return;
227
+ }
228
+ // --- uninstall ---
229
+ if (options.uninstall) {
230
+ console.log(`\n${c.heading("Removing OpenCodeRAG runtime...")}\n`);
231
+ removeIfExists(runtimePluginDir);
232
+ // Only remove the @opencode-ai/plugin SDK package — the scope dir may be
233
+ // shared with other OpenCode plugins/tools.
234
+ removeIfExists(runtimeSdkPluginDir);
235
+ removeIfExists(versionFile);
236
+ if (removeGlobalPlugin()) {
237
+ console.log(` ${c.updated("Removed:")} ${c.file(getGlobalPluginDir())}`);
107
238
  }
108
- // --- install ---
239
+ console.log(` ${c.updated("Removed:")} ${c.file(runtimePluginDir)}`);
240
+ console.log(` ${c.updated("Removed:")} ${c.file(runtimeSdkPluginDir)}`);
241
+ const uninstallPm = bestAvailablePackageManager() ?? "npm";
242
+ console.log(`\n ${c.success("Done.")} Run ${c.file(globalUninstallCommand(uninstallPm, PLUGIN_NAME))} to remove the global package.\n`);
243
+ return;
244
+ }
245
+ // --- install runtime ---
246
+ if (options.skipRuntime) {
247
+ console.log(`\n ${c.exists("Skipped:")} runtime install (--skip-runtime)`);
248
+ }
249
+ else {
109
250
  console.log(`\n${c.heading("Setting up OpenCodeRAG runtime...")}\n`);
110
- // Check if already installed and up-to-date
111
251
  const installedVersion = readVersionFile(versionFile);
112
252
  const runtimeDist = path.join(runtimePluginDir, "dist");
113
253
  const alreadyInstalled = existsSync(runtimeDist);
@@ -128,31 +268,152 @@ export function registerSetupCommand(program) {
128
268
  console.error(` ${c.error("✗")} ${err}`);
129
269
  }
130
270
  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")}`);
271
+ process.exitCode = 1;
272
+ return;
273
+ }
274
+ }
275
+ // --- global plugin (default) ---
276
+ let pluginMode = options.workspacePlugin ? "workspace" : "global";
277
+ if (pluginMode === "global") {
278
+ try {
279
+ const installed = installGlobalPlugin({ force: options.force });
280
+ const label = installed.written.length > 0 ? c.created("Installed:") : c.exists("Exists:");
281
+ console.log(`\n ${label} global plugin at ${c.file(installed.dir)}`);
282
+ }
283
+ catch (err) {
284
+ console.log(`\n ${c.warn("Global plugin install skipped:")} ${err.message}`);
285
+ console.log(` ${c.dim("Falling back to the workspace-local plugin layout.")}`);
286
+ pluginMode = "workspace";
287
+ }
288
+ }
289
+ // --- workspace ---
290
+ const cwd = process.cwd();
291
+ const prompter = createPrompter(!options.yes);
292
+ try {
293
+ if (!isLikelyProjectRoot(cwd)) {
294
+ console.log(`\n${c.heading("Workspace")}`);
295
+ console.log(` ${c.dim("This directory does not look like a project root.")}`);
296
+ const proceed = prompter.interactive
297
+ ? await prompter.confirm({ message: "Initialize it as an OpenCodeRAG workspace anyway?", defaultValue: false })
298
+ : false;
299
+ if (!proceed) {
300
+ console.log(` ${c.warn("Skipped workspace setup.")} Run setup inside a project directory.\n`);
301
+ return;
302
+ }
303
+ }
304
+ migrateLegacyProjectConfig(cwd);
305
+ const configPath = findConfigFile(cwd) ?? projectConfigPath(cwd);
306
+ const configLabel = path.relative(cwd, configPath).replace(/\\/g, "/");
307
+ const existing = loadWorkspaceRawConfig(cwd);
308
+ const configured = hasConfiguredEmbedding(existing);
309
+ const explicitFlags = hasExplicitSetupFlags(options);
310
+ const existingEmbedding = existing.embedding;
311
+ const configProxy = existingEmbedding && typeof existingEmbedding === "object" && !Array.isArray(existingEmbedding)
312
+ ? existingEmbedding.proxy
313
+ : undefined;
314
+ let answers;
315
+ if (prompter.interactive && (options.reconfigure || !configured)) {
316
+ answers = await runSetupWizard({
317
+ ...options,
318
+ prompter,
319
+ existing,
320
+ proxy: configProxy,
321
+ });
322
+ if (answers === undefined) {
323
+ console.log(`\n ${c.warn("Setup cancelled.")} No configuration was changed.\n`);
324
+ return;
325
+ }
326
+ }
327
+ else if (explicitFlags) {
328
+ answers = answersFromFlags(options, existing);
329
+ }
330
+ if (answers) {
331
+ // A wizard/flag run still needs the baseline template (indexing tuning,
332
+ // chunking, retrieval defaults) before the sparse patch is merged in.
333
+ if (!existsSync(configPath)) {
334
+ await writeDefaultWorkspaceConfig(configPath, configLabel);
335
+ }
336
+ const patch = buildConfigPatch(answers);
337
+ const globalPath = globalConfigPath();
338
+ if (!writeConfigPatch(globalPath, patch.global)) {
339
+ console.log(` ${c.warn("Could not write the global config.")} Check permissions for ${c.file(globalPath)}.`);
340
+ }
341
+ else {
342
+ console.log(`\n ${c.updated("Updated:")} ${c.file(globalPath)} ${c.dim("(provider/model settings)")}`);
343
+ }
344
+ // Strip stale provider keys that the old `init` template wrote into the
345
+ // workspace file: the global layer is a base layer, so those copies
346
+ // would shadow the models just chosen.
347
+ const workspaceRaw = readJsonObjectSafe(configPath);
348
+ const shadowing = findShadowingProviderKeys(workspaceRaw);
349
+ if (shadowing.length > 0) {
350
+ const remove = prompter.interactive
351
+ ? await prompter.confirm({
352
+ message: `Remove ${shadowing.length} stale provider setting(s) from ${configLabel}? They would override the global config.`,
353
+ defaultValue: true,
354
+ })
355
+ : true;
356
+ if (remove) {
357
+ removeConfigPaths(workspaceRaw, shadowing);
358
+ writeFileSync(`${configPath}.bak`, readFileSync(configPath, "utf-8"), "utf-8");
359
+ writeFileSync(configPath, `${JSON.stringify(workspaceRaw, null, 2)}\n`, "utf-8");
360
+ console.log(` ${c.updated("Cleaned:")} ${c.file(configLabel)} ${c.dim("(provider keys moved to the global config)")}`);
361
+ }
362
+ }
363
+ if (!writeConfigPatch(configPath, patch.workspace)) {
364
+ console.log(` ${c.warn("Could not write the workspace config.")} Check permissions for ${c.file(configPath)}.`);
140
365
  }
141
366
  else {
142
- await runWorkspaceInit({});
367
+ console.log(` ${c.updated("Updated:")} ${c.file(configLabel)} ${c.dim("(feature toggles)")}`);
143
368
  }
144
369
  }
370
+ else if (!existsSync(configPath)) {
371
+ // Non-interactive first run without flags: write the default template.
372
+ await writeDefaultWorkspaceConfig(configPath, configLabel);
373
+ }
145
374
  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
- });
375
+ console.log(`\n ${c.exists("Using:")} ${c.file(configLabel)} ${c.dim("(run setup --reconfigure to change providers)")}`);
376
+ }
377
+ await scaffoldWorkspace({
378
+ force: options.force,
379
+ skipInstall: options.skipInstall,
380
+ configPath,
381
+ workspacePlugin: pluginMode === "workspace",
382
+ });
383
+ if (!options.skipHealthCheck) {
384
+ const health = await runWorkspaceHealthCheck(cwd, prompter, { autoPull: answers?.recommended === true });
385
+ await offerHealthRepairs({
386
+ cwd,
387
+ workspaceConfigPath: configPath,
388
+ globalConfigPath: globalConfigPath(),
389
+ prompter,
390
+ results: health,
391
+ ...(configProxy ? { proxy: configProxy } : {}),
392
+ });
393
+ }
394
+ if (options.index !== false && prompter.interactive) {
395
+ const buildIndex = await prompter.confirm({
396
+ message: "Build the search index now? (can take a few minutes)",
397
+ defaultValue: true,
398
+ });
399
+ if (buildIndex)
400
+ buildIndexNow();
401
+ }
402
+ }
403
+ catch (err) {
404
+ console.error(`\n ${c.error("Setup failed:")} ${err.message}`);
405
+ process.exitCode = 1;
406
+ }
407
+ finally {
408
+ prompter.close();
409
+ destroyAllPooledConnections();
410
+ }
411
+ console.log(`\n${c.success("Setup complete.")}`);
412
+ console.log(`\n ${c.dim("Next steps:")}`);
413
+ console.log(` ${c.dim(" 1. Restart OpenCode if it is running")}`);
414
+ console.log(` ${c.dim(" 2. Run `opencode-rag index` to build the search index")}`);
415
+ checkOpenCodeRunning();
416
+ console.log();
156
417
  }
157
418
  /**
158
419
  * Self-update: when this OpenCodeRAG build is outdated compared to the latest
@@ -181,9 +442,11 @@ async function ensureUpToDate() {
181
442
  if (!updated.success) {
182
443
  console.error(` ${c.error("✗-")} ${updated.message}`);
183
444
  console.error(` ${c.dim("You can retry later with `opencode-rag update`.\n")}`);
184
- process.exit(1);
445
+ process.exitCode = 1;
446
+ }
447
+ else {
448
+ console.log(` ${c.success("✓")} ${updated.message}`);
185
449
  }
186
- console.log(` ${c.success("✓")} ${updated.message}`);
187
450
  }
188
451
  /**
189
452
  * Query the npm registry for the latest published version of the plugin.
@@ -195,14 +458,10 @@ async function ensureUpToDate() {
195
458
  *
196
459
  * Best-effort: returns `null` when every endpoint lookup fails (offline,
197
460
  * mirror without the endpoint, malformed response).
198
- *
199
- * @returns The latest version string, or `null` on failure.
200
461
  */
201
462
  async function getLatestNpmVersion() {
202
463
  const registry = (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
203
464
  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
465
  const urls = [
207
466
  `${registry}/-/package/${pkgPath}/dist-tags`,
208
467
  `${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;