opencode-rag-plugin 2.0.1 → 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.
@@ -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