opencode-rag-plugin 2.1.0 → 2.2.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.
package/ReadMe.md CHANGED
@@ -14,9 +14,9 @@ You don't need a dedicated GPU to run smaller embedding LLMs, as these models ca
14
14
  # 1. Install globally (automatically sets up the OpenCode runtime)
15
15
  npm install -g opencode-rag-plugin
16
16
 
17
- # 2. Initialize in your project
17
+ # 2. One command per workspace - runtime check + workspace setup
18
18
  cd /path/to/your/project
19
- opencode-rag init
19
+ opencode-rag setup
20
20
 
21
21
  # 3. Index your workspace
22
22
  opencode-rag index
@@ -25,6 +25,13 @@ opencode-rag index
25
25
  opencode-rag query "authentication middleware"
26
26
  ```
27
27
 
28
+ `opencode-rag setup` installs/verifies the machine-level runtime and, when
29
+ run inside a project, initializes the workspace (`.opencode/`, plugin entries,
30
+ skill file, `opencode-rag.json`) in one step. When the plugin is not installed
31
+ globally yet, it fetches the latest published version from npm automatically.
32
+ `opencode-rag init` remains available for re-syncing an already initialized
33
+ workspace, and `opencode-rag update` upgrades to a newer release.
34
+
28
35
  **Prerequisites:** Node.js v22+, [Ollama](https://ollama.ai) (default) or other LLM-hosters (OpenAI-, Google- or Anthropic-compatible).
29
36
 
30
37
  > **Contributors / developers:** Clone the repo and use `npm install --legacy-peer-deps; npm run build` — see [Development docs](doc/development.md).
@@ -10,6 +10,7 @@
10
10
  * installation.
11
11
  */
12
12
  import type { Command } from "commander";
13
+ import type { InitOptions } from "../types.js";
13
14
  /**
14
15
  * Register the `init` command on the given Commander program.
15
16
  *
@@ -20,3 +21,31 @@ import type { Command } from "commander";
20
21
  * @param program - The Commander `Command` instance to register on.
21
22
  */
22
23
  export declare function registerInitCommand(program: Command): void;
24
+ /**
25
+ * Run the full workspace initialization: `.opencode/` directory structure,
26
+ * plugin entry files, `opencode-rag.json`, skill file, AGENTS.md guidance,
27
+ * provider health checks, and plugin linking from the global runtime cache.
28
+ *
29
+ * Shared between the `init` command and the automatic workspace step of
30
+ * `opencode-rag setup`.
31
+ *
32
+ * @param options - init options (force, skipInstall, skipHealthCheck).
33
+ */
34
+ export declare function runWorkspaceInit(options?: InitOptions): Promise<void>;
35
+ /**
36
+ * Best-effort check whether `cwd` looks like a project root (git repo or
37
+ * common project manifest files). `opencode-rag setup` uses this to decide
38
+ * whether to automatically initialize the current workspace.
39
+ *
40
+ * @param cwd - Directory to inspect.
41
+ * @returns Whether the directory looks like a project root.
42
+ */
43
+ export declare function isLikelyProjectRoot(cwd: string): boolean;
44
+ /**
45
+ * Check whether the workspace at `cwd` has already been initialized with
46
+ * OpenCodeRAG (plugin entry files and the TUI plugin config are present).
47
+ *
48
+ * @param cwd - Directory to inspect.
49
+ * @returns Whether the workspace looks initialized.
50
+ */
51
+ export declare function isWorkspaceInitialized(cwd: string): boolean;
@@ -37,315 +37,360 @@ export function registerInitCommand(program) {
37
37
  " Ollama backend (GPU vs CPU).\n" +
38
38
  " - Re-running in an existing workspace: re-syncs plugin/skill files and keeps the\n" +
39
39
  " existing opencode-rag.json (overwriting requires interactive confirmation).\n" +
40
- "\nWorkspace-level step — run AFTER 'opencode-rag setup' on this machine, then 'opencode-rag index'.\n")
40
+ "\nUsually run automatically by 'opencode-rag setup'; run manually to re-sync an existing workspace.\n")
41
41
  .option("-f, --force", "overwrite existing files")
42
42
  .option("--skip-install", "skip installing workspace-local plugin dependencies")
43
43
  .option("--skip-health-check", "skip provider connectivity and model availability check")
44
- .action(async (options) => {
44
+ .action((options) => runWorkspaceInit(options));
45
+ }
46
+ /**
47
+ * Run the full workspace initialization: `.opencode/` directory structure,
48
+ * plugin entry files, `opencode-rag.json`, skill file, AGENTS.md guidance,
49
+ * provider health checks, and plugin linking from the global runtime cache.
50
+ *
51
+ * Shared between the `init` command and the automatic workspace step of
52
+ * `opencode-rag setup`.
53
+ *
54
+ * @param options - init options (force, skipInstall, skipHealthCheck).
55
+ */
56
+ export async function runWorkspaceInit(options = {}) {
57
+ try {
58
+ const cwd = process.cwd();
59
+ const packageMetadata = getPackageMetadata();
60
+ // Use findConfigFile so an existing config in .opencode/rag.json (or
61
+ // .opencode/opencode-rag.json) is respected instead of being shadowed
62
+ // by a new root-level opencode-rag.json.
63
+ const configPath = findConfigFile(cwd) ?? path.join(cwd, "opencode-rag.json");
64
+ const opencodeDir = path.join(cwd, ".opencode");
65
+ const gitignorePath = path.join(opencodeDir, ".gitignore");
66
+ const opencodeConfigPath = path.join(opencodeDir, "opencode.json");
67
+ const pluginsDir = path.join(opencodeDir, "plugins");
68
+ const pluginEntryPath = path.join(pluginsDir, "rag-plugin.js");
69
+ const tuiPluginEntryPath = path.join(pluginsDir, "rag-tui.js");
70
+ const tuiConfigPath = path.join(opencodeDir, "tui.json");
71
+ const opencodePackagePath = path.join(opencodeDir, "package.json");
72
+ console.log(`\n${c.heading("Initializing OpenCodeRAG in workspace...")}\n`);
73
+ if (!existsSync(opencodeDir)) {
74
+ mkdirSync(opencodeDir, { recursive: true });
75
+ console.log(` ${c.created("Created:")} .opencode/`);
76
+ }
77
+ else {
78
+ console.log(` ${c.exists("Exists:")} .opencode/`);
79
+ }
80
+ // Wiki safety: warn if wiki exists but would be affected (currently init never touches it)
81
+ const wikiDir = path.join(opencodeDir, "wiki");
82
+ if (existsSync(wikiDir)) {
83
+ console.log(` ${c.exists("Preserved:")} .opencode/wiki/ (never modified by init)`);
84
+ }
85
+ if (!existsSync(pluginsDir)) {
86
+ mkdirSync(pluginsDir, { recursive: true });
87
+ console.log(` ${c.created("Created:")} .opencode/plugins/`);
88
+ }
89
+ else {
90
+ console.log(` ${c.exists("Exists:")} .opencode/plugins/`);
91
+ }
92
+ const gitignoreExists = existsSync(gitignorePath);
93
+ const nextGitignoreContent = mergeGitignoreContent(gitignoreExists ? readFileSync(gitignorePath, "utf-8") : undefined);
94
+ if (!gitignoreExists || options.force || readFileSync(gitignorePath, "utf-8") !== nextGitignoreContent) {
95
+ writeFileSync(gitignorePath, nextGitignoreContent, "utf-8");
96
+ console.log(` ${gitignoreExists ? c.updated("Updated:") : c.created("Created:")} .opencode/.gitignore`);
97
+ }
98
+ else {
99
+ console.log(` ${c.exists("Exists:")} .opencode/.gitignore`);
100
+ }
101
+ const opencodeConfigExists = existsSync(opencodeConfigPath);
102
+ const nextOpencodeConfig = buildOpencodeConfig(readJsonObject(opencodeConfigPath));
103
+ if (!opencodeConfigExists || options.force) {
104
+ writeJsonFile(opencodeConfigPath, nextOpencodeConfig);
105
+ console.log(` ${opencodeConfigExists ? c.updated("Updated:") : c.created("Created:")} .opencode/opencode.json`);
106
+ }
107
+ else if (JSON.stringify(readJsonObject(opencodeConfigPath)) !== JSON.stringify(nextOpencodeConfig)) {
108
+ writeJsonFile(opencodeConfigPath, nextOpencodeConfig);
109
+ console.log(` ${c.updated("Updated:")} .opencode/opencode.json`);
110
+ }
111
+ else {
112
+ console.log(` ${c.exists("Exists:")} .opencode/opencode.json`);
113
+ }
114
+ const pluginEntryExists = existsSync(pluginEntryPath);
115
+ const pluginEntryContent = generateWorkspacePluginFile(packageMetadata.name);
116
+ if (!pluginEntryExists || options.force) {
117
+ writeFileSync(pluginEntryPath, pluginEntryContent, "utf-8");
118
+ console.log(` ${pluginEntryExists ? c.updated("Updated:") : c.created("Created:")} .opencode/plugins/rag-plugin.js`);
119
+ }
120
+ else if (readFileSync(pluginEntryPath, "utf-8") !== pluginEntryContent) {
121
+ writeFileSync(pluginEntryPath, pluginEntryContent, "utf-8");
122
+ console.log(` ${c.updated("Updated:")} .opencode/plugins/rag-plugin.js`);
123
+ }
124
+ else {
125
+ console.log(` ${c.exists("Exists:")} .opencode/plugins/rag-plugin.js`);
126
+ }
127
+ const tuiPluginEntryExists = existsSync(tuiPluginEntryPath);
128
+ const tuiPluginEntryContent = generateWorkspaceTuiPluginFile(packageMetadata.name);
129
+ if (!tuiPluginEntryExists || options.force) {
130
+ writeFileSync(tuiPluginEntryPath, tuiPluginEntryContent, "utf-8");
131
+ console.log(` ${tuiPluginEntryExists ? c.updated("Updated:") : c.created("Created:")} .opencode/plugins/rag-tui.js`);
132
+ }
133
+ else if (readFileSync(tuiPluginEntryPath, "utf-8") !== tuiPluginEntryContent) {
134
+ writeFileSync(tuiPluginEntryPath, tuiPluginEntryContent, "utf-8");
135
+ console.log(` ${c.updated("Updated:")} .opencode/plugins/rag-tui.js`);
136
+ }
137
+ else {
138
+ console.log(` ${c.exists("Exists:")} .opencode/plugins/rag-tui.js`);
139
+ }
140
+ const tuiConfigExists = existsSync(tuiConfigPath);
141
+ const nextTuiConfig = { plugin: ["./plugins/rag-tui.js"] };
142
+ if (!tuiConfigExists || options.force) {
143
+ writeJsonFile(tuiConfigPath, nextTuiConfig);
144
+ console.log(` ${tuiConfigExists ? c.updated("Updated:") : c.created("Created:")} .opencode/tui.json`);
145
+ }
146
+ else if (JSON.stringify(readJsonObject(tuiConfigPath)) !== JSON.stringify(nextTuiConfig)) {
147
+ writeJsonFile(tuiConfigPath, nextTuiConfig);
148
+ console.log(` ${c.updated("Updated:")} .opencode/tui.json`);
149
+ }
150
+ else {
151
+ console.log(` ${c.exists("Exists:")} .opencode/tui.json`);
152
+ }
153
+ const skillsDir = path.join(opencodeDir, "skills");
154
+ const skillDir = path.join(skillsDir, "opencode-rag");
155
+ const skillPath = path.join(skillDir, "SKILL.md");
156
+ if (!existsSync(skillDir)) {
157
+ mkdirSync(skillDir, { recursive: true });
158
+ console.log(` ${c.created("Created:")} .opencode/skills/opencode-rag/`);
159
+ }
160
+ const skillContent = generateSkillFile();
161
+ const skillExists = existsSync(skillPath);
162
+ if (!skillExists || options.force) {
163
+ writeFileSync(skillPath, skillContent, "utf-8");
164
+ console.log(` ${skillExists ? c.updated("Updated:") : c.created("Created:")} .opencode/skills/opencode-rag/SKILL.md`);
165
+ }
166
+ else if (readFileSync(skillPath, "utf-8") !== skillContent) {
167
+ writeFileSync(skillPath, skillContent, "utf-8");
168
+ console.log(` ${c.updated("Updated:")} .opencode/skills/opencode-rag/SKILL.md`);
169
+ }
170
+ else {
171
+ console.log(` ${c.exists("Exists:")} .opencode/skills/opencode-rag/SKILL.md`);
172
+ }
173
+ const agentsMdPath = path.join(cwd, "AGENTS.md");
174
+ const agentsMdExists = existsSync(agentsMdPath);
175
+ // Read effective promptEnforcement from existing config (if present)
176
+ let promptEnforcement = true;
45
177
  try {
46
- const cwd = process.cwd();
47
- const packageMetadata = getPackageMetadata();
48
- // Use findConfigFile so an existing config in .opencode/rag.json (or
49
- // .opencode/opencode-rag.json) is respected instead of being shadowed
50
- // by a new root-level opencode-rag.json.
51
- const configPath = findConfigFile(cwd) ?? path.join(cwd, "opencode-rag.json");
52
- const opencodeDir = path.join(cwd, ".opencode");
53
- const gitignorePath = path.join(opencodeDir, ".gitignore");
54
- const opencodeConfigPath = path.join(opencodeDir, "opencode.json");
55
- const pluginsDir = path.join(opencodeDir, "plugins");
56
- const pluginEntryPath = path.join(pluginsDir, "rag-plugin.js");
57
- const tuiPluginEntryPath = path.join(pluginsDir, "rag-tui.js");
58
- const tuiConfigPath = path.join(opencodeDir, "tui.json");
59
- const opencodePackagePath = path.join(opencodeDir, "package.json");
60
- console.log(`\n${c.heading("Initializing OpenCodeRAG in workspace...")}\n`);
61
- if (!existsSync(opencodeDir)) {
62
- mkdirSync(opencodeDir, { recursive: true });
63
- console.log(` ${c.created("Created:")} .opencode/`);
64
- }
65
- else {
66
- console.log(` ${c.exists("Exists:")} .opencode/`);
67
- }
68
- // Wiki safety: warn if wiki exists but would be affected (currently init never touches it)
69
- const wikiDir = path.join(opencodeDir, "wiki");
70
- if (existsSync(wikiDir)) {
71
- console.log(` ${c.exists("Preserved:")} .opencode/wiki/ (never modified by init)`);
72
- }
73
- if (!existsSync(pluginsDir)) {
74
- mkdirSync(pluginsDir, { recursive: true });
75
- console.log(` ${c.created("Created:")} .opencode/plugins/`);
76
- }
77
- else {
78
- console.log(` ${c.exists("Exists:")} .opencode/plugins/`);
79
- }
80
- const gitignoreExists = existsSync(gitignorePath);
81
- const nextGitignoreContent = mergeGitignoreContent(gitignoreExists ? readFileSync(gitignorePath, "utf-8") : undefined);
82
- if (!gitignoreExists || options.force || readFileSync(gitignorePath, "utf-8") !== nextGitignoreContent) {
83
- writeFileSync(gitignorePath, nextGitignoreContent, "utf-8");
84
- console.log(` ${gitignoreExists ? c.updated("Updated:") : c.created("Created:")} .opencode/.gitignore`);
85
- }
86
- else {
87
- console.log(` ${c.exists("Exists:")} .opencode/.gitignore`);
88
- }
89
- const opencodeConfigExists = existsSync(opencodeConfigPath);
90
- const nextOpencodeConfig = buildOpencodeConfig(readJsonObject(opencodeConfigPath));
91
- if (!opencodeConfigExists || options.force) {
92
- writeJsonFile(opencodeConfigPath, nextOpencodeConfig);
93
- console.log(` ${opencodeConfigExists ? c.updated("Updated:") : c.created("Created:")} .opencode/opencode.json`);
94
- }
95
- else if (JSON.stringify(readJsonObject(opencodeConfigPath)) !== JSON.stringify(nextOpencodeConfig)) {
96
- writeJsonFile(opencodeConfigPath, nextOpencodeConfig);
97
- console.log(` ${c.updated("Updated:")} .opencode/opencode.json`);
98
- }
99
- else {
100
- console.log(` ${c.exists("Exists:")} .opencode/opencode.json`);
101
- }
102
- const pluginEntryExists = existsSync(pluginEntryPath);
103
- const pluginEntryContent = generateWorkspacePluginFile(packageMetadata.name);
104
- if (!pluginEntryExists || options.force) {
105
- writeFileSync(pluginEntryPath, pluginEntryContent, "utf-8");
106
- console.log(` ${pluginEntryExists ? c.updated("Updated:") : c.created("Created:")} .opencode/plugins/rag-plugin.js`);
107
- }
108
- else if (readFileSync(pluginEntryPath, "utf-8") !== pluginEntryContent) {
109
- writeFileSync(pluginEntryPath, pluginEntryContent, "utf-8");
110
- console.log(` ${c.updated("Updated:")} .opencode/plugins/rag-plugin.js`);
111
- }
112
- else {
113
- console.log(` ${c.exists("Exists:")} .opencode/plugins/rag-plugin.js`);
114
- }
115
- const tuiPluginEntryExists = existsSync(tuiPluginEntryPath);
116
- const tuiPluginEntryContent = generateWorkspaceTuiPluginFile(packageMetadata.name);
117
- if (!tuiPluginEntryExists || options.force) {
118
- writeFileSync(tuiPluginEntryPath, tuiPluginEntryContent, "utf-8");
119
- console.log(` ${tuiPluginEntryExists ? c.updated("Updated:") : c.created("Created:")} .opencode/plugins/rag-tui.js`);
120
- }
121
- else if (readFileSync(tuiPluginEntryPath, "utf-8") !== tuiPluginEntryContent) {
122
- writeFileSync(tuiPluginEntryPath, tuiPluginEntryContent, "utf-8");
123
- console.log(` ${c.updated("Updated:")} .opencode/plugins/rag-tui.js`);
124
- }
125
- else {
126
- console.log(` ${c.exists("Exists:")} .opencode/plugins/rag-tui.js`);
127
- }
128
- const tuiConfigExists = existsSync(tuiConfigPath);
129
- const nextTuiConfig = { plugin: ["./plugins/rag-tui.js"] };
130
- if (!tuiConfigExists || options.force) {
131
- writeJsonFile(tuiConfigPath, nextTuiConfig);
132
- console.log(` ${tuiConfigExists ? c.updated("Updated:") : c.created("Created:")} .opencode/tui.json`);
133
- }
134
- else if (JSON.stringify(readJsonObject(tuiConfigPath)) !== JSON.stringify(nextTuiConfig)) {
135
- writeJsonFile(tuiConfigPath, nextTuiConfig);
136
- console.log(` ${c.updated("Updated:")} .opencode/tui.json`);
137
- }
138
- else {
139
- console.log(` ${c.exists("Exists:")} .opencode/tui.json`);
140
- }
141
- const skillsDir = path.join(opencodeDir, "skills");
142
- const skillDir = path.join(skillsDir, "opencode-rag");
143
- const skillPath = path.join(skillDir, "SKILL.md");
144
- if (!existsSync(skillDir)) {
145
- mkdirSync(skillDir, { recursive: true });
146
- console.log(` ${c.created("Created:")} .opencode/skills/opencode-rag/`);
178
+ if (existsSync(configPath)) {
179
+ const existingCfg = loadConfig(configPath, false);
180
+ promptEnforcement = existingCfg.memory?.promptEnforcement ?? true;
147
181
  }
148
- const skillContent = generateSkillFile();
149
- const skillExists = existsSync(skillPath);
150
- if (!skillExists || options.force) {
151
- writeFileSync(skillPath, skillContent, "utf-8");
152
- console.log(` ${skillExists ? c.updated("Updated:") : c.created("Created:")} .opencode/skills/opencode-rag/SKILL.md`);
153
- }
154
- else if (readFileSync(skillPath, "utf-8") !== skillContent) {
155
- writeFileSync(skillPath, skillContent, "utf-8");
156
- console.log(` ${c.updated("Updated:")} .opencode/skills/opencode-rag/SKILL.md`);
157
- }
158
- else {
159
- console.log(` ${c.exists("Exists:")} .opencode/skills/opencode-rag/SKILL.md`);
160
- }
161
- const agentsMdPath = path.join(cwd, "AGENTS.md");
162
- const agentsMdExists = existsSync(agentsMdPath);
163
- // Read effective promptEnforcement from existing config (if present)
164
- let promptEnforcement = true;
165
- try {
166
- if (existsSync(configPath)) {
167
- const existingCfg = loadConfig(configPath, false);
168
- promptEnforcement = existingCfg.memory?.promptEnforcement ?? true;
182
+ }
183
+ catch {
184
+ // Malformed or missing config — use default
185
+ }
186
+ const nextAgentsMd = mergeAgentsMdContent(agentsMdExists ? readFileSync(agentsMdPath, "utf-8") : undefined, { promptEnforcement });
187
+ if (!agentsMdExists || options.force) {
188
+ writeFileSync(agentsMdPath, nextAgentsMd, "utf-8");
189
+ console.log(` ${agentsMdExists ? c.updated("Updated:") : c.created("Created:")} AGENTS.md`);
190
+ }
191
+ else if (readFileSync(agentsMdPath, "utf-8") !== nextAgentsMd) {
192
+ writeFileSync(agentsMdPath, nextAgentsMd, "utf-8");
193
+ console.log(` ${c.updated("Updated:")} AGENTS.md`);
194
+ }
195
+ else {
196
+ console.log(` ${c.exists("Exists:")} AGENTS.md`);
197
+ }
198
+ const workspacePackageExists = existsSync(opencodePackagePath);
199
+ const nextWorkspacePackage = buildWorkspacePackageJson(readJsonObject(opencodePackagePath), packageMetadata);
200
+ if (!workspacePackageExists || options.force) {
201
+ writeJsonFile(opencodePackagePath, nextWorkspacePackage);
202
+ console.log(` ${workspacePackageExists ? c.updated("Updated:") : c.created("Created:")} .opencode/package.json`);
203
+ }
204
+ else if (JSON.stringify(readJsonObject(opencodePackagePath)) !== JSON.stringify(nextWorkspacePackage)) {
205
+ writeJsonFile(opencodePackagePath, nextWorkspacePackage);
206
+ console.log(` ${c.updated("Updated:")} .opencode/package.json`);
207
+ }
208
+ else {
209
+ console.log(` ${c.exists("Exists:")} .opencode/package.json`);
210
+ }
211
+ const configExists = existsSync(configPath);
212
+ // Detect the Ollama backend (CPU vs GPU) lazily — only when we are
213
+ // actually about to write a config — and tune embedding batches for it.
214
+ let detectedTuning;
215
+ const configContent = async () => {
216
+ if (!detectedTuning) {
217
+ try {
218
+ const info = await detectOllamaBackend();
219
+ detectedTuning = info.tuning;
220
+ const icon = info.backend === "gpu" ? c.success("GPU:") :
221
+ info.backend === "cpu" ? c.warn("CPU:") :
222
+ c.dim("Backend:");
223
+ console.log(` ${icon} ${info.message}`);
224
+ }
225
+ catch {
226
+ detectedTuning = undefined;
169
227
  }
170
228
  }
171
- catch {
172
- // Malformed or missing config — use default
173
- }
174
- const nextAgentsMd = mergeAgentsMdContent(agentsMdExists ? readFileSync(agentsMdPath, "utf-8") : undefined, { promptEnforcement });
175
- if (!agentsMdExists || options.force) {
176
- writeFileSync(agentsMdPath, nextAgentsMd, "utf-8");
177
- console.log(` ${agentsMdExists ? c.updated("Updated:") : c.created("Created:")} AGENTS.md`);
178
- }
179
- else if (readFileSync(agentsMdPath, "utf-8") !== nextAgentsMd) {
180
- writeFileSync(agentsMdPath, nextAgentsMd, "utf-8");
181
- console.log(` ${c.updated("Updated:")} AGENTS.md`);
182
- }
183
- else {
184
- console.log(` ${c.exists("Exists:")} AGENTS.md`);
185
- }
186
- const workspacePackageExists = existsSync(opencodePackagePath);
187
- const nextWorkspacePackage = buildWorkspacePackageJson(readJsonObject(opencodePackagePath), packageMetadata);
188
- if (!workspacePackageExists || options.force) {
189
- writeJsonFile(opencodePackagePath, nextWorkspacePackage);
190
- console.log(` ${workspacePackageExists ? c.updated("Updated:") : c.created("Created:")} .opencode/package.json`);
191
- }
192
- else if (JSON.stringify(readJsonObject(opencodePackagePath)) !== JSON.stringify(nextWorkspacePackage)) {
193
- writeJsonFile(opencodePackagePath, nextWorkspacePackage);
194
- console.log(` ${c.updated("Updated:")} .opencode/package.json`);
229
+ return generateDefaultConfigJson(detectedTuning);
230
+ };
231
+ if (!configExists) {
232
+ writeFileSync(configPath, await configContent(), "utf-8");
233
+ console.log(` ${c.created("Created:")} opencode-rag.json`);
234
+ }
235
+ else {
236
+ // NEVER overwrite existing config without interactive confirmation
237
+ let overwrite = false;
238
+ if (process.stdin.isTTY) {
239
+ const readline = await import("node:readline");
240
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
241
+ const answer = await new Promise((resolve) => {
242
+ rl.question(` ${c.warn("opencode-rag.json already exists.")} Overwrite with default config? A backup will be saved. (y/N) `, resolve);
243
+ });
244
+ rl.close();
245
+ overwrite = /^y(?:es)?$/i.test(answer.trim());
246
+ }
247
+ if (overwrite) {
248
+ copyFileSync(configPath, `${configPath}.bak`);
249
+ console.log(` ${c.dim("Backup:")} opencode-rag.json.bak`);
250
+ writeFileSync(configPath, await configContent(), "utf-8");
251
+ console.log(` ${c.updated("Updated:")} opencode-rag.json`);
195
252
  }
196
253
  else {
197
- console.log(` ${c.exists("Exists:")} .opencode/package.json`);
254
+ console.log(` ${c.exists("Exists:")} opencode-rag.json (preserved)`);
255
+ if (!process.stdin.isTTY && options.force) {
256
+ console.log(` ${c.warn("Skipped overwrite:")} non-interactive shell. Edit opencode-rag.json manually or re-run in a TTY.`);
257
+ }
198
258
  }
199
- const configExists = existsSync(configPath);
200
- // Detect the Ollama backend (CPU vs GPU) lazily — only when we are
201
- // actually about to write a config — and tune embedding batches for it.
202
- let detectedTuning;
203
- const configContent = async () => {
204
- if (!detectedTuning) {
205
- try {
206
- const info = await detectOllamaBackend();
207
- detectedTuning = info.tuning;
208
- const icon = info.backend === "gpu" ? c.success("GPU:") :
209
- info.backend === "cpu" ? c.warn("CPU:") :
210
- c.dim("Backend:");
211
- console.log(` ${icon} ${info.message}`);
259
+ }
260
+ // ── Provider health check + dependency install (parallel) ──
261
+ const healthPromise = options.skipHealthCheck
262
+ ? null
263
+ : (async () => {
264
+ console.log(`\n${c.heading("Checking provider connectivity...")}\n`);
265
+ const ragConfig = loadConfig(configPath);
266
+ return checkProviderHealth(ragConfig);
267
+ })();
268
+ const installPromise = options.skipInstall
269
+ ? null
270
+ : installPluginFromGlobal(opencodeDir, packageMetadata.name, false);
271
+ // Wait for health check results first
272
+ if (healthPromise) {
273
+ const results = await healthPromise;
274
+ for (const r of results) {
275
+ const icon = r.status === "ok" ? c.success("✓") : r.status === "missing" ? c.warn("○") : c.error("✗");
276
+ const typeLabel = r.type === "image_description" ? "image description" : r.type === "image_description_on_demand" ? "image description (on-demand)" : r.type;
277
+ const label = `${typeLabel} model`;
278
+ console.log(` ${icon} ${c.value(r.model)} (${r.provider}) — ${label}: ${r.status}`);
279
+ if (r.error)
280
+ console.log(` ${c.dim(r.error)}`);
281
+ }
282
+ const missingOllama = results.filter((r) => r.status === "missing" && r.provider === "ollama");
283
+ if (missingOllama.length > 0) {
284
+ const ragConfig = loadConfig(configPath);
285
+ const pullEntries = missingOllama.map((r) => {
286
+ if (r.type === "embedding") {
287
+ return { model: r.model, baseUrl: ragConfig.embedding.baseUrl, proxy: ragConfig.embedding.proxy };
212
288
  }
213
- catch {
214
- detectedTuning = undefined;
289
+ if (r.type === "description" && ragConfig.description) {
290
+ return { model: r.model, baseUrl: ragConfig.description.baseUrl, proxy: ragConfig.description.proxy };
215
291
  }
292
+ if (r.type === "image_description" && ragConfig.imageDescription) {
293
+ return { model: r.model, baseUrl: ragConfig.imageDescription.baseUrl, proxy: ragConfig.imageDescription.proxy };
294
+ }
295
+ if (r.type === "image_description_on_demand" && ragConfig.imageDescription) {
296
+ const onDemand = ragConfig.imageDescription.onDemand;
297
+ return {
298
+ model: r.model,
299
+ baseUrl: onDemand?.baseUrl ?? ragConfig.imageDescription.baseUrl,
300
+ proxy: onDemand?.proxy ?? ragConfig.imageDescription.proxy,
301
+ };
302
+ }
303
+ return { model: r.model, baseUrl: ragConfig.embedding.baseUrl, proxy: ragConfig.embedding.proxy };
304
+ });
305
+ console.log(`\n ${c.warn("Models not found:")} ${pullEntries.map((e) => e.model).join(", ")}`);
306
+ // Non-TTY guard: rl.question would block forever with a still-open
307
+ // stdin pipe (e.g. `echo y | opencode-rag init`, CI runners).
308
+ if (!process.stdin.isTTY) {
309
+ console.log(` ${c.dim("Non-interactive shell — skipping. Pull manually with: ollama pull <model>")}`);
216
310
  }
217
- return generateDefaultConfigJson(detectedTuning);
218
- };
219
- if (!configExists) {
220
- writeFileSync(configPath, await configContent(), "utf-8");
221
- console.log(` ${c.created("Created:")} opencode-rag.json`);
222
- }
223
- else {
224
- // NEVER overwrite existing config without interactive confirmation
225
- let overwrite = false;
226
- if (process.stdin.isTTY) {
311
+ else {
227
312
  const readline = await import("node:readline");
228
313
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
229
314
  const answer = await new Promise((resolve) => {
230
- rl.question(` ${c.warn("opencode-rag.json already exists.")} Overwrite with default config? A backup will be saved. (y/N) `, resolve);
315
+ rl.question(` Pull ${pullEntries.length === 1 ? "this model" : "these models"} now? (y/n) `, resolve);
231
316
  });
232
317
  rl.close();
233
- overwrite = /^y(?:es)?$/i.test(answer.trim());
234
- }
235
- if (overwrite) {
236
- copyFileSync(configPath, `${configPath}.bak`);
237
- console.log(` ${c.dim("Backup:")} opencode-rag.json.bak`);
238
- writeFileSync(configPath, await configContent(), "utf-8");
239
- console.log(` ${c.updated("Updated:")} opencode-rag.json`);
240
- }
241
- else {
242
- console.log(` ${c.exists("Exists:")} opencode-rag.json (preserved)`);
243
- if (!process.stdin.isTTY && options.force) {
244
- console.log(` ${c.warn("Skipped overwrite:")} non-interactive shell. Edit opencode-rag.json manually or re-run in a TTY.`);
245
- }
246
- }
247
- }
248
- // ── Provider health check + dependency install (parallel) ──
249
- const healthPromise = options.skipHealthCheck
250
- ? null
251
- : (async () => {
252
- console.log(`\n${c.heading("Checking provider connectivity...")}\n`);
253
- const ragConfig = loadConfig(configPath);
254
- return checkProviderHealth(ragConfig);
255
- })();
256
- const installPromise = options.skipInstall
257
- ? null
258
- : installPluginFromGlobal(opencodeDir, packageMetadata.name, false);
259
- // Wait for health check results first
260
- if (healthPromise) {
261
- const results = await healthPromise;
262
- for (const r of results) {
263
- const icon = r.status === "ok" ? c.success("✓") : r.status === "missing" ? c.warn("○") : c.error("✗");
264
- const typeLabel = r.type === "image_description" ? "image description" : r.type === "image_description_on_demand" ? "image description (on-demand)" : r.type;
265
- const label = `${typeLabel} model`;
266
- console.log(` ${icon} ${c.value(r.model)} (${r.provider}) — ${label}: ${r.status}`);
267
- if (r.error)
268
- console.log(` ${c.dim(r.error)}`);
269
- }
270
- const missingOllama = results.filter((r) => r.status === "missing" && r.provider === "ollama");
271
- if (missingOllama.length > 0) {
272
- const ragConfig = loadConfig(configPath);
273
- const pullEntries = missingOllama.map((r) => {
274
- if (r.type === "embedding") {
275
- return { model: r.model, baseUrl: ragConfig.embedding.baseUrl, proxy: ragConfig.embedding.proxy };
276
- }
277
- if (r.type === "description" && ragConfig.description) {
278
- return { model: r.model, baseUrl: ragConfig.description.baseUrl, proxy: ragConfig.description.proxy };
318
+ if (answer.toLowerCase() === "y" || answer.toLowerCase() === "yes") {
319
+ console.log();
320
+ try {
321
+ await pullOllamaModels(pullEntries, (model, line) => {
322
+ console.log(` ${c.value(model)}: ${line}`);
323
+ });
324
+ console.log(`\n ${c.success("Models pulled successfully.")}`);
279
325
  }
280
- if (r.type === "image_description" && ragConfig.imageDescription) {
281
- return { model: r.model, baseUrl: ragConfig.imageDescription.baseUrl, proxy: ragConfig.imageDescription.proxy };
326
+ catch (err) {
327
+ console.error(`\n ${c.error("Pull failed:")} ${err.message}`);
328
+ console.log(` ${c.dim("Pull manually with: ollama pull <model>")}`);
282
329
  }
283
- if (r.type === "image_description_on_demand" && ragConfig.imageDescription) {
284
- const onDemand = ragConfig.imageDescription.onDemand;
285
- return {
286
- model: r.model,
287
- baseUrl: onDemand?.baseUrl ?? ragConfig.imageDescription.baseUrl,
288
- proxy: onDemand?.proxy ?? ragConfig.imageDescription.proxy,
289
- };
290
- }
291
- return { model: r.model, baseUrl: ragConfig.embedding.baseUrl, proxy: ragConfig.embedding.proxy };
292
- });
293
- console.log(`\n ${c.warn("Models not found:")} ${pullEntries.map((e) => e.model).join(", ")}`);
294
- // Non-TTY guard: rl.question would block forever with a still-open
295
- // stdin pipe (e.g. `echo y | opencode-rag init`, CI runners).
296
- if (!process.stdin.isTTY) {
297
- console.log(` ${c.dim("Non-interactive shell — skipping. Pull manually with: ollama pull <model>")}`);
298
330
  }
299
331
  else {
300
- const readline = await import("node:readline");
301
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
302
- const answer = await new Promise((resolve) => {
303
- rl.question(` Pull ${pullEntries.length === 1 ? "this model" : "these models"} now? (y/n) `, resolve);
304
- });
305
- rl.close();
306
- if (answer.toLowerCase() === "y" || answer.toLowerCase() === "yes") {
307
- console.log();
308
- try {
309
- await pullOllamaModels(pullEntries, (model, line) => {
310
- console.log(` ${c.value(model)}: ${line}`);
311
- });
312
- console.log(`\n ${c.success("Models pulled successfully.")}`);
313
- }
314
- catch (err) {
315
- console.error(`\n ${c.error("Pull failed:")} ${err.message}`);
316
- console.log(` ${c.dim("Pull manually with: ollama pull <model>")}`);
317
- }
318
- }
319
- else {
320
- console.log(` ${c.dim("Skipped. Pull manually with: ollama pull <model>")}`);
321
- }
332
+ console.log(` ${c.dim("Skipped. Pull manually with: ollama pull <model>")}`);
322
333
  }
323
334
  }
324
- const hasErrors = results.some((r) => r.status === "error");
325
- if (hasErrors) {
326
- console.log(`\n ${c.warn("Some providers are not reachable.")} Check configuration and network, then run ${c.file("'opencode-rag index'")}.`);
327
- }
328
335
  }
329
- // Now install the plugin from global cache via junction
330
- if (installPromise) {
331
- console.log(`\n${c.heading("Installing workspace-local plugin...")}\n`);
332
- await installPromise;
333
- console.log(`\n ${c.success("Installed:")} .opencode/node_modules/`);
334
- console.log(` ${c.dim("Plugin is linked to global runtime cache; no npm install was required.")}`);
336
+ const hasErrors = results.some((r) => r.status === "error");
337
+ if (hasErrors) {
338
+ console.log(`\n ${c.warn("Some providers are not reachable.")} Check configuration and network, then run ${c.file("'opencode-rag index'")}.`);
335
339
  }
336
- else {
337
- console.log(`\n ${c.exists("Skipped:")} plugin installation (--skip-install)`);
338
- }
339
- console.log(`\n${c.success("Done.")} Restart OpenCode if it is running, then run ${c.file("'opencode-rag index'")} in this workspace.`);
340
340
  }
341
- catch (err) {
342
- console.error(`\n ${c.error("Init failed:")} ${err.message}`);
343
- console.error(` ${c.dim("Fix the issue above, then run 'opencode-rag init' again.")}`);
344
- process.exitCode = 1;
341
+ // Now install the plugin from global cache via junction
342
+ if (installPromise) {
343
+ console.log(`\n${c.heading("Installing workspace-local plugin...")}\n`);
344
+ await installPromise;
345
+ console.log(`\n ${c.success("Installed:")} .opencode/node_modules/`);
346
+ console.log(` ${c.dim("Plugin is linked to global runtime cache; no npm install was required.")}`);
345
347
  }
346
- finally {
347
- destroyAllPooledConnections();
348
+ else {
349
+ console.log(`\n ${c.exists("Skipped:")} plugin installation (--skip-install)`);
348
350
  }
349
- });
351
+ console.log(`\n${c.success("Done.")} Restart OpenCode if it is running, then run ${c.file("'opencode-rag index'")} in this workspace.`);
352
+ }
353
+ catch (err) {
354
+ console.error(`\n ${c.error("Init failed:")} ${err.message}`);
355
+ console.error(` ${c.dim("Fix the issue above, then run 'opencode-rag init' again.")}`);
356
+ process.exitCode = 1;
357
+ }
358
+ finally {
359
+ destroyAllPooledConnections();
360
+ }
361
+ }
362
+ /**
363
+ * Best-effort check whether `cwd` looks like a project root (git repo or
364
+ * common project manifest files). `opencode-rag setup` uses this to decide
365
+ * whether to automatically initialize the current workspace.
366
+ *
367
+ * @param cwd - Directory to inspect.
368
+ * @returns Whether the directory looks like a project root.
369
+ */
370
+ export function isLikelyProjectRoot(cwd) {
371
+ if (existsSync(path.join(cwd, ".git"))) {
372
+ return true;
373
+ }
374
+ const markers = [
375
+ "package.json",
376
+ "AGENTS.md",
377
+ "README.md",
378
+ "pyproject.toml",
379
+ "Cargo.toml",
380
+ "go.mod",
381
+ "opencode-rag.json",
382
+ ];
383
+ return markers.some((marker) => existsSync(path.join(cwd, marker)));
384
+ }
385
+ /**
386
+ * Check whether the workspace at `cwd` has already been initialized with
387
+ * OpenCodeRAG (plugin entry files and the TUI plugin config are present).
388
+ *
389
+ * @param cwd - Directory to inspect.
390
+ * @returns Whether the workspace looks initialized.
391
+ */
392
+ export function isWorkspaceInitialized(cwd) {
393
+ return (existsSync(path.join(cwd, ".opencode", "plugins", "rag-plugin.js")) &&
394
+ existsSync(path.join(cwd, ".opencode", "tui.json")));
350
395
  }
351
396
  //# sourceMappingURL=init.js.map
@@ -4,6 +4,8 @@ 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
+ import { compareVersions, getCurrentVersion, installLatestUpdate } from "../../core/version-check.js";
8
+ import { isLikelyProjectRoot, isWorkspaceInitialized, runWorkspaceInit } from "./init.js";
7
9
  const PLUGIN_NAME = "opencode-rag-plugin";
8
10
  function removeIfExists(targetPath) {
9
11
  if (existsSync(targetPath)) {
@@ -36,13 +38,16 @@ function checkOpenCodeRunning() {
36
38
  export function registerSetupCommand(program) {
37
39
  program
38
40
  .command("setup")
39
- .description("Install/update the OpenCodeRAG runtime once per machine")
41
+ .description("Install/update the OpenCodeRAG runtime and initialize the current workspace")
40
42
  .addHelpText("after", "\nUse cases:\n" +
41
43
  " - First-time install: run once per machine to install the plugin runtime\n" +
42
- " into ~/.opencode/ so OpenCode can discover the RAG plugin.\n" +
43
- " - Updating: re-sync the runtime to the published plugin version.\n" +
44
+ " into ~/.opencode/ so OpenCode can discover the RAG plugin. When the\n" +
45
+ " plugin is not installed yet, installs the latest version from npm.\n" +
46
+ " - Workspace setup: run inside a project to also initialize .opencode/,\n" +
47
+ " the skill file and opencode-rag.json for this workspace.\n" +
48
+ " - Updating: use 'opencode-rag update' to install a newer release.\n" +
44
49
  " - Troubleshooting: use --check to inspect the runtime, or --force to reinstall.\n" +
45
- "\nMachine-level step — run BEFORE 'opencode-rag init' (init configures each workspace).\n")
50
+ "\nMachine + workspace step: run 'opencode-rag init' only when you need to re-sync\nan already initialized workspace.\n")
46
51
  .option("--uninstall", "remove the runtime and cleanup")
47
52
  .option("-f, --force", "force re-setup even if up-to-date")
48
53
  .option("--check", "check whether the runtime is correctly installed")
@@ -103,9 +108,11 @@ export function registerSetupCommand(program) {
103
108
  const runtimeDist = path.join(runtimePluginDir, "dist");
104
109
  const alreadyInstalled = existsSync(runtimeDist);
105
110
  if (alreadyInstalled && installedVersion === pluginVersion && !options.force) {
106
- console.log(` ${c.success("Already up-to-date.")} (${c.value(pluginVersion)}) at ${c.file(runtimeDir)}\n`);
107
- console.log(` ${c.dim("Run `opencode-rag setup --force` to re-install.")}\n`);
108
- return;
111
+ console.log(` ${c.success("Already up-to-date.")} (${c.value(pluginVersion)}) at ${c.file(runtimeDir)}`);
112
+ console.log(` ${c.dim("Run `opencode-rag setup --force` to re-install the runtime.\n")}`);
113
+ }
114
+ else {
115
+ await ensureGlobalPlugin();
109
116
  }
110
117
  const result = await setupRuntime({ force: options.force, version: pluginVersion });
111
118
  if (result.success) {
@@ -114,8 +121,7 @@ export function registerSetupCommand(program) {
114
121
  console.log(`\n${c.success("Setup complete.")}`);
115
122
  console.log(`\n ${c.dim("Next steps:")}`);
116
123
  console.log(` ${c.dim(" 1. Restart OpenCode if it is running")}`);
117
- console.log(` ${c.dim(" 2. Run `opencode-rag init` in each workspace")}`);
118
- console.log(` ${c.dim(" 3. Run `opencode-rag index` to build the search index")}`);
124
+ console.log(` ${c.dim(" 2. Run `opencode-rag index` to build the search index")}`);
119
125
  }
120
126
  else {
121
127
  for (const err of result.errors) {
@@ -124,8 +130,88 @@ export function registerSetupCommand(program) {
124
130
  console.error(`\n ${c.error("Setup failed. Please check the errors above or run with --force.\n")}`);
125
131
  process.exit(1);
126
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")}`);
140
+ }
141
+ else {
142
+ await runWorkspaceInit({});
143
+ }
144
+ }
145
+ 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
+ }
127
149
  checkOpenCodeRunning();
128
150
  console.log();
129
151
  });
130
152
  }
153
+ /**
154
+ * Ensure the plugin package is installed globally.
155
+ *
156
+ * When it is missing (e.g. fresh machine), queries the npm registry for the
157
+ * latest OpenCodeRAG version and installs it, so a bare `opencode-rag setup`
158
+ * bootstraps the whole stack. When the plugin exists but a newer version is
159
+ * published, prints a hint pointing at `opencode-rag update`.
160
+ */
161
+ async function ensureGlobalPlugin() {
162
+ let globalPluginDir = "";
163
+ try {
164
+ const globalRoot = execSync("npm root -g", { encoding: "utf-8", timeout: 10_000 }).trim();
165
+ globalPluginDir = path.join(globalRoot, PLUGIN_NAME);
166
+ }
167
+ catch {
168
+ // npm unavailable -> bootstrap cannot run
169
+ }
170
+ const distOk = globalPluginDir !== "" &&
171
+ existsSync(path.join(globalPluginDir, "dist", "plugin-entry.js")) &&
172
+ existsSync(path.join(globalPluginDir, "dist", "cli.js"));
173
+ if (distOk) {
174
+ const latest = getLatestNpmVersion();
175
+ if (latest && compareVersions(latest, getCurrentVersion()) > 0) {
176
+ console.log(` ${c.warn("Newer version available on npm:")} ${c.value(latest)}`);
177
+ console.log(` ${c.dim("Run `opencode-rag update` to install it.\n")}`);
178
+ }
179
+ return;
180
+ }
181
+ console.log(` ${c.warn("Plugin not installed globally.")} Looking up the latest version on npm...\n`);
182
+ const latest = getLatestNpmVersion();
183
+ if (!latest) {
184
+ console.error(` ${c.error("✗-")} Could not determine the latest version from npm. Install manually with:`);
185
+ console.error(` ${c.file("npm install -g opencode-rag-plugin")}`);
186
+ console.error(` ${c.dim("then re-run `opencode-rag setup`.\n")}`);
187
+ process.exit(1);
188
+ }
189
+ console.log(` ${c.created("Found:")} latest npm release ${c.value(latest)}`);
190
+ console.log(` ${c.dim("Installing...")}\n`);
191
+ const updated = await installLatestUpdate({ verbose: false });
192
+ if (!updated.success) {
193
+ console.error(` ${c.error("✗-")} ${updated.message}`);
194
+ process.exit(1);
195
+ }
196
+ console.log(` ${c.success("✓")} ${updated.message}`);
197
+ }
198
+ /**
199
+ * Query the npm registry for the latest published version of the plugin.
200
+ *
201
+ * Best-effort: returns `null` when npm is unavailable or the lookup fails.
202
+ *
203
+ * @returns The latest version string, or `null` on failure.
204
+ */
205
+ function getLatestNpmVersion() {
206
+ try {
207
+ const out = execSync(`npm view ${PLUGIN_NAME} dist-tags.latest`, {
208
+ encoding: "utf-8",
209
+ timeout: 15_000,
210
+ }).trim();
211
+ return out || null;
212
+ }
213
+ catch {
214
+ return null;
215
+ }
216
+ }
131
217
  //# sourceMappingURL=setup.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-rag-plugin",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "OpenCode plugin for local-first RAG-based semantic code search",
5
5
  "type": "module",
6
6
  "main": "./dist/plugin-entry.js",