opencode-rag-plugin 2.11.2 → 2.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/ReadMe.md +386 -222
  2. package/dist/cli/commands/backend-detect.d.ts +1 -1
  3. package/dist/cli/commands/backend-detect.js +1 -1
  4. package/dist/cli/commands/index.d.ts +0 -1
  5. package/dist/cli/commands/index.js +0 -1
  6. package/dist/cli/commands/setup.js +344 -85
  7. package/dist/cli/commands/{init-helpers.d.ts → workspace-helpers.d.ts} +10 -7
  8. package/dist/cli/commands/{init-helpers.js → workspace-helpers.js} +15 -62
  9. package/dist/cli/index.js +1 -2
  10. package/dist/cli/ollama.d.ts +12 -0
  11. package/dist/cli/ollama.js +26 -0
  12. package/dist/cli/prompt.d.ts +121 -0
  13. package/dist/cli/prompt.js +309 -0
  14. package/dist/cli/types.d.ts +31 -19
  15. package/dist/cli/wizard/apply.d.ts +60 -0
  16. package/dist/cli/wizard/apply.js +243 -0
  17. package/dist/cli/wizard/flow.d.ts +121 -0
  18. package/dist/cli/wizard/flow.js +904 -0
  19. package/dist/cli/wizard/model-catalog.d.ts +80 -0
  20. package/dist/cli/wizard/model-catalog.js +414 -0
  21. package/dist/cli/wizard/presets.d.ts +55 -0
  22. package/dist/cli/wizard/presets.js +70 -0
  23. package/dist/cli/wizard/repair.d.ts +54 -0
  24. package/dist/cli/wizard/repair.js +266 -0
  25. package/dist/cli/wizard/types.d.ts +99 -0
  26. package/dist/cli/wizard/types.js +5 -0
  27. package/dist/cli/workspace.d.ts +57 -0
  28. package/dist/cli/workspace.js +407 -0
  29. package/dist/cli.d.ts +1 -1
  30. package/dist/cli.js +1 -1
  31. package/dist/core/auto-scaffold.d.ts +21 -0
  32. package/dist/core/auto-scaffold.js +80 -0
  33. package/dist/core/config.d.ts +13 -2
  34. package/dist/core/config.js +13 -3
  35. package/dist/core/global-plugin.d.ts +48 -0
  36. package/dist/core/global-plugin.js +114 -0
  37. package/dist/core/provider-defaults.d.ts +2 -0
  38. package/dist/core/provider-defaults.js +4 -0
  39. package/dist/core/setup-runtime.js +40 -26
  40. package/dist/embedder/health.js +44 -2
  41. package/dist/eval/fast-index.js +1 -1
  42. package/dist/opencode/system-guidance.d.ts +1 -1
  43. package/dist/opencode/system-guidance.js +1 -1
  44. package/dist/tui.d.ts +11 -0
  45. package/dist/tui.js +12 -1
  46. package/dist/v2/v2-adapter.js +9 -0
  47. package/package.json +3 -2
  48. package/scripts/postinstall-setup.js +16 -0
  49. package/dist/cli/commands/init.d.ts +0 -51
  50. package/dist/cli/commands/init.js +0 -508
@@ -0,0 +1,904 @@
1
+ /**
2
+ * @fileoverview Interactive `setup` wizard.
3
+ *
4
+ * The flow is deliberately linear and every question has a default taken from
5
+ * the effective configuration, so pressing Enter through the wizard keeps an
6
+ * existing setup intact. Any prompt resolving `undefined` (Ctrl+C / Ctrl+D)
7
+ * aborts the whole wizard: no configuration is written.
8
+ */
9
+ import { DEFAULT_CONFIG } from "../../core/config.js";
10
+ import { getProviderDefault, supportsChat, supportsEmbedding } from "../../core/provider-defaults.js";
11
+ import { c } from "../format.js";
12
+ import { ollamaInstallHint } from "../ollama.js";
13
+ import { detectOllamaBackend } from "../commands/backend-detect.js";
14
+ import { fetchModelCatalog, probeEmbeddingDimension, ollamaRoot, } from "./model-catalog.js";
15
+ import { describePreset, presetForBackend } from "./presets.js";
16
+ const PROVIDERS = [
17
+ {
18
+ id: "ollama",
19
+ label: "Ollama",
20
+ description: "Local or remote — embeddings, chat, vision and the decision model",
21
+ embedding: true,
22
+ chat: true,
23
+ },
24
+ {
25
+ id: "openai",
26
+ label: "OpenAI-compatible API",
27
+ description: "OpenAI, llama.cpp, LM Studio, vLLM, OpenRouter, …",
28
+ embedding: true,
29
+ chat: true,
30
+ },
31
+ {
32
+ id: "cohere",
33
+ label: "Cohere",
34
+ description: "Embeddings only",
35
+ embedding: true,
36
+ chat: false,
37
+ },
38
+ {
39
+ id: "anthropic",
40
+ label: "Anthropic",
41
+ description: "Chat and vision — no embedding API",
42
+ embedding: false,
43
+ chat: true,
44
+ },
45
+ {
46
+ id: "google",
47
+ label: "Google Gemini",
48
+ description: "Chat and vision — no embedding API",
49
+ embedding: false,
50
+ chat: true,
51
+ },
52
+ ];
53
+ /** Read a section of the raw config. */
54
+ function section(config, name) {
55
+ const value = config[name];
56
+ return value && typeof value === "object" && !Array.isArray(value)
57
+ ? value
58
+ : undefined;
59
+ }
60
+ /** Read a string from a raw config section. */
61
+ function readString(config, key) {
62
+ const value = config?.[key];
63
+ return typeof value === "string" && value.length > 0 ? value : undefined;
64
+ }
65
+ /** Read a boolean from a raw config section. */
66
+ function readBoolean(config, key) {
67
+ const value = config?.[key];
68
+ return typeof value === "boolean" ? value : undefined;
69
+ }
70
+ /** Default base URL for a provider. */
71
+ function defaultBaseUrl(provider) {
72
+ const defaults = getProviderDefault(provider);
73
+ if (defaults?.defaultBaseUrl)
74
+ return defaults.defaultBaseUrl;
75
+ if (provider === "ollama")
76
+ return "http://127.0.0.1:11434/api";
77
+ return "";
78
+ }
79
+ /** Render a catalog probe result as a status line. */
80
+ function printCatalogStatus(catalog) {
81
+ if (catalog.reachable) {
82
+ const count = catalog.models.length;
83
+ console.log(` ${c.success("✓")} ${c.value(catalog.baseUrl)} — ${count} model${count === 1 ? "" : "s"} found`);
84
+ return;
85
+ }
86
+ console.log(` ${c.error("✗")} ${c.value(catalog.baseUrl)} — ${catalog.error ?? "unreachable"}`);
87
+ }
88
+ /** Ask for a provider + base URL + optional API key, then probe its models. */
89
+ export async function askHost(prompter, options) {
90
+ const { message, existing, flags } = options;
91
+ const previous = section(existing, "embedding");
92
+ const entries = [...PROVIDERS];
93
+ for (const extra of options.extraProviders ?? []) {
94
+ if (!entries.some((entry) => entry.id === extra.id))
95
+ entries.push(extra);
96
+ }
97
+ const candidates = entries.filter((entry) => (options.requireEmbedding ? entry.embedding : true) &&
98
+ (options.requireChat ? entry.chat : true));
99
+ const defaultProvider = (flags.provider && candidates.some((entry) => entry.id === flags.provider) ? flags.provider : undefined) ??
100
+ readString(previous, "provider") ??
101
+ DEFAULT_CONFIG.embedding.provider;
102
+ const defaultIndex = Math.max(0, candidates.findIndex((entry) => entry.id === defaultProvider));
103
+ const picked = await prompter.select({
104
+ message,
105
+ options: candidates.map((entry) => ({
106
+ label: entry.label,
107
+ value: entry.id,
108
+ description: entry.description,
109
+ })),
110
+ defaultIndex,
111
+ });
112
+ if (picked === undefined)
113
+ return undefined;
114
+ const entry = candidates.find((candidate) => candidate.id === picked);
115
+ if (!entry)
116
+ return undefined;
117
+ const baseUrlDefault = flags.baseUrl ??
118
+ readString(previous, "baseUrl") ??
119
+ (entry.id === "ollama" ? "http://127.0.0.1:11434/api" : defaultBaseUrl(entry.id));
120
+ const baseUrl = await prompter.text({
121
+ message: "Base URL",
122
+ defaultValue: baseUrlDefault,
123
+ hint: entry.id === "ollama"
124
+ ? "Ollama accepts http://127.0.0.1:11434 or http://127.0.0.1:11434/api"
125
+ : entry.id === "openai"
126
+ ? "OpenAI-compatible servers usually end in /v1 (llama.cpp, LM Studio, vLLM, …)"
127
+ : undefined,
128
+ validate: (value) => {
129
+ if (!value)
130
+ return "A base URL is required.";
131
+ try {
132
+ new URL(value);
133
+ return undefined;
134
+ }
135
+ catch {
136
+ return "Enter a valid URL, e.g. http://127.0.0.1:11434/api";
137
+ }
138
+ },
139
+ });
140
+ if (baseUrl === undefined)
141
+ return undefined;
142
+ let apiKey;
143
+ const envVar = getProviderDefault(entry.id)?.apiKeyEnvVar;
144
+ const envValue = envVar ? process.env[envVar] : undefined;
145
+ const existingKey = readString(previous, "apiKey");
146
+ const flagKey = flags.apiKey && flags.apiKey.startsWith("env:")
147
+ ? process.env[flags.apiKey.slice(4)]
148
+ : flags.apiKey;
149
+ if (flagKey) {
150
+ apiKey = flagKey;
151
+ }
152
+ else if (options.forceKeyPrompt && entry.id !== "ollama") {
153
+ if (existingKey && !existingKey.startsWith("env:")) {
154
+ console.log(` ${c.dim("The stored key was rejected — paste a new one, or press Enter to keep it.")}`);
155
+ }
156
+ const typed = await prompter.password("API key (Enter keeps the current one)");
157
+ if (typed === undefined)
158
+ return undefined;
159
+ if (typed.trim().length > 0)
160
+ apiKey = typed.trim();
161
+ else if (existingKey && !existingKey.startsWith("env:"))
162
+ apiKey = existingKey;
163
+ }
164
+ else if (existingKey && !existingKey.startsWith("env:")) {
165
+ apiKey = existingKey;
166
+ console.log(` ${c.dim("Using the API key already stored in the config.")}`);
167
+ }
168
+ else if (envValue) {
169
+ console.log(` ${c.dim(`Using ${envVar} from the environment (not written to the config).`)}`);
170
+ }
171
+ else if (entry.id !== "ollama") {
172
+ console.log(` ${c.dim(envVar ? `No ${envVar} set. Paste a key or leave empty to add it later.` : "Paste an API key or leave empty to add it later.")}`);
173
+ const typed = await prompter.password("API key (Enter to skip)");
174
+ if (typed === undefined)
175
+ return undefined;
176
+ if (typed.trim().length > 0)
177
+ apiKey = typed.trim();
178
+ }
179
+ console.log(`\n ${c.dim(`Checking ${entry.id} at ${baseUrl}…`)}`);
180
+ const catalog = await fetchModelCatalog({
181
+ provider: entry.id,
182
+ baseUrl,
183
+ apiKey,
184
+ proxy: options.proxy,
185
+ });
186
+ printCatalogStatus(catalog);
187
+ return {
188
+ host: {
189
+ provider: entry.id,
190
+ baseUrl: entry.id === "ollama" ? catalog.baseUrl : baseUrl,
191
+ ...(apiKey ? { apiKey } : {}),
192
+ },
193
+ catalog,
194
+ };
195
+ }
196
+ /**
197
+ * Pick a model from a probed catalog, falling back to free-text entry.
198
+ *
199
+ * `__custom__` is always offered so a model that the provider does not list
200
+ * (or a freshly pulled one) can still be typed.
201
+ */
202
+ export async function pickModel(prompter, options) {
203
+ const { catalog, capability } = options;
204
+ const candidates = catalog.models.filter((model) => model.capabilities.includes(capability));
205
+ // Keep the configured model selectable when the host lists models but did
206
+ // not advertise it. With no candidates at all, fall straight through to
207
+ // manual entry instead of showing a one-item menu.
208
+ if (candidates.length > 0 && options.defaultValue && !candidates.some((model) => model.id === options.defaultValue)) {
209
+ candidates.unshift({ id: options.defaultValue, capabilities: [capability] });
210
+ }
211
+ if (candidates.length === 0) {
212
+ if (catalog.reachable) {
213
+ console.log(` ${c.warn("No model with the required capability was advertised by the host.")}`);
214
+ }
215
+ return prompter.text({
216
+ message: options.message,
217
+ defaultValue: options.defaultValue ?? "",
218
+ hint: "Type the model name exactly as the provider expects it.",
219
+ });
220
+ }
221
+ const entries = candidates.map((model) => ({
222
+ label: model.id,
223
+ value: model.id,
224
+ description: model.detail,
225
+ }));
226
+ entries.push({ label: "Type a model name…", value: "__custom__" });
227
+ if (options.allowSkip) {
228
+ entries.push({ label: "Skip for now", value: "__skip__" });
229
+ }
230
+ const defaultIndex = Math.max(0, options.defaultValue ? candidates.findIndex((model) => model.id === options.defaultValue) : 0);
231
+ const picked = await prompter.select({
232
+ message: options.message,
233
+ options: entries,
234
+ defaultIndex,
235
+ });
236
+ if (picked === undefined)
237
+ return undefined;
238
+ if (picked === "__skip__")
239
+ return undefined;
240
+ if (picked === "__custom__") {
241
+ return prompter.text({
242
+ message: options.message,
243
+ defaultValue: options.defaultValue ?? "",
244
+ hint: "Type the model name exactly as the provider expects it.",
245
+ });
246
+ }
247
+ return picked;
248
+ }
249
+ /** Print a compact summary of the collected answers. */
250
+ function printSummary(answers) {
251
+ console.log(`\n${c.heading("Configuration summary")}\n`);
252
+ const host = (choice) => `${choice.provider} @ ${choice.baseUrl}${choice.apiKey ? " (API key set)" : ""}`;
253
+ console.log(` ${c.label("Embedding:")} ${c.value(answers.embedding.model)} — ${host(answers.embedding)}${answers.embedding.vectorDimension ? ` (${answers.embedding.vectorDimension} dims)` : ""}`);
254
+ console.log(` ${c.label("Description:")} ${answers.description ? `${c.value(answers.description.model)} — ${host(answers.description)}` : c.dim("disabled")}`);
255
+ console.log(` ${c.label("Vision:")} ${answers.imageDescription ? `${c.value(answers.imageDescription.model)} — ${host(answers.imageDescription)}` : c.dim("disabled")}`);
256
+ console.log(` ${c.label("Decision:")} ${answers.decision?.enabled ? `${c.value(answers.decision.model ?? "tev1")} — ${answers.decision.baseUrl ?? "ollama"}` : c.dim("disabled")}`);
257
+ console.log(` ${c.label("Reranking:")} ${answers.reranking?.enabled ? `${c.value(answers.reranking.model ?? "reranker")} — ${answers.reranking.baseUrl ?? ""}` : c.dim("disabled")}`);
258
+ console.log(` ${c.label("Shell guard:")} ${answers.shellGuard ? (answers.shellGuard.enabled ? c.value("enabled") : c.dim("disabled")) : c.dim("unchanged")}`);
259
+ console.log(` ${c.label("Memory:")} ${answers.memory ? (answers.memory.passiveCapture ? c.value("auto-capture on") : c.dim("auto-capture off")) : c.dim("unchanged")}`);
260
+ console.log(` ${c.label("Vector store:")} ${answers.vectorStore ? c.value(answers.vectorStore.provider) : c.dim("unchanged")}`);
261
+ console.log(`\n ${c.dim("Provider/model settings are written to the global config; toggles to .opencode/opencode-rag.json.")}`);
262
+ }
263
+ /** Ask the advanced questions (reranking, shell guard, memory, vector store). */
264
+ async function askAdvanced(prompter, existing, flags) {
265
+ const reranking = section(existing, "reranking");
266
+ const shellGuard = section(existing, "shellGuard");
267
+ const memory = section(existing, "memory");
268
+ const vectorStore = section(existing, "vectorStore");
269
+ const indexing = section(existing, "indexing");
270
+ const openCode = section(existing, "openCode");
271
+ const autoIndex = section(openCode ?? {}, "autoIndex");
272
+ const answers = {};
273
+ const wantRerank = flags.reranking ??
274
+ (await prompter.confirm({
275
+ message: "Enable reranking with a llama-server /v1/rerank endpoint?",
276
+ defaultValue: readBoolean(reranking, "enabled") ?? DEFAULT_CONFIG.reranking?.enabled ?? false,
277
+ }));
278
+ if (wantRerank === undefined)
279
+ return undefined;
280
+ if (wantRerank) {
281
+ const baseUrl = await prompter.text({
282
+ message: "Rerank base URL",
283
+ defaultValue: readString(reranking, "baseUrl") ?? DEFAULT_CONFIG.reranking?.baseUrl ?? "http://127.0.0.1:8080/v1",
284
+ });
285
+ if (baseUrl === undefined)
286
+ return undefined;
287
+ const model = await prompter.text({
288
+ message: "Rerank model",
289
+ defaultValue: readString(reranking, "model") ?? DEFAULT_CONFIG.reranking?.model ?? "qwen3-reranker-0.6b",
290
+ });
291
+ if (model === undefined)
292
+ return undefined;
293
+ answers.reranking = { enabled: true, baseUrl, model };
294
+ }
295
+ else {
296
+ answers.reranking = { enabled: false };
297
+ }
298
+ const wantGuard = flags.shellGuard ??
299
+ (await prompter.confirm({
300
+ message: "Enable the shell-command guard (needs the decision model)?",
301
+ defaultValue: readBoolean(shellGuard, "enabled") ?? DEFAULT_CONFIG.shellGuard?.enabled ?? false,
302
+ }));
303
+ if (wantGuard === undefined)
304
+ return undefined;
305
+ answers.shellGuard = { enabled: wantGuard };
306
+ const wantCapture = flags.memoryCapture ??
307
+ (await prompter.confirm({
308
+ message: "Enable automatic quirk capture (passive + prompt enforcement + session end)?",
309
+ defaultValue: readBoolean(memory, "passiveCapture") ?? DEFAULT_CONFIG.memory?.passiveCapture ?? true,
310
+ }));
311
+ if (wantCapture === undefined)
312
+ return undefined;
313
+ answers.memory = {
314
+ passiveCapture: wantCapture,
315
+ promptEnforcement: wantCapture,
316
+ sessionEndExtraction: wantCapture,
317
+ };
318
+ const backendDefault = flags.vectorStore ?? readString(vectorStore, "provider") ?? "lancedb";
319
+ const backend = await prompter.select({
320
+ message: "Vector store backend",
321
+ options: [
322
+ { label: "LanceDB (local, default)", value: "lancedb", description: "One index per workspace" },
323
+ { label: "ClickHouse (central)", value: "clickhouse", description: "One shared index for many machines" },
324
+ ],
325
+ defaultIndex: backendDefault === "clickhouse" ? 1 : 0,
326
+ });
327
+ if (backend === undefined)
328
+ return undefined;
329
+ if (backend === "clickhouse") {
330
+ const current = section(vectorStore ?? {}, "clickhouse");
331
+ const url = await prompter.text({
332
+ message: "ClickHouse URL",
333
+ defaultValue: flags.clickhouseUrl ?? readString(current, "url") ?? "http://localhost:8123",
334
+ });
335
+ if (url === undefined)
336
+ return undefined;
337
+ const database = await prompter.text({
338
+ message: "ClickHouse database",
339
+ defaultValue: flags.clickhouseDatabase ?? readString(current, "database") ?? "OpenCodeRAG",
340
+ });
341
+ if (database === undefined)
342
+ return undefined;
343
+ const username = await prompter.text({
344
+ message: "ClickHouse user",
345
+ defaultValue: flags.clickhouseUser ?? readString(current, "username") ?? "default",
346
+ });
347
+ if (username === undefined)
348
+ return undefined;
349
+ const passwordEnv = await prompter.text({
350
+ message: "Environment variable holding the ClickHouse password",
351
+ defaultValue: flags.clickhousePasswordEnv ?? readString(current, "passwordEnv") ?? "OPENCODERAG_CLICKHOUSE_PASSWORD",
352
+ });
353
+ if (passwordEnv === undefined)
354
+ return undefined;
355
+ const namespace = await prompter.text({
356
+ message: "Namespace (table suffix, optional)",
357
+ defaultValue: flags.clickhouseNamespace ?? readString(current, "namespace") ?? "",
358
+ });
359
+ if (namespace === undefined)
360
+ return undefined;
361
+ answers.vectorStore = {
362
+ provider: "clickhouse",
363
+ clickhouse: {
364
+ url,
365
+ database,
366
+ username,
367
+ passwordEnv,
368
+ ...(namespace ? { namespace } : {}),
369
+ },
370
+ };
371
+ }
372
+ else {
373
+ answers.vectorStore = { provider: "lancedb" };
374
+ }
375
+ const embedDescriptions = await prompter.confirm({
376
+ message: "Embed chunk descriptions as well as code? (turn off for code-specialized embedders)",
377
+ defaultValue: readBoolean(indexing, "embedDescriptions") ?? DEFAULT_CONFIG.indexing.embedDescriptions ?? true,
378
+ });
379
+ if (embedDescriptions === undefined)
380
+ return undefined;
381
+ answers.indexing = { embedDescriptions };
382
+ const wantWatcher = await prompter.confirm({
383
+ message: "Run the background indexer automatically?",
384
+ defaultValue: readBoolean(autoIndex, "enabled") ?? DEFAULT_CONFIG.openCode.autoIndex?.enabled ?? false,
385
+ });
386
+ if (wantWatcher === undefined)
387
+ return undefined;
388
+ answers.openCode = { autoIndex: wantWatcher };
389
+ return answers;
390
+ }
391
+ /**
392
+ * Whether the caller passed any flag that should override the stored config.
393
+ *
394
+ * `setup` only rewrites configuration when the wizard ran, when a flag was
395
+ * supplied, or when no config exists yet.
396
+ */
397
+ export function hasExplicitSetupFlags(flags) {
398
+ const keys = [
399
+ "provider",
400
+ "baseUrl",
401
+ "apiKey",
402
+ "embeddingModel",
403
+ "descriptionModel",
404
+ "visionModel",
405
+ "decisionModel",
406
+ "description",
407
+ "vision",
408
+ "decision",
409
+ "reranking",
410
+ "shellGuard",
411
+ "memoryCapture",
412
+ "vectorStore",
413
+ ];
414
+ return keys.some((key) => flags[key] !== undefined);
415
+ }
416
+ /**
417
+ * Build answers from CLI flags plus the existing config, for non-interactive
418
+ * runs (`--yes`, CI, piped stdin).
419
+ *
420
+ * Only used when at least one explicit flag is present; otherwise `setup`
421
+ * leaves the stored configuration alone.
422
+ */
423
+ export function answersFromFlags(flags, existing) {
424
+ const embeddingSection = section(existing, "embedding");
425
+ const provider = flags.provider ?? readString(embeddingSection, "provider") ?? DEFAULT_CONFIG.embedding.provider;
426
+ const baseUrl = flags.baseUrl ??
427
+ readString(embeddingSection, "baseUrl") ??
428
+ (provider === "ollama" ? "http://127.0.0.1:11434/api" : defaultBaseUrl(provider));
429
+ const apiKey = flags.apiKey?.startsWith("env:")
430
+ ? process.env[flags.apiKey.slice(4)]
431
+ : flags.apiKey ?? readString(embeddingSection, "apiKey");
432
+ const configuredModel = readString(embeddingSection, "model");
433
+ const model = flags.embeddingModel ?? configuredModel ?? DEFAULT_CONFIG.embedding.model;
434
+ // A configured dimension belongs to the configured model *and* host. Keep
435
+ // it only when neither changes: carrying it to a different model would make
436
+ // the store reject the new vectors (see concepts/embedding-dimension-integrity).
437
+ const sameTarget = configuredModel !== undefined &&
438
+ configuredModel === model &&
439
+ provider === (readString(embeddingSection, "provider") ?? DEFAULT_CONFIG.embedding.provider) &&
440
+ baseUrl ===
441
+ (readString(embeddingSection, "baseUrl") ??
442
+ (provider === "ollama" ? "http://127.0.0.1:11434/api" : defaultBaseUrl(provider)));
443
+ const vectorDimension = sameTarget && typeof embeddingSection?.vectorDimension === "number"
444
+ ? embeddingSection.vectorDimension
445
+ : undefined;
446
+ const embedding = {
447
+ provider,
448
+ baseUrl,
449
+ ...(apiKey ? { apiKey } : {}),
450
+ model,
451
+ ...(vectorDimension ? { vectorDimension } : {}),
452
+ };
453
+ const descriptionSection = section(existing, "description");
454
+ const descriptionFlag = flags.description ?? (flags.descriptionModel ? true : undefined);
455
+ const chatAvailable = supportsChat(provider) || readString(descriptionSection, "provider") !== undefined;
456
+ // Only touch descriptions when asked, or when a fresh workspace gets a host
457
+ // that can actually serve chat completions.
458
+ const enableDescription = descriptionFlag === true ||
459
+ (descriptionFlag === undefined && descriptionSection === undefined && chatAvailable);
460
+ const description = enableDescription
461
+ ? {
462
+ provider: readString(descriptionSection, "provider") ?? provider,
463
+ baseUrl: readString(descriptionSection, "baseUrl") ?? baseUrl,
464
+ ...(readString(descriptionSection, "apiKey") ? { apiKey: readString(descriptionSection, "apiKey") } : {}),
465
+ model: flags.descriptionModel ??
466
+ readString(descriptionSection, "model") ??
467
+ DEFAULT_CONFIG.description?.model ??
468
+ "qwen2.5:3b",
469
+ }
470
+ : undefined;
471
+ const descriptionEnabled = descriptionFlag === false ? false : enableDescription ? true : undefined;
472
+ const visionSection = section(existing, "imageDescription");
473
+ const visionFlag = flags.vision ?? (flags.visionModel ? true : undefined);
474
+ const imageDescription = visionFlag === true && chatAvailable
475
+ ? {
476
+ provider: readString(visionSection, "provider") ?? provider,
477
+ baseUrl: readString(visionSection, "baseUrl") ?? baseUrl,
478
+ ...(readString(visionSection, "apiKey") ? { apiKey: readString(visionSection, "apiKey") } : {}),
479
+ model: flags.visionModel ??
480
+ readString(visionSection, "model") ??
481
+ DEFAULT_CONFIG.imageDescription?.model ??
482
+ "minicpm-v4.6:latest",
483
+ }
484
+ : undefined;
485
+ const imageDescriptionEnabled = visionFlag === false ? false : visionFlag === true ? true : undefined;
486
+ const decisionSection = section(existing, "decision");
487
+ const decisionFlag = flags.decision ?? (flags.decisionModel ? true : undefined);
488
+ let decision;
489
+ if (decisionFlag === true) {
490
+ decision = {
491
+ enabled: true,
492
+ baseUrl: readString(decisionSection, "baseUrl") ?? "http://127.0.0.1:11434/api",
493
+ model: flags.decisionModel ?? readString(decisionSection, "model") ?? DEFAULT_CONFIG.decision?.model ?? "tev1:4b",
494
+ routeBeforeAsking: readBoolean(decisionSection, "routeBeforeAsking") ?? false,
495
+ };
496
+ }
497
+ else if (decisionFlag === false) {
498
+ decision = { enabled: false };
499
+ }
500
+ const answers = {
501
+ embedding,
502
+ ...(descriptionEnabled !== undefined ? { descriptionEnabled } : {}),
503
+ ...(imageDescriptionEnabled !== undefined ? { imageDescriptionEnabled } : {}),
504
+ ...(description ? { description } : {}),
505
+ ...(imageDescription ? { imageDescription } : {}),
506
+ ...(decision ? { decision } : {}),
507
+ };
508
+ if (flags.reranking !== undefined) {
509
+ const rerankSection = section(existing, "reranking");
510
+ answers.reranking = flags.reranking
511
+ ? {
512
+ enabled: true,
513
+ baseUrl: readString(rerankSection, "baseUrl") ?? DEFAULT_CONFIG.reranking?.baseUrl ?? "http://127.0.0.1:8080/v1",
514
+ model: readString(rerankSection, "model") ?? DEFAULT_CONFIG.reranking?.model ?? "qwen3-reranker-0.6b",
515
+ }
516
+ : { enabled: false };
517
+ }
518
+ if (flags.shellGuard !== undefined) {
519
+ answers.shellGuard = { enabled: flags.shellGuard };
520
+ }
521
+ if (flags.memoryCapture !== undefined) {
522
+ answers.memory = {
523
+ passiveCapture: flags.memoryCapture,
524
+ promptEnforcement: flags.memoryCapture,
525
+ sessionEndExtraction: flags.memoryCapture,
526
+ };
527
+ }
528
+ if (flags.vectorStore) {
529
+ const clickhouseSection = section(section(existing, "vectorStore") ?? {}, "clickhouse");
530
+ answers.vectorStore =
531
+ flags.vectorStore === "clickhouse"
532
+ ? {
533
+ provider: "clickhouse",
534
+ clickhouse: {
535
+ url: flags.clickhouseUrl ?? readString(clickhouseSection, "url") ?? "http://localhost:8123",
536
+ database: flags.clickhouseDatabase ?? readString(clickhouseSection, "database") ?? "OpenCodeRAG",
537
+ username: flags.clickhouseUser ?? readString(clickhouseSection, "username") ?? "default",
538
+ passwordEnv: flags.clickhousePasswordEnv ??
539
+ readString(clickhouseSection, "passwordEnv") ??
540
+ "OPENCODERAG_CLICKHOUSE_PASSWORD",
541
+ ...(flags.clickhouseNamespace ?? readString(clickhouseSection, "namespace")
542
+ ? { namespace: flags.clickhouseNamespace ?? readString(clickhouseSection, "namespace") }
543
+ : {}),
544
+ },
545
+ }
546
+ : { provider: "lancedb" };
547
+ }
548
+ return answers;
549
+ }
550
+ /**
551
+ * Offer the one-question recommended setup.
552
+ *
553
+ * Returns `{ kind: "answers" }` when the user accepted the preset,
554
+ * `{ kind: "custom" }` when the full wizard should run instead, and
555
+ * `{ kind: "cancel" }` when the user aborted.
556
+ */
557
+ async function offerRecommendedSetup(prompter, options) {
558
+ const { existing, proxy } = options;
559
+ const embeddingSection = section(existing, "embedding");
560
+ const existingProvider = readString(embeddingSection, "provider");
561
+ // Non-Ollama setups are already deliberate; keep the detailed wizard.
562
+ if (existingProvider && existingProvider !== "ollama")
563
+ return { kind: "custom" };
564
+ const baseUrl = readString(embeddingSection, "baseUrl") ?? "http://127.0.0.1:11434/api";
565
+ console.log(`\n ${c.dim(`Checking Ollama at ${baseUrl}…`)}`);
566
+ const catalog = await fetchModelCatalog({ provider: "ollama", baseUrl, proxy });
567
+ if (!catalog.reachable) {
568
+ console.log(` ${c.warn("Ollama is not reachable.")} ${c.dim(ollamaInstallHint())}`);
569
+ console.log(` ${c.dim("Continuing with manual setup.")}`);
570
+ return { kind: "custom" };
571
+ }
572
+ const info = await detectOllamaBackend(catalog.baseUrl, proxy);
573
+ const preset = presetForBackend(info.backend);
574
+ console.log(`\n${c.heading("Recommended setup")} ${c.dim(`(${preset.label} — ${preset.description})`)}\n`);
575
+ for (const model of describePreset(preset, catalog)) {
576
+ console.log(` ${c.value(model)}`);
577
+ }
578
+ const accept = await prompter.confirm({
579
+ message: `Use this recommended ${preset.label} setup?`,
580
+ defaultValue: true,
581
+ });
582
+ if (accept === undefined)
583
+ return { kind: "cancel" };
584
+ if (!accept)
585
+ return { kind: "custom" };
586
+ const dimension = await probeEmbeddingDimension({
587
+ provider: "ollama",
588
+ baseUrl: catalog.baseUrl,
589
+ model: preset.embedding,
590
+ proxy,
591
+ });
592
+ // Re-running the preset for the same model/host must not discard a known
593
+ // dimension just because the probe failed (the model may be unloaded).
594
+ const configuredDimension = typeof embeddingSection?.vectorDimension === "number" ? embeddingSection.vectorDimension : undefined;
595
+ const sameModel = readString(embeddingSection, "model") === preset.embedding;
596
+ const sameHost = (readString(embeddingSection, "baseUrl") ?? "http://127.0.0.1:11434/api") === catalog.baseUrl;
597
+ const vectorDimension = dimension ?? (sameModel && sameHost ? configuredDimension : undefined);
598
+ if (dimension) {
599
+ console.log(`\n ${c.success("✓")} ${c.value(preset.embedding)} produces ${dimension}-dimensional vectors`);
600
+ }
601
+ else if (vectorDimension) {
602
+ console.log(`\n ${c.dim(`Kept the configured vector dimension (${vectorDimension}).`)}`);
603
+ }
604
+ const decisionSection = section(existing, "decision");
605
+ const decisionEnabled = readBoolean(decisionSection, "enabled") ?? false;
606
+ const decision = decisionEnabled
607
+ ? {
608
+ enabled: true,
609
+ baseUrl: readString(decisionSection, "baseUrl") ?? catalog.baseUrl,
610
+ model: readString(decisionSection, "model") ?? DEFAULT_CONFIG.decision?.model ?? "tev1:4b",
611
+ routeBeforeAsking: readBoolean(decisionSection, "routeBeforeAsking") ?? false,
612
+ }
613
+ : { enabled: false };
614
+ const answers = {
615
+ embedding: {
616
+ provider: "ollama",
617
+ baseUrl: catalog.baseUrl,
618
+ model: preset.embedding,
619
+ ...(vectorDimension ? { vectorDimension } : {}),
620
+ },
621
+ ...(preset.descriptionModel
622
+ ? {
623
+ description: {
624
+ provider: "ollama",
625
+ baseUrl: catalog.baseUrl,
626
+ model: preset.descriptionModel,
627
+ },
628
+ }
629
+ : {}),
630
+ descriptionEnabled: Boolean(preset.descriptionModel),
631
+ ...(preset.visionModel
632
+ ? {
633
+ imageDescription: {
634
+ provider: "ollama",
635
+ baseUrl: catalog.baseUrl,
636
+ model: preset.visionModel,
637
+ },
638
+ }
639
+ : {}),
640
+ imageDescriptionEnabled: Boolean(preset.visionModel),
641
+ decision,
642
+ recommended: true,
643
+ };
644
+ return { kind: "answers", answers };
645
+ }
646
+ /**
647
+ * Run the interactive wizard.
648
+ *
649
+ * @returns The collected answers, or `undefined` when the user cancelled or
650
+ * declined to apply the configuration.
651
+ */
652
+ export async function runSetupWizard(options) {
653
+ const { prompter, existing } = options;
654
+ const flags = options;
655
+ console.log(`\n${c.heading("OpenCodeRAG setup")}`);
656
+ const recommended = await offerRecommendedSetup(prompter, options);
657
+ if (recommended.kind === "cancel")
658
+ return undefined;
659
+ if (recommended.kind === "answers")
660
+ return recommended.answers;
661
+ console.log(`\n ${c.dim("Answer the questions below. Enter accepts the value in [brackets].")}\n`);
662
+ const primary = await askHost(prompter, {
663
+ message: "Which provider hosts your models?",
664
+ existing,
665
+ flags,
666
+ proxy: options.proxy,
667
+ requireEmbedding: false,
668
+ });
669
+ if (!primary)
670
+ return undefined;
671
+ let embeddingHost = primary;
672
+ if (!supportsEmbedding(primary.host.provider)) {
673
+ console.log(`\n ${c.warn(`${primary.host.provider} does not provide embeddings.`)} Choose a separate embedding host.`);
674
+ const separate = await askHost(prompter, {
675
+ message: "Embedding provider",
676
+ existing: {},
677
+ flags: { ...flags, provider: undefined, baseUrl: undefined, apiKey: undefined },
678
+ proxy: options.proxy,
679
+ requireEmbedding: true,
680
+ });
681
+ if (!separate)
682
+ return undefined;
683
+ embeddingHost = separate;
684
+ }
685
+ const embeddingModel = await pickModel(prompter, {
686
+ message: "Embedding model",
687
+ catalog: embeddingHost.catalog,
688
+ capability: "embedding",
689
+ defaultValue: flags.embeddingModel ??
690
+ readString(section(existing, "embedding"), "model") ??
691
+ DEFAULT_CONFIG.embedding.model,
692
+ });
693
+ if (embeddingModel === undefined)
694
+ return undefined;
695
+ const previousSection = section(existing, "embedding");
696
+ const previousDimension = previousSection?.vectorDimension;
697
+ const previousModel = readString(previousSection, "model");
698
+ const previousProvider = readString(previousSection, "provider");
699
+ const previousBaseUrl = readString(previousSection, "baseUrl");
700
+ const unchangedTarget = typeof previousDimension === "number" &&
701
+ previousModel === embeddingModel &&
702
+ (previousProvider === undefined || previousProvider === embeddingHost.host.provider) &&
703
+ (previousBaseUrl === undefined || previousBaseUrl === embeddingHost.host.baseUrl);
704
+ let vectorDimension;
705
+ if (embeddingHost.catalog.reachable) {
706
+ vectorDimension = await probeEmbeddingDimension({
707
+ provider: embeddingHost.host.provider,
708
+ baseUrl: embeddingHost.host.baseUrl,
709
+ model: embeddingModel,
710
+ apiKey: embeddingHost.host.apiKey,
711
+ proxy: options.proxy,
712
+ });
713
+ if (vectorDimension) {
714
+ console.log(` ${c.success("✓")} ${c.value(embeddingModel)} produces ${vectorDimension}-dimensional vectors`);
715
+ }
716
+ else if (unchangedTarget) {
717
+ vectorDimension = previousDimension;
718
+ console.log(` ${c.dim(`Kept the configured vector dimension (${vectorDimension}).`)}`);
719
+ }
720
+ else {
721
+ console.log(` ${c.warn("Could not probe the vector dimension.")} It will be detected on the first index run.`);
722
+ }
723
+ }
724
+ else if (unchangedTarget) {
725
+ // Offline reconfigure of the same target: keep the known dimension.
726
+ vectorDimension = previousDimension;
727
+ }
728
+ const embedding = {
729
+ provider: embeddingHost.host.provider,
730
+ baseUrl: embeddingHost.host.baseUrl,
731
+ ...(embeddingHost.host.apiKey ? { apiKey: embeddingHost.host.apiKey } : {}),
732
+ model: embeddingModel,
733
+ ...(vectorDimension ? { vectorDimension } : {}),
734
+ };
735
+ // ── Chat host (shared by description and vision) ──
736
+ const descriptionDefault = flags.description ??
737
+ (flags.descriptionModel ? true : undefined) ??
738
+ readBoolean(section(existing, "description"), "enabled") ??
739
+ (supportsChat(primary.host.provider) ? (DEFAULT_CONFIG.description?.enabled ?? true) : false);
740
+ const wantDescription = await prompter.confirm({
741
+ message: "Generate LLM descriptions for indexed code chunks?",
742
+ defaultValue: descriptionDefault,
743
+ });
744
+ if (wantDescription === undefined)
745
+ return undefined;
746
+ const visionDefault = flags.vision ??
747
+ (flags.visionModel ? true : undefined) ??
748
+ readBoolean(section(existing, "imageDescription"), "enabled") ??
749
+ false;
750
+ const wantVision = await prompter.confirm({
751
+ message: "Describe images with a vision model?",
752
+ defaultValue: visionDefault,
753
+ });
754
+ if (wantVision === undefined)
755
+ return undefined;
756
+ let chatHost = primary;
757
+ if ((wantDescription || wantVision) && !supportsChat(primary.host.provider)) {
758
+ console.log(`\n ${c.warn(`${primary.host.provider} cannot serve chat completions.`)} Choose a chat/vision host.`);
759
+ const separate = await askHost(prompter, {
760
+ message: "Chat/vision provider",
761
+ existing: {},
762
+ flags: { ...flags, provider: undefined, baseUrl: undefined, apiKey: undefined },
763
+ proxy: options.proxy,
764
+ requireChat: true,
765
+ });
766
+ if (!separate)
767
+ return undefined;
768
+ chatHost = separate;
769
+ }
770
+ let description;
771
+ if (wantDescription) {
772
+ const model = await pickModel(prompter, {
773
+ message: "Description model",
774
+ catalog: chatHost.catalog,
775
+ capability: "chat",
776
+ defaultValue: flags.descriptionModel ??
777
+ readString(section(existing, "description"), "model") ??
778
+ DEFAULT_CONFIG.description?.model,
779
+ });
780
+ if (model === undefined)
781
+ return undefined;
782
+ description = {
783
+ provider: chatHost.host.provider,
784
+ baseUrl: chatHost.host.baseUrl,
785
+ ...(chatHost.host.apiKey ? { apiKey: chatHost.host.apiKey } : {}),
786
+ model,
787
+ };
788
+ }
789
+ let imageDescription;
790
+ if (wantVision) {
791
+ const model = await pickModel(prompter, {
792
+ message: "Vision model",
793
+ catalog: chatHost.catalog,
794
+ capability: "vision",
795
+ defaultValue: flags.visionModel ??
796
+ readString(section(existing, "imageDescription"), "model") ??
797
+ DEFAULT_CONFIG.imageDescription?.model,
798
+ });
799
+ if (model === undefined)
800
+ return undefined;
801
+ imageDescription = {
802
+ provider: chatHost.host.provider,
803
+ baseUrl: chatHost.host.baseUrl,
804
+ ...(chatHost.host.apiKey ? { apiKey: chatHost.host.apiKey } : {}),
805
+ model,
806
+ };
807
+ }
808
+ // ── Decision model (Ollama only) ──
809
+ const decisionSection = section(existing, "decision");
810
+ const decisionDefault = flags.decision ??
811
+ (flags.decisionModel ? true : undefined) ??
812
+ readBoolean(decisionSection, "enabled") ??
813
+ DEFAULT_CONFIG.decision?.enabled ??
814
+ false;
815
+ const wantDecision = await prompter.confirm({
816
+ message: "Enable the local decision model (make_decision, tev1)?",
817
+ defaultValue: decisionDefault,
818
+ });
819
+ if (wantDecision === undefined)
820
+ return undefined;
821
+ let decision;
822
+ if (wantDecision) {
823
+ const knownOllama = [primary, embeddingHost, chatHost].find((host) => host.host.provider === "ollama");
824
+ let decisionBaseUrl = readString(decisionSection, "baseUrl") ??
825
+ knownOllama?.host.baseUrl ??
826
+ "http://127.0.0.1:11434/api";
827
+ if (!knownOllama) {
828
+ const typed = await prompter.text({
829
+ message: "Ollama base URL for the decision model",
830
+ defaultValue: decisionBaseUrl,
831
+ hint: "tev1 requires Ollama >= 0.35 and `ollama pull tev1:0.8b`",
832
+ });
833
+ if (typed === undefined)
834
+ return undefined;
835
+ decisionBaseUrl = typed;
836
+ }
837
+ const decisionModel = await prompter.select({
838
+ message: "Decision model",
839
+ options: [
840
+ { label: "tev1:0.8b", value: "tev1:0.8b", description: "Fastest, good default" },
841
+ { label: "tev1:4b", value: "tev1:4b", description: "More accurate, slower" },
842
+ { label: "tev1", value: "tev1", description: "Whichever tag is pulled" },
843
+ { label: "Type a model name…", value: "__custom__" },
844
+ ],
845
+ defaultIndex: 0,
846
+ });
847
+ if (decisionModel === undefined)
848
+ return undefined;
849
+ let resolvedDecisionModel = decisionModel;
850
+ if (decisionModel === "__custom__") {
851
+ const typed = await prompter.text({
852
+ message: "Decision model",
853
+ defaultValue: flags.decisionModel ?? readString(decisionSection, "model") ?? "tev1:0.8b",
854
+ });
855
+ if (typed === undefined)
856
+ return undefined;
857
+ resolvedDecisionModel = typed;
858
+ }
859
+ const routeBeforeAsking = await prompter.confirm({
860
+ message: "Let the agent route choices through make_decision before asking you?",
861
+ defaultValue: readBoolean(decisionSection, "routeBeforeAsking") ?? false,
862
+ });
863
+ if (routeBeforeAsking === undefined)
864
+ return undefined;
865
+ decision = {
866
+ enabled: true,
867
+ baseUrl: ollamaRoot(decisionBaseUrl) + "/api",
868
+ model: resolvedDecisionModel,
869
+ routeBeforeAsking,
870
+ };
871
+ }
872
+ else {
873
+ decision = { enabled: false };
874
+ }
875
+ // ── Advanced options ──
876
+ const advancedFlagsSet = flags.reranking !== undefined ||
877
+ flags.shellGuard !== undefined ||
878
+ flags.memoryCapture !== undefined ||
879
+ flags.vectorStore !== undefined;
880
+ const advanced = advancedFlagsSet || await prompter.confirm({
881
+ message: "Configure advanced options (reranking, shell guard, memory, vector store)?",
882
+ defaultValue: false,
883
+ });
884
+ if (advanced === undefined)
885
+ return undefined;
886
+ const advancedAnswers = advanced ? await askAdvanced(prompter, existing, flags) : undefined;
887
+ if (advancedAnswers === undefined && advanced)
888
+ return undefined;
889
+ const answers = {
890
+ embedding,
891
+ descriptionEnabled: wantDescription,
892
+ imageDescriptionEnabled: wantVision,
893
+ ...(description ? { description } : {}),
894
+ ...(imageDescription ? { imageDescription } : {}),
895
+ ...(decision ? { decision } : {}),
896
+ ...(advancedAnswers ?? {}),
897
+ };
898
+ printSummary(answers);
899
+ const apply = await prompter.confirm({ message: "Apply this configuration?", defaultValue: true });
900
+ if (apply === undefined)
901
+ return undefined;
902
+ return apply ? answers : undefined;
903
+ }
904
+ //# sourceMappingURL=flow.js.map