opencode-rag-plugin 2.12.0 → 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.
@@ -9,7 +9,10 @@
9
9
  import { DEFAULT_CONFIG } from "../../core/config.js";
10
10
  import { getProviderDefault, supportsChat, supportsEmbedding } from "../../core/provider-defaults.js";
11
11
  import { c } from "../format.js";
12
+ import { ollamaInstallHint } from "../ollama.js";
13
+ import { detectOllamaBackend } from "../commands/backend-detect.js";
12
14
  import { fetchModelCatalog, probeEmbeddingDimension, ollamaRoot, } from "./model-catalog.js";
15
+ import { describePreset, presetForBackend } from "./presets.js";
13
16
  const PROVIDERS = [
14
17
  {
15
18
  id: "ollama",
@@ -83,10 +86,15 @@ function printCatalogStatus(catalog) {
83
86
  console.log(` ${c.error("✗")} ${c.value(catalog.baseUrl)} — ${catalog.error ?? "unreachable"}`);
84
87
  }
85
88
  /** Ask for a provider + base URL + optional API key, then probe its models. */
86
- async function askHost(prompter, options) {
89
+ export async function askHost(prompter, options) {
87
90
  const { message, existing, flags } = options;
88
91
  const previous = section(existing, "embedding");
89
- const candidates = PROVIDERS.filter((entry) => (options.requireEmbedding ? entry.embedding : true) &&
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) &&
90
98
  (options.requireChat ? entry.chat : true));
91
99
  const defaultProvider = (flags.provider && candidates.some((entry) => entry.id === flags.provider) ? flags.provider : undefined) ??
92
100
  readString(previous, "provider") ??
@@ -141,6 +149,18 @@ async function askHost(prompter, options) {
141
149
  if (flagKey) {
142
150
  apiKey = flagKey;
143
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
+ }
144
164
  else if (existingKey && !existingKey.startsWith("env:")) {
145
165
  apiKey = existingKey;
146
166
  console.log(` ${c.dim("Using the API key already stored in the config.")}`);
@@ -148,7 +168,7 @@ async function askHost(prompter, options) {
148
168
  else if (envValue) {
149
169
  console.log(` ${c.dim(`Using ${envVar} from the environment (not written to the config).`)}`);
150
170
  }
151
- else if (entry.id === "openai" || entry.id === "cohere" || entry.id === "anthropic" || entry.id === "google") {
171
+ else if (entry.id !== "ollama") {
152
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.")}`);
153
173
  const typed = await prompter.password("API key (Enter to skip)");
154
174
  if (typed === undefined)
@@ -179,7 +199,7 @@ async function askHost(prompter, options) {
179
199
  * `__custom__` is always offered so a model that the provider does not list
180
200
  * (or a freshly pulled one) can still be typed.
181
201
  */
182
- async function pickModel(prompter, options) {
202
+ export async function pickModel(prompter, options) {
183
203
  const { catalog, capability } = options;
184
204
  const candidates = catalog.models.filter((model) => model.capabilities.includes(capability));
185
205
  // Keep the configured model selectable when the host lists models but did
@@ -409,12 +429,25 @@ export function answersFromFlags(flags, existing) {
409
429
  const apiKey = flags.apiKey?.startsWith("env:")
410
430
  ? process.env[flags.apiKey.slice(4)]
411
431
  : flags.apiKey ?? readString(embeddingSection, "apiKey");
412
- const vectorDimension = typeof embeddingSection?.vectorDimension === "number" ? embeddingSection.vectorDimension : undefined;
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;
413
446
  const embedding = {
414
447
  provider,
415
448
  baseUrl,
416
449
  ...(apiKey ? { apiKey } : {}),
417
- model: flags.embeddingModel ?? readString(embeddingSection, "model") ?? DEFAULT_CONFIG.embedding.model,
450
+ model,
418
451
  ...(vectorDimension ? { vectorDimension } : {}),
419
452
  };
420
453
  const descriptionSection = section(existing, "description");
@@ -514,6 +547,102 @@ export function answersFromFlags(flags, existing) {
514
547
  }
515
548
  return answers;
516
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
+ }
517
646
  /**
518
647
  * Run the interactive wizard.
519
648
  *
@@ -524,6 +653,11 @@ export async function runSetupWizard(options) {
524
653
  const { prompter, existing } = options;
525
654
  const flags = options;
526
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;
527
661
  console.log(`\n ${c.dim("Answer the questions below. Enter accepts the value in [brackets].")}\n`);
528
662
  const primary = await askHost(prompter, {
529
663
  message: "Which provider hosts your models?",
@@ -558,10 +692,17 @@ export async function runSetupWizard(options) {
558
692
  });
559
693
  if (embeddingModel === undefined)
560
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);
561
704
  let vectorDimension;
562
705
  if (embeddingHost.catalog.reachable) {
563
- const previousDimension = section(existing, "embedding")?.vectorDimension;
564
- const previousModel = readString(section(existing, "embedding"), "model");
565
706
  vectorDimension = await probeEmbeddingDimension({
566
707
  provider: embeddingHost.host.provider,
567
708
  baseUrl: embeddingHost.host.baseUrl,
@@ -572,14 +713,18 @@ export async function runSetupWizard(options) {
572
713
  if (vectorDimension) {
573
714
  console.log(` ${c.success("✓")} ${c.value(embeddingModel)} produces ${vectorDimension}-dimensional vectors`);
574
715
  }
575
- else if (typeof previousDimension === "number" && previousModel === embeddingModel) {
716
+ else if (unchangedTarget) {
576
717
  vectorDimension = previousDimension;
577
- console.log(` ${c.dim(`Kept the configured vector dimension (${previousDimension}).`)}`);
718
+ console.log(` ${c.dim(`Kept the configured vector dimension (${vectorDimension}).`)}`);
578
719
  }
579
720
  else {
580
721
  console.log(` ${c.warn("Could not probe the vector dimension.")} It will be detected on the first index run.`);
581
722
  }
582
723
  }
724
+ else if (unchangedTarget) {
725
+ // Offline reconfigure of the same target: keep the known dimension.
726
+ vectorDimension = previousDimension;
727
+ }
583
728
  const embedding = {
584
729
  provider: embeddingHost.host.provider,
585
730
  baseUrl: embeddingHost.host.baseUrl,
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @fileoverview Recommended model presets for one-question `setup`.
3
+ *
4
+ * The presets are the "press Enter" path: they map a detected Ollama backend
5
+ * (CPU vs GPU) to a small, well-tested model set so a first-time user does not
6
+ * have to choose four models. The full wizard remains available as "Custom
7
+ * setup" and via `--reconfigure`.
8
+ */
9
+ import type { ModelCatalog } from "./model-catalog.js";
10
+ /** Preset identifiers. */
11
+ export type PresetId = "ollama-cpu" | "ollama-gpu" | "openai";
12
+ /** One recommended model set. */
13
+ export interface Preset {
14
+ /** Stable identifier. */
15
+ id: PresetId;
16
+ /** Human-readable label. */
17
+ label: string;
18
+ /** One-line description shown in the prompt. */
19
+ description: string;
20
+ /** Provider that serves the models. */
21
+ provider: "ollama" | "openai";
22
+ /** Embedding model (required). */
23
+ embedding: string;
24
+ /** Description model, when the preset enables descriptions. */
25
+ descriptionModel?: string;
26
+ /** Vision model, when the preset enables image descriptions. */
27
+ visionModel?: string;
28
+ }
29
+ /** CPU-friendly Ollama preset (small models, fast on consumer hardware). */
30
+ export declare const OLLAMA_CPU_PRESET: Preset;
31
+ /** GPU Ollama preset (larger embedding model for better recall). */
32
+ export declare const OLLAMA_GPU_PRESET: Preset;
33
+ /** OpenAI preset (cloud; needs OPENAI_API_KEY). */
34
+ export declare const OPENAI_PRESET: Preset;
35
+ /** All presets, in display order. */
36
+ export declare const PRESETS: readonly Preset[];
37
+ /** Pick the Ollama preset matching a detected backend. */
38
+ export declare function presetForBackend(backend: "gpu" | "cpu" | "unreachable" | "unknown"): Preset;
39
+ /** A model from a preset plus whether the host already has it. */
40
+ export interface PresetModelStatus {
41
+ /** Model id. */
42
+ id: string;
43
+ /** Whether the host listed the model. */
44
+ installed: boolean;
45
+ }
46
+ /**
47
+ * List the preset's models with their installation status.
48
+ *
49
+ * An unreachable catalog reports every model as not installed (the caller
50
+ * only uses this for display after a successful probe, but being defensive
51
+ * keeps the helper usable from tests).
52
+ */
53
+ export declare function presetModelStatus(preset: Preset, catalog?: ModelCatalog): PresetModelStatus[];
54
+ /** Render the preset's model list for the confirmation prompt. */
55
+ export declare function describePreset(preset: Preset, catalog?: ModelCatalog): string[];
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @fileoverview Recommended model presets for one-question `setup`.
3
+ *
4
+ * The presets are the "press Enter" path: they map a detected Ollama backend
5
+ * (CPU vs GPU) to a small, well-tested model set so a first-time user does not
6
+ * have to choose four models. The full wizard remains available as "Custom
7
+ * setup" and via `--reconfigure`.
8
+ */
9
+ /** CPU-friendly Ollama preset (small models, fast on consumer hardware). */
10
+ export const OLLAMA_CPU_PRESET = {
11
+ id: "ollama-cpu",
12
+ label: "Ollama · CPU",
13
+ description: "Small models that stay fast without a dedicated GPU",
14
+ provider: "ollama",
15
+ embedding: "qwen3-embedding:0.6b",
16
+ descriptionModel: "qwen2.5:3b",
17
+ visionModel: "minicpm-v4.6",
18
+ };
19
+ /** GPU Ollama preset (larger embedding model for better recall). */
20
+ export const OLLAMA_GPU_PRESET = {
21
+ id: "ollama-gpu",
22
+ label: "Ollama · GPU",
23
+ description: "Larger embedding model for better recall",
24
+ provider: "ollama",
25
+ embedding: "qwen3-embedding:1.7b",
26
+ descriptionModel: "qwen2.5:3b",
27
+ visionModel: "minicpm-v4.6",
28
+ };
29
+ /** OpenAI preset (cloud; needs OPENAI_API_KEY). */
30
+ export const OPENAI_PRESET = {
31
+ id: "openai",
32
+ label: "OpenAI",
33
+ description: "Cloud models (requires OPENAI_API_KEY)",
34
+ provider: "openai",
35
+ embedding: "text-embedding-3-small",
36
+ descriptionModel: "gpt-4o-mini",
37
+ visionModel: "gpt-4o-mini",
38
+ };
39
+ /** All presets, in display order. */
40
+ export const PRESETS = [OLLAMA_CPU_PRESET, OLLAMA_GPU_PRESET, OPENAI_PRESET];
41
+ /** Pick the Ollama preset matching a detected backend. */
42
+ export function presetForBackend(backend) {
43
+ return backend === "gpu" ? OLLAMA_GPU_PRESET : OLLAMA_CPU_PRESET;
44
+ }
45
+ /**
46
+ * Whether a model id is present in the catalog.
47
+ *
48
+ * Ollama lists the implicit `:latest` tag explicitly, so `minicpm-v4.6` and
49
+ * `minicpm-v4.6:latest` are the same model for the "installed" display.
50
+ */
51
+ function isInstalled(installed, id) {
52
+ return installed.has(id) || installed.has(`${id.replace(/:latest$/i, "")}:latest`);
53
+ }
54
+ /**
55
+ * List the preset's models with their installation status.
56
+ *
57
+ * An unreachable catalog reports every model as not installed (the caller
58
+ * only uses this for display after a successful probe, but being defensive
59
+ * keeps the helper usable from tests).
60
+ */
61
+ export function presetModelStatus(preset, catalog) {
62
+ const installed = new Set(catalog?.models.map((model) => model.id) ?? []);
63
+ const ids = [preset.embedding, preset.descriptionModel, preset.visionModel].filter((id) => typeof id === "string" && id.length > 0);
64
+ return ids.map((id) => ({ id, installed: isInstalled(installed, id) }));
65
+ }
66
+ /** Render the preset's model list for the confirmation prompt. */
67
+ export function describePreset(preset, catalog) {
68
+ return presetModelStatus(preset, catalog).map((model) => `${model.id}${model.installed ? " (installed)" : " (will be pulled)"}`);
69
+ }
70
+ //# sourceMappingURL=presets.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @fileoverview Repair flow for models that fail the post-setup health check.
3
+ *
4
+ * `setup` probes the configured providers after applying the configuration.
5
+ * When a model answers with an error (expired key, wrong URL, unreachable
6
+ * server) the run must not stop at "Some providers are not reachable": this
7
+ * module asks whether to fix the section, then collects provider, base URL,
8
+ * API key and model (the same questions as the wizard) and writes the result
9
+ * into the config layer that already owns the section.
10
+ *
11
+ * The health check resolves API keys the same way the runtime does
12
+ * (`resolveApiKey`), so a key stored in OpenCode's auth store is used instead
13
+ * of the indexing section's key — an expired Zen key then reports itself as
14
+ * expired rather than as a generic 401.
15
+ */
16
+ import { type ProxyConfig } from "../../core/config.js";
17
+ import { type HealthCheckResult } from "../../embedder/health.js";
18
+ import type { Prompter } from "../prompt.js";
19
+ /** Options for {@link offerHealthRepairs}. */
20
+ export interface HealthRepairOptions {
21
+ /** Workspace root (used to reload the effective config and detect sections). */
22
+ cwd: string;
23
+ /** Existing workspace config path (`setup` already resolved it). */
24
+ workspaceConfigPath: string;
25
+ /** Machine-global config path. */
26
+ globalConfigPath: string;
27
+ prompter: Prompter;
28
+ /** Results of the health check that just printed its report. */
29
+ results: readonly HealthCheckResult[];
30
+ proxy?: ProxyConfig;
31
+ }
32
+ /**
33
+ * Pick the config file that owns a section.
34
+ *
35
+ * The section is repaired where the user already put it, so the write is
36
+ * visible immediately instead of being shadowed by another layer.
37
+ */
38
+ export declare function resolveRepairLayer(workspaceConfigPath: string, globalConfigPath: string, section: string, sub?: string): string;
39
+ /**
40
+ * Build the sparse patch for a repaired section.
41
+ *
42
+ * `apiKey: null` deletes a stale key (so an environment variable or the
43
+ * OpenCode auth store can take over); `vectorDimension: null` does the same
44
+ * for an embedding model that may have a different dimension.
45
+ */
46
+ export declare function buildRepairPatch(section: "embedding" | "description" | "imageDescription" | "reranking", sub: "onDemand" | undefined, choice: Record<string, unknown>): Record<string, unknown>;
47
+ /**
48
+ * Offer to repair every model that failed the connectivity check.
49
+ *
50
+ * Only runs for an interactive prompter: `--yes` / non-TTY runs keep the
51
+ * current report-and-continue behaviour. Returns the number of sections that
52
+ * were written.
53
+ */
54
+ export declare function offerHealthRepairs(options: HealthRepairOptions): Promise<number>;