opencode-rag-plugin 2.11.2 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/ReadMe.md +305 -207
  2. package/dist/cli/commands/backend-detect.d.ts +1 -1
  3. package/dist/cli/commands/backend-detect.js +1 -1
  4. package/dist/cli/commands/index.d.ts +0 -1
  5. package/dist/cli/commands/index.js +0 -1
  6. package/dist/cli/commands/setup.js +271 -85
  7. package/dist/cli/commands/{init-helpers.d.ts → workspace-helpers.d.ts} +10 -7
  8. package/dist/cli/commands/{init-helpers.js → workspace-helpers.js} +12 -62
  9. package/dist/cli/index.js +1 -2
  10. package/dist/cli/prompt.d.ts +84 -0
  11. package/dist/cli/prompt.js +247 -0
  12. package/dist/cli/types.d.ts +16 -17
  13. package/dist/cli/wizard/apply.d.ts +58 -0
  14. package/dist/cli/wizard/apply.js +234 -0
  15. package/dist/cli/wizard/flow.d.ts +83 -0
  16. package/dist/cli/wizard/flow.js +759 -0
  17. package/dist/cli/wizard/model-catalog.d.ts +80 -0
  18. package/dist/cli/wizard/model-catalog.js +414 -0
  19. package/dist/cli/wizard/types.d.ts +94 -0
  20. package/dist/cli/wizard/types.js +5 -0
  21. package/dist/cli/workspace.d.ts +40 -0
  22. package/dist/cli/workspace.js +322 -0
  23. package/dist/cli.d.ts +1 -1
  24. package/dist/cli.js +1 -1
  25. package/dist/core/config.d.ts +2 -2
  26. package/dist/core/config.js +2 -2
  27. package/dist/core/provider-defaults.d.ts +2 -0
  28. package/dist/core/provider-defaults.js +4 -0
  29. package/dist/eval/fast-index.js +1 -1
  30. package/dist/opencode/system-guidance.d.ts +1 -1
  31. package/dist/opencode/system-guidance.js +1 -1
  32. package/dist/tui.d.ts +11 -0
  33. package/dist/tui.js +12 -1
  34. package/package.json +1 -1
  35. package/dist/cli/commands/init.d.ts +0 -51
  36. package/dist/cli/commands/init.js +0 -508
@@ -1,508 +0,0 @@
1
- /**
2
- * @fileoverview Init command for configuring a workspace with OpenCodeRAG (directory structure, plugin files, config, health checks).
3
- */
4
- /**
5
- * `init` command — configures a workspace for OpenCodeRAG.
6
- *
7
- * Creates the `.opencode/` directory structure, plugin entry files,
8
- * workspace package.json, opencode config, skill file, and runtime
9
- * configuration. Also handles provider health checks and dependency
10
- * installation.
11
- */
12
- import path from "node:path";
13
- import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, copyFileSync } from "node:fs";
14
- import { loadConfig, findConfigFile, loadWorkspaceConfig, configuredSections, migrateLegacyProjectConfig, projectConfigPath } from "../../core/config.js";
15
- import { checkProviderHealth, pullOllamaModels } from "../../embedder/health.js";
16
- import { destroyAllPooledConnections } from "../../embedder/http.js";
17
- import { c } from "../format.js";
18
- import { getPackageMetadata, readJsonObject, writeJsonFile } from "../helpers.js";
19
- import { buildLegacyTuiConfig, buildOpencodeConfig, buildWorkspacePackageJson, generateDefaultConfigJson, generateSkillFile, generateDecisionSkillFile, generateLegacyWorkspacePluginFile, generateLegacyWorkspaceTuiPluginFile, generateWorkspacePluginFile, generateWorkspaceTuiPluginFile, installPluginFromGlobal, mergeAgentsMdContent, mergeGitignoreContent, LEGACY_PLUGIN_ENTRY, LEGACY_TUI_CONFIG, LEGACY_TUI_ENTRY, WORKSPACE_PLUGIN_DIR, WORKSPACE_PLUGIN_ENTRY, WORKSPACE_TUI_ENTRY, } from "./init-helpers.js";
20
- import { detectOllamaBackend } from "./backend-detect.js";
21
- /**
22
- * Register the `init` command on the given Commander program.
23
- *
24
- * Creates the full `.opencode/` workspace structure, plugin entries,
25
- * skill file, and `opencode-rag.json` config. Optionally runs provider
26
- * health checks and installs workspace-local npm dependencies.
27
- *
28
- * @param program - The Commander `Command` instance to register on.
29
- */
30
- export function registerInitCommand(program) {
31
- program
32
- .command("init")
33
- .description("Configure this workspace (files + auto-tuned opencode-rag.json)")
34
- .addHelpText("after", "\nUse cases:\n" +
35
- " - First-time workspace setup: creates .opencode/, the RAG skill file, AGENTS.md\n" +
36
- " guidance, and opencode-rag.json with embedding batches auto-detected for the\n" +
37
- " Ollama backend (GPU vs CPU).\n" +
38
- " - Re-running in an existing workspace: re-syncs plugin/skill files and keeps the\n" +
39
- " existing opencode-rag.json (overwriting requires interactive confirmation).\n" +
40
- "\nUsually run automatically by 'opencode-rag setup'; run manually to re-sync an existing workspace.\n")
41
- .option("-f, --force", "overwrite existing files")
42
- .option("--skip-install", "skip installing workspace-local plugin dependencies")
43
- .option("--skip-health-check", "skip provider connectivity and model availability check")
44
- .option("--vector-store <provider>", "vector store backend to write (lancedb | clickhouse)")
45
- .option("--clickhouse-url <url>", "ClickHouse endpoint (default http://localhost:8123)")
46
- .option("--clickhouse-database <name>", "ClickHouse database (default OpenCodeRAG)")
47
- .option("--clickhouse-user <name>", "ClickHouse user (default default)")
48
- .option("--clickhouse-password-env <name>", "env var holding the ClickHouse password")
49
- .option("--clickhouse-namespace <name>", "project namespace / table suffix")
50
- .action((options) => runWorkspaceInit(options));
51
- }
52
- /**
53
- * Run the full workspace initialization: `.opencode/` directory structure,
54
- * plugin entry files, `opencode-rag.json`, skill file, AGENTS.md guidance,
55
- * provider health checks, and plugin linking from the global runtime cache.
56
- *
57
- * Shared between the `init` command and the automatic workspace step of
58
- * `opencode-rag setup`.
59
- *
60
- * @param options - init options (force, skipInstall, skipHealthCheck).
61
- */
62
- export async function runWorkspaceInit(options = {}) {
63
- try {
64
- const cwd = process.cwd();
65
- const packageMetadata = getPackageMetadata();
66
- // The workspace config now lives in `.opencode/`: move a legacy
67
- // root-level opencode-rag.json there (only when the canonical file is
68
- // absent), then respect whatever config exists — `.opencode/rag.json`
69
- // included — instead of shadowing it with a new file.
70
- const migratedConfigPath = migrateLegacyProjectConfig(cwd);
71
- const configPath = findConfigFile(cwd) ?? projectConfigPath(cwd);
72
- const configLabel = path.relative(cwd, configPath).replace(/\\/g, "/");
73
- const opencodeDir = path.join(cwd, ".opencode");
74
- const gitignorePath = path.join(opencodeDir, ".gitignore");
75
- const opencodeConfigPath = path.join(opencodeDir, "opencode.json");
76
- const pluginsDir = path.join(opencodeDir, "plugins");
77
- const workspacePluginDir = path.join(pluginsDir, WORKSPACE_PLUGIN_DIR);
78
- const pluginEntryPath = path.join(workspacePluginDir, "index.js");
79
- const tuiPluginEntryPath = path.join(workspacePluginDir, "tui.js");
80
- const legacyPluginEntryPath = path.join(pluginsDir, "rag-plugin.js");
81
- const legacyTuiPluginEntryPath = path.join(pluginsDir, "rag-tui.js");
82
- const legacyTuiConfigPath = path.join(opencodeDir, "tui.json");
83
- const opencodePackagePath = path.join(opencodeDir, "package.json");
84
- console.log(`\n${c.heading("Initializing OpenCodeRAG in workspace...")}\n`);
85
- if (migratedConfigPath) {
86
- console.log(` ${c.updated("Moved:")} opencode-rag.json → .opencode/opencode-rag.json\n`);
87
- }
88
- if (!existsSync(opencodeDir)) {
89
- mkdirSync(opencodeDir, { recursive: true });
90
- console.log(` ${c.created("Created:")} .opencode/`);
91
- }
92
- else {
93
- console.log(` ${c.exists("Exists:")} .opencode/`);
94
- }
95
- // Wiki safety: warn if wiki exists but would be affected (currently init never touches it)
96
- const wikiDir = path.join(opencodeDir, "wiki");
97
- if (existsSync(wikiDir)) {
98
- console.log(` ${c.exists("Preserved:")} .opencode/wiki/ (never modified by init)`);
99
- }
100
- if (!existsSync(pluginsDir)) {
101
- mkdirSync(pluginsDir, { recursive: true });
102
- console.log(` ${c.created("Created:")} .opencode/plugins/`);
103
- }
104
- else {
105
- console.log(` ${c.exists("Exists:")} .opencode/plugins/`);
106
- }
107
- const gitignoreExists = existsSync(gitignorePath);
108
- const nextGitignoreContent = mergeGitignoreContent(gitignoreExists ? readFileSync(gitignorePath, "utf-8") : undefined);
109
- if (!gitignoreExists || options.force || readFileSync(gitignorePath, "utf-8") !== nextGitignoreContent) {
110
- writeFileSync(gitignorePath, nextGitignoreContent, "utf-8");
111
- console.log(` ${gitignoreExists ? c.updated("Updated:") : c.created("Created:")} .opencode/.gitignore`);
112
- }
113
- else {
114
- console.log(` ${c.exists("Exists:")} .opencode/.gitignore`);
115
- }
116
- const opencodeConfigExists = existsSync(opencodeConfigPath);
117
- const nextOpencodeConfig = buildOpencodeConfig(readJsonObject(opencodeConfigPath));
118
- if (!opencodeConfigExists || options.force) {
119
- writeJsonFile(opencodeConfigPath, nextOpencodeConfig);
120
- console.log(` ${opencodeConfigExists ? c.updated("Updated:") : c.created("Created:")} .opencode/opencode.json`);
121
- }
122
- else if (JSON.stringify(readJsonObject(opencodeConfigPath)) !== JSON.stringify(nextOpencodeConfig)) {
123
- writeJsonFile(opencodeConfigPath, nextOpencodeConfig);
124
- console.log(` ${c.updated("Updated:")} .opencode/opencode.json`);
125
- }
126
- else {
127
- console.log(` ${c.exists("Exists:")} .opencode/opencode.json`);
128
- }
129
- // OpenCode 2 discovers plugin *directories* under `.opencode/plugins/`:
130
- // `index.js` is the server (business) entrypoint and `tui.js` beside it
131
- // is the CLI entrypoint. Flat `.js` files only reach the server role, so
132
- // the terminal UI never saw the TUI plugin before this layout.
133
- if (!existsSync(workspacePluginDir)) {
134
- mkdirSync(workspacePluginDir, { recursive: true });
135
- console.log(` ${c.created("Created:")} .opencode/plugins/${WORKSPACE_PLUGIN_DIR}/`);
136
- }
137
- const pluginEntryExists = existsSync(pluginEntryPath);
138
- const pluginEntryContent = generateWorkspacePluginFile(packageMetadata.name);
139
- if (!pluginEntryExists || options.force) {
140
- writeFileSync(pluginEntryPath, pluginEntryContent, "utf-8");
141
- console.log(` ${pluginEntryExists ? c.updated("Updated:") : c.created("Created:")} ${WORKSPACE_PLUGIN_ENTRY}`);
142
- }
143
- else if (readFileSync(pluginEntryPath, "utf-8") !== pluginEntryContent) {
144
- writeFileSync(pluginEntryPath, pluginEntryContent, "utf-8");
145
- console.log(` ${c.updated("Updated:")} ${WORKSPACE_PLUGIN_ENTRY}`);
146
- }
147
- else {
148
- console.log(` ${c.exists("Exists:")} ${WORKSPACE_PLUGIN_ENTRY}`);
149
- }
150
- const tuiPluginEntryExists = existsSync(tuiPluginEntryPath);
151
- const tuiPluginEntryContent = generateWorkspaceTuiPluginFile(packageMetadata.name);
152
- if (!tuiPluginEntryExists || options.force) {
153
- writeFileSync(tuiPluginEntryPath, tuiPluginEntryContent, "utf-8");
154
- console.log(` ${tuiPluginEntryExists ? c.updated("Updated:") : c.created("Created:")} ${WORKSPACE_TUI_ENTRY}`);
155
- }
156
- else if (readFileSync(tuiPluginEntryPath, "utf-8") !== tuiPluginEntryContent) {
157
- writeFileSync(tuiPluginEntryPath, tuiPluginEntryContent, "utf-8");
158
- console.log(` ${c.updated("Updated:")} ${WORKSPACE_TUI_ENTRY}`);
159
- }
160
- else {
161
- console.log(` ${c.exists("Exists:")} ${WORKSPACE_TUI_ENTRY}`);
162
- }
163
- // Migrate away from the V1-era flat entries: a leftover `rag-plugin.js`
164
- // registers the server plugin a second time, and `rag-tui.js` is dead
165
- // weight (the TUI never loads flat files). Only files whose content is
166
- // exactly what an earlier `init` wrote are removed — hand-written files
167
- // and custom `.opencode/tui.json` configs are left untouched.
168
- const legacyEntries = [
169
- [legacyPluginEntryPath, generateLegacyWorkspacePluginFile(packageMetadata.name), LEGACY_PLUGIN_ENTRY],
170
- [legacyTuiPluginEntryPath, generateLegacyWorkspaceTuiPluginFile(packageMetadata.name), LEGACY_TUI_ENTRY],
171
- ];
172
- for (const [legacyPath, legacyContent, legacyRel] of legacyEntries) {
173
- if (!existsSync(legacyPath))
174
- continue;
175
- if (readFileSync(legacyPath, "utf-8") === legacyContent) {
176
- unlinkSync(legacyPath);
177
- console.log(` ${c.updated("Removed:")} ${legacyRel} (superseded by ${WORKSPACE_PLUGIN_DIR}/)`);
178
- }
179
- else {
180
- console.log(` ${c.warn("Kept:")} ${legacyRel} (modified locally — no longer loaded by OpenCode 2)`);
181
- }
182
- }
183
- if (existsSync(legacyTuiConfigPath)) {
184
- const sameLegacyConfig = JSON.stringify(readJsonObject(legacyTuiConfigPath)) === JSON.stringify(buildLegacyTuiConfig());
185
- if (sameLegacyConfig) {
186
- unlinkSync(legacyTuiConfigPath);
187
- console.log(` ${c.updated("Removed:")} ${LEGACY_TUI_CONFIG} (V1 config — OpenCode 2 discovers CLI plugins)`);
188
- }
189
- else {
190
- console.log(` ${c.warn("Kept:")} ${LEGACY_TUI_CONFIG} (V1 config — ignored by OpenCode 2)`);
191
- }
192
- }
193
- const skillsDir = path.join(opencodeDir, "skills");
194
- const skillDir = path.join(skillsDir, "opencode-rag");
195
- const skillPath = path.join(skillDir, "SKILL.md");
196
- if (!existsSync(skillDir)) {
197
- mkdirSync(skillDir, { recursive: true });
198
- console.log(` ${c.created("Created:")} .opencode/skills/opencode-rag/`);
199
- }
200
- const skillContent = generateSkillFile();
201
- const skillExists = existsSync(skillPath);
202
- if (!skillExists || options.force) {
203
- writeFileSync(skillPath, skillContent, "utf-8");
204
- console.log(` ${skillExists ? c.updated("Updated:") : c.created("Created:")} .opencode/skills/opencode-rag/SKILL.md`);
205
- }
206
- else if (readFileSync(skillPath, "utf-8") !== skillContent) {
207
- writeFileSync(skillPath, skillContent, "utf-8");
208
- console.log(` ${c.updated("Updated:")} .opencode/skills/opencode-rag/SKILL.md`);
209
- }
210
- else {
211
- console.log(` ${c.exists("Exists:")} .opencode/skills/opencode-rag/SKILL.md`);
212
- }
213
- // Separate decision-model skill — loaded on demand when a task needs
214
- // classification/routing/scoring via `make_decision`.
215
- const decisionSkillDir = path.join(skillsDir, "make-decision");
216
- const decisionSkillPath = path.join(decisionSkillDir, "SKILL.md");
217
- if (!existsSync(decisionSkillDir)) {
218
- mkdirSync(decisionSkillDir, { recursive: true });
219
- console.log(` ${c.created("Created:")} .opencode/skills/make-decision/`);
220
- }
221
- const decisionSkillContent = generateDecisionSkillFile();
222
- const decisionSkillExists = existsSync(decisionSkillPath);
223
- if (!decisionSkillExists || options.force) {
224
- writeFileSync(decisionSkillPath, decisionSkillContent, "utf-8");
225
- console.log(` ${decisionSkillExists ? c.updated("Updated:") : c.created("Created:")} .opencode/skills/make-decision/SKILL.md`);
226
- }
227
- else if (readFileSync(decisionSkillPath, "utf-8") !== decisionSkillContent) {
228
- writeFileSync(decisionSkillPath, decisionSkillContent, "utf-8");
229
- console.log(` ${c.updated("Updated:")} .opencode/skills/make-decision/SKILL.md`);
230
- }
231
- else {
232
- console.log(` ${c.exists("Exists:")} .opencode/skills/make-decision/SKILL.md`);
233
- }
234
- const agentsMdPath = path.join(cwd, "AGENTS.md");
235
- const agentsMdExists = existsSync(agentsMdPath);
236
- // Read effective memory/decision flags from existing config (if present)
237
- let promptEnforcement = true;
238
- let decisionEnabled = false;
239
- let routeBeforeAsking = false;
240
- try {
241
- if (existsSync(configPath)) {
242
- const existingCfg = loadConfig(configPath, false);
243
- promptEnforcement = existingCfg.memory?.promptEnforcement ?? true;
244
- decisionEnabled = existingCfg.decision?.enabled ?? false;
245
- routeBeforeAsking = existingCfg.decision?.routeBeforeAsking ?? false;
246
- }
247
- }
248
- catch {
249
- // Malformed or missing config — use defaults
250
- }
251
- const nextAgentsMd = mergeAgentsMdContent(agentsMdExists ? readFileSync(agentsMdPath, "utf-8") : undefined, { promptEnforcement, decisionEnabled, routeBeforeAsking });
252
- if (!agentsMdExists || options.force) {
253
- writeFileSync(agentsMdPath, nextAgentsMd, "utf-8");
254
- console.log(` ${agentsMdExists ? c.updated("Updated:") : c.created("Created:")} AGENTS.md`);
255
- }
256
- else if (readFileSync(agentsMdPath, "utf-8") !== nextAgentsMd) {
257
- writeFileSync(agentsMdPath, nextAgentsMd, "utf-8");
258
- console.log(` ${c.updated("Updated:")} AGENTS.md`);
259
- }
260
- else {
261
- console.log(` ${c.exists("Exists:")} AGENTS.md`);
262
- }
263
- const workspacePackageExists = existsSync(opencodePackagePath);
264
- const nextWorkspacePackage = buildWorkspacePackageJson(readJsonObject(opencodePackagePath), packageMetadata);
265
- if (!workspacePackageExists || options.force) {
266
- writeJsonFile(opencodePackagePath, nextWorkspacePackage);
267
- console.log(` ${workspacePackageExists ? c.updated("Updated:") : c.created("Created:")} .opencode/package.json`);
268
- }
269
- else if (JSON.stringify(readJsonObject(opencodePackagePath)) !== JSON.stringify(nextWorkspacePackage)) {
270
- writeJsonFile(opencodePackagePath, nextWorkspacePackage);
271
- console.log(` ${c.updated("Updated:")} .opencode/package.json`);
272
- }
273
- else {
274
- console.log(` ${c.exists("Exists:")} .opencode/package.json`);
275
- }
276
- const configExists = existsSync(configPath);
277
- // Detect the Ollama backend (CPU vs GPU) lazily — only when we are
278
- // actually about to write a config — and tune embedding batches for it.
279
- let detectedTuning;
280
- const configContent = async () => {
281
- if (!detectedTuning) {
282
- try {
283
- const info = await detectOllamaBackend();
284
- detectedTuning = info.tuning;
285
- const icon = info.backend === "gpu" ? c.success("GPU:") :
286
- info.backend === "cpu" ? c.warn("CPU:") :
287
- c.dim("Backend:");
288
- console.log(` ${icon} ${info.message}`);
289
- }
290
- catch {
291
- detectedTuning = undefined;
292
- }
293
- }
294
- // Carry the identity-critical embedding keys (apiKey, vectorDimension)
295
- // over from the file being replaced: a reset must never downgrade the
296
- // store schema to the 384 default or drop provider auth.
297
- let existingRaw;
298
- if (configExists) {
299
- try {
300
- existingRaw = readFileSync(configPath, "utf-8");
301
- }
302
- catch {
303
- existingRaw = undefined;
304
- }
305
- }
306
- return generateDefaultConfigJson(detectedTuning, existingRaw);
307
- };
308
- let configWritten = false;
309
- if (!configExists) {
310
- writeFileSync(configPath, await configContent(), "utf-8");
311
- configWritten = true;
312
- console.log(` ${c.created("Created:")} ${configLabel}`);
313
- }
314
- else {
315
- // NEVER overwrite existing config without interactive confirmation
316
- let overwrite = false;
317
- if (process.stdin.isTTY) {
318
- const readline = await import("node:readline");
319
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
320
- const answer = await new Promise((resolve) => {
321
- rl.question(` ${c.warn(`${configLabel} already exists.`)} Overwrite with default config? A backup will be saved. (y/N) `, resolve);
322
- });
323
- rl.close();
324
- overwrite = /^y(?:es)?$/i.test(answer.trim());
325
- }
326
- if (overwrite) {
327
- copyFileSync(configPath, `${configPath}.bak`);
328
- console.log(` ${c.dim("Backup:")} ${configLabel}.bak`);
329
- writeFileSync(configPath, await configContent(), "utf-8");
330
- configWritten = true;
331
- console.log(` ${c.updated("Updated:")} ${configLabel}`);
332
- }
333
- else {
334
- console.log(` ${c.exists("Exists:")} ${configLabel} (preserved)`);
335
- if (!process.stdin.isTTY && options.force) {
336
- console.log(` ${c.warn("Skipped overwrite:")} non-interactive shell. Edit ${configLabel} manually or re-run in a TTY.`);
337
- }
338
- }
339
- }
340
- // ── Optional central ClickHouse backend ──
341
- if (configWritten && options.vectorStore === "clickhouse") {
342
- const raw = readJsonObject(configPath) ?? {};
343
- const current = (raw.vectorStore ?? {});
344
- const currentClickhouse = current.clickhouse && typeof current.clickhouse === "object"
345
- ? current.clickhouse
346
- : {};
347
- raw.vectorStore = {
348
- ...current,
349
- provider: "clickhouse",
350
- clickhouse: {
351
- ...currentClickhouse,
352
- url: options.clickhouseUrl ?? "http://localhost:8123",
353
- database: options.clickhouseDatabase ?? "OpenCodeRAG",
354
- username: options.clickhouseUser ?? "default",
355
- passwordEnv: options.clickhousePasswordEnv ?? "OPENCODERAG_CLICKHOUSE_PASSWORD",
356
- ...(options.clickhouseNamespace ? { namespace: options.clickhouseNamespace } : {}),
357
- },
358
- };
359
- writeJsonFile(configPath, raw);
360
- console.log(` ${c.created("Configured:")} clickhouse backend (${options.clickhouseUrl ?? "http://localhost:8123"})`);
361
- }
362
- // ── Provider health check + dependency install (parallel) ──
363
- const healthPromise = options.skipHealthCheck
364
- ? null
365
- : (async () => {
366
- console.log(`\n${c.heading("Checking provider connectivity...")}\n`);
367
- // Effective config (global < workspace) and the sections the user
368
- // actually configured: models that are merely on by default are
369
- // never probed or offered for `ollama pull`.
370
- const ragConfig = loadWorkspaceConfig(cwd);
371
- return checkProviderHealth(ragConfig, configuredSections(cwd));
372
- })();
373
- const installPromise = options.skipInstall
374
- ? null
375
- : installPluginFromGlobal(opencodeDir, packageMetadata.name, false);
376
- // Wait for health check results first
377
- if (healthPromise) {
378
- const results = await healthPromise;
379
- for (const r of results) {
380
- const icon = r.status === "ok" ? c.success("✓") : r.status === "missing" ? c.warn("○") : c.error("✗");
381
- const typeLabel = r.type === "image_description" ? "image description" : r.type === "image_description_on_demand" ? "image description (on-demand)" : r.type;
382
- const label = `${typeLabel} model`;
383
- console.log(` ${icon} ${c.value(r.model)} (${r.provider}) — ${label}: ${r.status}`);
384
- if (r.error)
385
- console.log(` ${c.dim(r.error)}`);
386
- }
387
- const missingOllama = results.filter((r) => r.status === "missing" && r.provider === "ollama");
388
- if (missingOllama.length > 0) {
389
- const ragConfig = loadWorkspaceConfig(cwd);
390
- const pullEntries = missingOllama.map((r) => {
391
- if (r.type === "embedding") {
392
- return { model: r.model, baseUrl: ragConfig.embedding.baseUrl, proxy: ragConfig.embedding.proxy };
393
- }
394
- if (r.type === "description" && ragConfig.description) {
395
- return { model: r.model, baseUrl: ragConfig.description.baseUrl, proxy: ragConfig.description.proxy };
396
- }
397
- if (r.type === "image_description" && ragConfig.imageDescription) {
398
- return { model: r.model, baseUrl: ragConfig.imageDescription.baseUrl, proxy: ragConfig.imageDescription.proxy };
399
- }
400
- if (r.type === "image_description_on_demand" && ragConfig.imageDescription) {
401
- const onDemand = ragConfig.imageDescription.onDemand;
402
- return {
403
- model: r.model,
404
- baseUrl: onDemand?.baseUrl ?? ragConfig.imageDescription.baseUrl,
405
- proxy: onDemand?.proxy ?? ragConfig.imageDescription.proxy,
406
- };
407
- }
408
- return { model: r.model, baseUrl: ragConfig.embedding.baseUrl, proxy: ragConfig.embedding.proxy };
409
- });
410
- console.log(`\n ${c.warn("Models not found:")} ${pullEntries.map((e) => e.model).join(", ")}`);
411
- // Non-TTY guard: rl.question would block forever with a still-open
412
- // stdin pipe (e.g. `echo y | opencode-rag init`, CI runners).
413
- if (!process.stdin.isTTY) {
414
- console.log(` ${c.dim("Non-interactive shell — skipping. Pull manually with: ollama pull <model>")}`);
415
- }
416
- else {
417
- const readline = await import("node:readline");
418
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
419
- const answer = await new Promise((resolve) => {
420
- rl.question(` Pull ${pullEntries.length === 1 ? "this model" : "these models"} now? (y/n) `, resolve);
421
- });
422
- rl.close();
423
- if (answer.toLowerCase() === "y" || answer.toLowerCase() === "yes") {
424
- console.log();
425
- try {
426
- await pullOllamaModels(pullEntries, (model, line) => {
427
- console.log(` ${c.value(model)}: ${line}`);
428
- });
429
- console.log(`\n ${c.success("Models pulled successfully.")}`);
430
- }
431
- catch (err) {
432
- console.error(`\n ${c.error("Pull failed:")} ${err.message}`);
433
- console.log(` ${c.dim("Pull manually with: ollama pull <model>")}`);
434
- }
435
- }
436
- else {
437
- console.log(` ${c.dim("Skipped. Pull manually with: ollama pull <model>")}`);
438
- }
439
- }
440
- }
441
- const hasErrors = results.some((r) => r.status === "error");
442
- if (hasErrors) {
443
- console.log(`\n ${c.warn("Some providers are not reachable.")} Check configuration and network, then run ${c.file("'opencode-rag index'")}.`);
444
- }
445
- }
446
- // Now install the plugin from global cache via junction
447
- if (installPromise) {
448
- console.log(`\n${c.heading("Installing workspace-local plugin...")}\n`);
449
- await installPromise;
450
- console.log(`\n ${c.success("Installed:")} .opencode/node_modules/`);
451
- console.log(` ${c.dim("Plugin is linked to global runtime cache; no npm install was required.")}`);
452
- }
453
- else {
454
- console.log(`\n ${c.exists("Skipped:")} plugin installation (--skip-install)`);
455
- }
456
- console.log(`\n${c.success("Done.")} Restart OpenCode if it is running, then run ${c.file("'opencode-rag index'")} in this workspace.`);
457
- }
458
- catch (err) {
459
- console.error(`\n ${c.error("Init failed:")} ${err.message}`);
460
- console.error(` ${c.dim("Fix the issue above, then run 'opencode-rag init' again.")}`);
461
- process.exitCode = 1;
462
- }
463
- finally {
464
- destroyAllPooledConnections();
465
- }
466
- }
467
- /**
468
- * Best-effort check whether `cwd` looks like a project root (git repo or
469
- * common project manifest files). `opencode-rag setup` uses this to decide
470
- * whether to automatically initialize the current workspace.
471
- *
472
- * @param cwd - Directory to inspect.
473
- * @returns Whether the directory looks like a project root.
474
- */
475
- export function isLikelyProjectRoot(cwd) {
476
- if (existsSync(path.join(cwd, ".git"))) {
477
- return true;
478
- }
479
- const markers = [
480
- "package.json",
481
- "AGENTS.md",
482
- "README.md",
483
- "pyproject.toml",
484
- "Cargo.toml",
485
- "go.mod",
486
- "opencode-rag.json",
487
- ".opencode/opencode-rag.json",
488
- ];
489
- return markers.some((marker) => existsSync(path.join(cwd, marker)));
490
- }
491
- /**
492
- * Check whether the workspace at `cwd` has already been initialized with
493
- * OpenCodeRAG (plugin entry files and the TUI plugin config are present).
494
- *
495
- * @param cwd - Directory to inspect.
496
- * @returns Whether the workspace looks initialized.
497
- */
498
- export function isWorkspaceInitialized(cwd) {
499
- // V2 layout: plugin directory with server + TUI entrypoints beside each other.
500
- if (existsSync(path.join(cwd, ".opencode", "plugins", WORKSPACE_PLUGIN_DIR, "index.js")) &&
501
- existsSync(path.join(cwd, ".opencode", "plugins", WORKSPACE_PLUGIN_DIR, "tui.js"))) {
502
- return true;
503
- }
504
- // V1 layout (flat entries + .opencode/tui.json): treated as *not* initialized
505
- // so `setup` re-runs `init` once and migrates the workspace.
506
- return false;
507
- }
508
- //# sourceMappingURL=init.js.map