opencode-rag-plugin 1.23.3 → 2.0.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.
package/dist/tui.js CHANGED
@@ -4,12 +4,20 @@
4
4
  */
5
5
  import { createElement, insert, setProp } from "@opentui/solid";
6
6
  import { readFileSync, existsSync, writeFileSync, unlinkSync } from "node:fs";
7
+ import { createRequire } from "node:module";
7
8
  import { dirname, join, resolve } from "node:path";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { loadRuntimeOverrides, saveRuntimeOverride } from "./core/runtime-overrides.js";
10
11
  import { PROVIDER_DEFAULTS } from "./core/provider-defaults.js";
11
12
  import { loadConfig, updateConfigValue } from "./core/config.js";
12
13
  import { setPendingRagInjection } from "./core/rag-injection-flag.js";
14
+ /**
15
+ * Lazy CommonJS require — this file is ESM ("type": "module"), so a bare
16
+ * `require()` throws ReferenceError. Used by `readTokenStats` to keep
17
+ * `./eval/storage.js` out of the TUI startup path (same pattern as
18
+ * `src/eval/token-counter.ts`).
19
+ */
20
+ const _require = createRequire(import.meta.url);
13
21
  /** Cached plugin version string from package.json. */
14
22
  let _version;
15
23
  /** Read the plugin version from package.json, caching the result. */
@@ -612,424 +620,365 @@ function buildSettingCategories(cfg, ro, providers) {
612
620
  },
613
621
  ];
614
622
  }
623
+ /** Map a V2 ResolvedTheme onto the legacy `{accent,text,textMuted}` shape `renderSidebar` expects. */
624
+ function v2Theme(theme) {
625
+ const t = theme;
626
+ return {
627
+ accent: t?.accent ?? t?.primary?.base ?? t?.primary ?? t?.border?.accent ?? "#7c9aff",
628
+ text: t?.text?.base ?? t?.text ?? t?.foreground ?? "#cdd6f4",
629
+ textMuted: t?.text?.muted ?? t?.text?.dim ?? t?.muted ?? t?.subtle ?? "#6c7086",
630
+ };
631
+ }
632
+ /** Translate a V1 keybinding string (`ctrl+enter`) to V2 key syntax (`ctrl+return`). */
633
+ function v2Bind(key) {
634
+ return key.replace(/\benter\b/g, "return");
635
+ }
636
+ /** Read token usage statistics from eval session logs (shared by the V2 path). */
637
+ function readTokenStats(worktree) {
638
+ try {
639
+ const configPath = getConfigPath(worktree);
640
+ if (!configPath)
641
+ return undefined;
642
+ const cfg = loadConfig(configPath);
643
+ const vs = cfg.vectorStore;
644
+ const storeRelPath = vs?.path ?? ".opencode/rag_db";
645
+ const storePath = resolve(worktree, storeRelPath);
646
+ const { listSessions } = _require("./eval/storage.js");
647
+ const sessions = listSessions(storePath);
648
+ if (sessions.length === 0)
649
+ return undefined;
650
+ const latest = sessions[0];
651
+ return {
652
+ inputTokens: latest.totalTokens.input,
653
+ ragCtxTokens: latest.ragContextTokens,
654
+ reads: Object.entries(latest.toolCallCounts).filter(([k]) => k === "read").reduce((s, [, v]) => s + v, 0),
655
+ ragTools: latest.ragToolCalls,
656
+ queries: latest.messageCount,
657
+ };
658
+ }
659
+ catch {
660
+ return undefined;
661
+ }
662
+ }
663
+ /** Rebuild legacy sdk `Provider` shapes (model picker / base URL / API key) from V2 data domains. */
664
+ function v2LegacyProviders(context) {
665
+ try {
666
+ const providers = (context.data?.provider?.list?.() ?? []);
667
+ const models = (context.data?.model?.list?.() ?? []);
668
+ return providers.map((p) => {
669
+ const id = String(p.id ?? "");
670
+ const modelMap = {};
671
+ for (const m of models) {
672
+ if ((m.providerID ?? "") !== id)
673
+ continue;
674
+ const modelId = String(m.modelID ?? m.id ?? "");
675
+ if (modelId)
676
+ modelMap[modelId] = { name: m.name };
677
+ }
678
+ return {
679
+ id,
680
+ name: p.name ?? id,
681
+ models: modelMap,
682
+ options: { baseURL: p.settings?.baseURL ?? p.options?.baseURL, apiKey: p.options?.apiKey },
683
+ };
684
+ });
685
+ }
686
+ catch {
687
+ return [];
688
+ }
689
+ }
615
690
  /**
616
- * Open the interactive settings dialog for OpenCodeRAG configuration.
617
- * Displays a cascading menu of categories → settings → value editors.
691
+ * V2 settings dialog — promise-based port of {@link openSettingsDialog}
692
+ * (category menu → setting menu → value editors) onto `context.ui.dialog`.
618
693
  */
619
- async function openSettingsDialog(api) {
620
- const worktree = api.state.path.worktree;
621
- if (!worktree)
694
+ async function openSettingsDialogV2(context, worktree, providers, onSettingsChanged) {
695
+ const ui = context.ui;
696
+ if (!ui)
622
697
  return;
698
+ const { dialog, toast } = ui;
699
+ const settingsToast = (variant, message) => toast.show({ variant, title: "Settings", message });
623
700
  const configPath = getConfigPath(worktree);
624
701
  if (!configPath) {
625
- api.ui.toast({ variant: "error", title: "Settings", message: "No config file found" });
702
+ settingsToast("error", "No config file found");
626
703
  return;
627
704
  }
628
705
  const cfgRaw = readJsonFile(configPath);
629
706
  if (!cfgRaw) {
630
- api.ui.toast({ variant: "error", title: "Settings", message: "Cannot read config" });
707
+ settingsToast("error", "Cannot read config");
631
708
  return;
632
709
  }
633
710
  const cfg = cfgRaw;
634
711
  const vs = cfg.vectorStore;
635
712
  const storeRelPath = vs?.path ?? ".opencode/rag_db";
636
713
  const storePath = resolve(worktree, storeRelPath);
637
- const providers = api.state.provider;
638
- function getCurrentOverrides() {
639
- return loadRuntimeOverrides(storePath);
640
- }
641
- function showCategoryMenu() {
642
- const ro = getCurrentOverrides();
643
- const cats = buildSettingCategories(cfg, ro, providers);
644
- const options = [
645
- ...cats.map((c) => ({
646
- title: c.label,
647
- value: c.id,
648
- description: c.description,
649
- })),
650
- { title: "Done", value: "__done__", description: "Close settings" },
651
- ];
652
- api.ui.dialog.replace(() => api.ui.DialogSelect({
714
+ const refreshCats = () => buildSettingCategories(cfg, loadRuntimeOverrides(storePath), providers);
715
+ const warnReindex = (path) => {
716
+ if (path[0] === "indexing" || path[0] === "chunking")
717
+ settingsToast("warning", "Chunking changed. Re-index required.");
718
+ };
719
+ categoryLoop: for (;;) {
720
+ const cats = refreshCats();
721
+ const catId = await dialog.select({
653
722
  title: "OpenCodeRAG Settings",
654
723
  placeholder: "Select a category",
655
- options,
656
- onSelect: (option) => {
657
- if (option.value === "__done__") {
658
- api.ui.dialog.clear();
659
- return;
660
- }
661
- const cat = cats.find((c) => c.id === option.value);
662
- if (cat)
663
- showSettingMenu(cat);
664
- },
665
- }));
666
- }
667
- function showSettingMenu(cat) {
668
- const options = [
669
- ...cat.entries.map((s) => ({
670
- title: `${s.label}: ${s.type === "boolean" ? (s.currentValue ? "Yes" : "No") : s.type === "json" ? JSON.stringify(s.currentValue) : String(s.currentValue)}`,
671
- value: s.path.join("."),
672
- description: s.options ? "Select to open model picker" : (s.type === "boolean" ? "Select to toggle" : "Select to edit"),
673
- })),
674
- { title: "\u2190 Back", value: "__back__", description: "Return to categories" },
675
- ];
676
- api.ui.dialog.replace(() => api.ui.DialogSelect({
677
- title: cat.label,
678
- placeholder: "Select a setting",
679
- options,
680
- onSelect: (option) => {
681
- if (option.value === "__back__") {
682
- showCategoryMenu();
683
- return;
684
- }
685
- const entry = cat.entries.find((s) => s.path.join(".") === option.value);
686
- if (!entry)
687
- return;
688
- if (entry.options) {
689
- showModelPicker(entry, cat);
690
- }
691
- else if (entry.type === "boolean") {
692
- const newVal = !entry.currentValue;
693
- saveRuntimeOverride(storePath, entry.path, newVal);
694
- updateConfigValue(configPath, entry.path, newVal);
695
- api.ui.toast({
696
- variant: "success",
697
- title: "Settings",
698
- message: `${entry.label}: ${newVal ? "Yes" : "No"}`,
699
- });
700
- if (entry.path[0] === "indexing" || entry.path[0] === "chunking") {
701
- api.ui.toast({ variant: "warning", title: "Settings", message: "Chunking changed. Re-index required." });
702
- }
703
- if (entry.path.join(".") === "openCode.autoIndex.enabled") {
704
- syncWatcherStatusFile(storePath, newVal);
705
- api.ui.toast({ variant: "warning", title: "Settings", message: "Watcher changes take effect after an OpenCode restart" });
706
- }
707
- entry.currentValue = newVal;
708
- api.onSettingsChanged?.();
709
- showSettingMenu(cat);
710
- }
711
- else if (entry.type === "number") {
712
- api.ui.dialog.replace(() => api.ui.DialogPrompt({
713
- title: `Edit ${entry.label}`,
714
- placeholder: "Enter new value",
715
- value: String(entry.currentValue),
716
- onConfirm: (input) => {
717
- const num = parseFloat(input);
718
- if (!isNaN(num)) {
719
- saveRuntimeOverride(storePath, entry.path, num);
720
- updateConfigValue(configPath, entry.path, num);
721
- api.ui.toast({
722
- variant: "success",
723
- title: "Settings",
724
- message: `${entry.label}: ${num}`,
725
- });
726
- if (entry.path[0] === "indexing" || entry.path[0] === "chunking") {
727
- api.ui.toast({ variant: "warning", title: "Settings", message: "Chunking changed. Re-index required." });
728
- }
729
- entry.currentValue = num;
730
- api.onSettingsChanged?.();
731
- }
732
- showSettingMenu(cat);
733
- },
734
- onCancel: () => {
735
- showSettingMenu(cat);
736
- },
737
- }));
738
- }
739
- else if (entry.type === "json") {
740
- api.ui.dialog.replace(() => api.ui.DialogPrompt({
741
- title: `Edit ${entry.label}`,
742
- placeholder: "JSON",
743
- value: JSON.stringify(entry.currentValue, null, 2),
744
- onConfirm: (input) => {
745
- try {
746
- const parsed = JSON.parse(input);
747
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
748
- api.ui.toast({ variant: "error", title: "Settings", message: "Value must be a JSON object" });
749
- showSettingMenu(cat);
750
- return;
751
- }
752
- saveRuntimeOverride(storePath, entry.path, parsed);
753
- updateConfigValue(configPath, entry.path, parsed);
754
- api.ui.toast({
755
- variant: "success",
756
- title: "Settings",
757
- message: `${entry.label}: updated`,
758
- });
759
- if (entry.path[0] === "indexing" || entry.path[0] === "chunking") {
760
- api.ui.toast({ variant: "warning", title: "Settings", message: "Chunking changed. Re-index required." });
761
- }
762
- entry.currentValue = parsed;
763
- api.onSettingsChanged?.();
764
- }
765
- catch {
766
- api.ui.toast({ variant: "error", title: "Settings", message: "Invalid JSON" });
767
- }
768
- showSettingMenu(cat);
769
- },
770
- onCancel: () => {
771
- showSettingMenu(cat);
772
- },
773
- }));
774
- }
775
- else {
776
- api.ui.dialog.replace(() => api.ui.DialogPrompt({
777
- title: `Edit ${entry.label}`,
778
- placeholder: "Enter new value",
779
- value: String(entry.currentValue),
780
- onConfirm: (input) => {
781
- saveRuntimeOverride(storePath, entry.path, input);
782
- updateConfigValue(configPath, entry.path, input);
783
- api.ui.toast({
784
- variant: "success",
785
- title: "Settings",
786
- message: `${entry.label}: ${input}`,
787
- });
788
- entry.currentValue = input;
789
- api.onSettingsChanged?.();
790
- showSettingMenu(cat);
791
- },
792
- onCancel: () => {
793
- showSettingMenu(cat);
794
- },
795
- }));
796
- }
797
- },
798
- }));
799
- }
800
- function showModelPicker(entry, cat) {
801
- api.ui.dialog.replace(() => api.ui.DialogSelect({
802
- title: `Select ${entry.label}`,
803
- placeholder: "Search models\u2026",
804
- options: entry.options ?? [],
805
- onSelect: (option) => {
806
- if (option.value === "__custom__") {
807
- api.ui.dialog.replace(() => api.ui.DialogPrompt({
724
+ options: [
725
+ ...cats.map((c) => ({ title: c.label, value: c.id, description: c.description })),
726
+ { title: "Done", value: "__done__", description: "Close settings" },
727
+ ],
728
+ });
729
+ if (!catId || catId === "__done__")
730
+ return;
731
+ const cat = cats.find((c) => c.id === catId);
732
+ if (!cat)
733
+ continue;
734
+ settingLoop: for (;;) {
735
+ // Rebuild so toggled values reflect immediately (matches the V1 dialog).
736
+ const fresh = refreshCats().find((c) => c.id === cat.id) ?? cat;
737
+ const picked = await dialog.select({
738
+ title: fresh.label,
739
+ placeholder: "Select a setting",
740
+ options: [
741
+ ...fresh.entries.map((s) => ({
742
+ title: `${s.label}: ${s.type === "boolean" ? (s.currentValue ? "Yes" : "No") : s.type === "json" ? JSON.stringify(s.currentValue) : String(s.currentValue)}`,
743
+ value: s.path.join("."),
744
+ description: s.options ? "Select to open model picker" : s.type === "boolean" ? "Select to toggle" : "Select to edit",
745
+ })),
746
+ { title: "\u2190 Back", value: "__back__", description: "Return to categories" },
747
+ ],
748
+ });
749
+ if (!picked || picked === "__back__")
750
+ continue categoryLoop;
751
+ const entry = fresh.entries.find((s) => s.path.join(".") === picked);
752
+ if (!entry)
753
+ continue;
754
+ if (entry.options) {
755
+ const modelPick = await dialog.select({
756
+ title: `Select ${entry.label}`,
757
+ placeholder: "Search models\u2026",
758
+ options: entry.options,
759
+ });
760
+ if (!modelPick)
761
+ continue;
762
+ let value = modelPick;
763
+ if (modelPick === "__custom__") {
764
+ const custom = await dialog.prompt({
808
765
  title: `Custom ${entry.label}`,
809
766
  placeholder: "e.g. ollama/my-model or openai/custom-model",
810
767
  value: typeof entry.currentValue === "string" ? entry.currentValue : "",
811
- onConfirm: (input) => {
812
- const saved = saveModelSelection(storePath, configPath, input, entry.path, providers);
813
- if (saved) {
814
- entry.currentValue = saved;
815
- }
816
- else if (input) {
817
- saveRuntimeOverride(storePath, entry.path, input);
818
- updateConfigValue(configPath, entry.path, input);
819
- entry.currentValue = input;
820
- }
821
- api.onSettingsChanged?.();
822
- showSettingMenu(cat);
823
- },
824
- onCancel: () => showSettingMenu(cat),
825
- }));
826
- return;
768
+ });
769
+ if (custom === undefined)
770
+ continue;
771
+ value = custom;
827
772
  }
828
- const saved = saveModelSelection(storePath, configPath, option.value, entry.path, providers);
773
+ const saved = saveModelSelection(storePath, configPath, value, entry.path, providers);
829
774
  if (saved) {
830
775
  entry.currentValue = saved;
831
- api.ui.toast({
832
- variant: "success",
833
- title: "Settings",
834
- message: `${entry.label}: ${saved}`,
835
- });
836
- const isEmbedding = entry.path[0] === "embedding";
837
- if (isEmbedding) {
838
- api.ui.toast({
839
- variant: "warning",
840
- title: "Settings",
841
- message: "Embedding changed. Re-index may be required. Restart OpenCode for changes.",
842
- });
776
+ settingsToast("success", `${entry.label}: ${saved}`);
777
+ if (entry.path[0] === "embedding") {
778
+ settingsToast("warning", "Embedding changed. Re-index may be required. Restart OpenCode for changes.");
843
779
  }
844
- api.onSettingsChanged?.();
845
780
  }
846
- showSettingMenu(cat);
847
- },
848
- }));
849
- }
850
- showCategoryMenu();
851
- }
852
- // ── Plugin export ──────────────────────────────────────────────────
853
- /**
854
- * The OpenCodeRAG TUI plugin module.
855
- * Registers sidebar panels, keybindings, and the settings dialog with OpenCode's
856
- * terminal UI framework.
857
- */
858
- const plugin = {
859
- id: `${PLUGIN_NAME}:tui`,
860
- tui: async (api, _options, meta) => {
861
- const version = meta.version ?? getVersion();
862
- let cachedStatus = DEFAULT_STATUS;
863
- let lastRefresh = 0;
864
- const REFRESH_INTERVAL_MS = Number(process.env.OPENCODE_RAG_TUI_REFRESH_MS) || 30000;
865
- // Load tui config for keybinding display
866
- let tuiConfig;
867
- const worktree = api.state.path.worktree;
868
- if (worktree) {
869
- const configPath = getConfigPath(worktree);
870
- if (configPath) {
871
- try {
872
- const cfg = loadConfig(configPath);
873
- tuiConfig = cfg.tui;
874
- }
875
- catch {
876
- // use defaults
781
+ else if (value) {
782
+ saveRuntimeOverride(storePath, entry.path, value);
783
+ updateConfigValue(configPath, entry.path, value);
784
+ entry.currentValue = value;
877
785
  }
786
+ onSettingsChanged?.();
787
+ continue;
878
788
  }
879
- }
880
- /** Refresh the cached RAG status from disk. */
881
- function refreshStatus() {
882
- const wt = api.state.path.worktree;
883
- if (wt) {
884
- cachedStatus = loadRagStatus(wt);
885
- lastRefresh = Date.now();
886
- }
887
- }
888
- refreshStatus();
889
- /** Load token usage statistics from eval session logs. */
890
- function loadTokenStats() {
891
- try {
892
- const wt = api.state.path.worktree;
893
- if (!wt)
894
- return undefined;
895
- const configPath = getConfigPath(wt);
896
- if (!configPath)
897
- return undefined;
898
- const cfg = loadConfig(configPath);
899
- const vs = cfg.vectorStore;
900
- const storeRelPath = vs?.path ?? ".opencode/rag_db";
901
- const storePath = resolve(wt, storeRelPath);
902
- const { listSessions } = require("./eval/storage.js");
903
- const sessions = listSessions(storePath);
904
- if (sessions.length === 0)
905
- return undefined;
906
- const latest = sessions[0];
907
- return {
908
- inputTokens: latest.totalTokens.input,
909
- ragCtxTokens: latest.ragContextTokens,
910
- reads: Object.entries(latest.toolCallCounts).filter(([k]) => k === "read").reduce((s, [, v]) => s + v, 0),
911
- ragTools: latest.ragToolCalls,
912
- queries: latest.messageCount,
913
- };
789
+ if (entry.type === "boolean") {
790
+ const newVal = !entry.currentValue;
791
+ saveRuntimeOverride(storePath, entry.path, newVal);
792
+ updateConfigValue(configPath, entry.path, newVal);
793
+ settingsToast("success", `${entry.label}: ${newVal ? "Yes" : "No"}`);
794
+ warnReindex(entry.path);
795
+ if (entry.path.join(".") === "openCode.autoIndex.enabled") {
796
+ syncWatcherStatusFile(storePath, newVal);
797
+ settingsToast("warning", "Watcher changes take effect after an OpenCode restart");
798
+ }
799
+ entry.currentValue = newVal;
800
+ onSettingsChanged?.();
801
+ continue;
914
802
  }
915
- catch {
916
- return undefined;
803
+ const raw = await dialog.prompt({
804
+ title: `Edit ${entry.label}`,
805
+ placeholder: entry.type === "json" ? "JSON" : "Enter new value",
806
+ value: entry.type === "json" ? JSON.stringify(entry.currentValue, null, 2) : String(entry.currentValue),
807
+ });
808
+ if (raw === undefined)
809
+ continue;
810
+ if (entry.type === "number") {
811
+ const num = parseFloat(raw);
812
+ if (isNaN(num)) {
813
+ settingsToast("error", "Enter a valid number");
814
+ continue;
815
+ }
816
+ saveRuntimeOverride(storePath, entry.path, num);
817
+ updateConfigValue(configPath, entry.path, num);
818
+ settingsToast("success", `${entry.label}: ${num}`);
819
+ warnReindex(entry.path);
820
+ entry.currentValue = num;
821
+ onSettingsChanged?.();
917
822
  }
918
- }
919
- // Register sidebar slot
920
- api.slots.register({
921
- order: 900,
922
- slots: {
923
- sidebar_content() {
924
- if (Date.now() - lastRefresh > REFRESH_INTERVAL_MS) {
925
- refreshStatus();
823
+ else if (entry.type === "json") {
824
+ try {
825
+ const parsed = JSON.parse(raw);
826
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
827
+ settingsToast("error", "Value must be a JSON object");
828
+ continue;
926
829
  }
927
- const tokenStats = loadTokenStats();
928
- return renderSidebar(api.theme.current, version, cachedStatus, tuiConfig, tokenStats);
929
- },
930
- },
931
- });
932
- // Register prompt slots — return null to let host render its default prompt.
933
- api.slots.register({
934
- order: 901,
935
- slots: {
936
- session_prompt() {
937
- return null;
938
- },
939
- home_prompt() {
940
- return null;
941
- },
942
- },
943
- });
944
- // Compute storePath for flag-based IPC with server plugin
945
- let flagStorePath;
946
- const worktreeForFlag = api.state.path.worktree;
947
- if (worktreeForFlag) {
948
- try {
949
- const flagConfigPath = getConfigPath(worktreeForFlag);
950
- if (flagConfigPath) {
951
- const flagCfg = loadConfig(flagConfigPath);
952
- const vs = flagCfg.vectorStore;
953
- const storeRelPath = vs?.path ?? ".opencode/rag_db";
954
- flagStorePath = resolve(worktreeForFlag, storeRelPath);
830
+ saveRuntimeOverride(storePath, entry.path, parsed);
831
+ updateConfigValue(configPath, entry.path, parsed);
832
+ settingsToast("success", `${entry.label}: updated`);
833
+ warnReindex(entry.path);
834
+ entry.currentValue = parsed;
835
+ onSettingsChanged?.();
836
+ }
837
+ catch {
838
+ settingsToast("error", "Invalid JSON");
955
839
  }
956
840
  }
957
- catch {
958
- // ignore
841
+ else {
842
+ saveRuntimeOverride(storePath, entry.path, raw);
843
+ updateConfigValue(configPath, entry.path, raw);
844
+ settingsToast("success", `${entry.label}: ${raw}`);
845
+ entry.currentValue = raw;
846
+ onSettingsChanged?.();
959
847
  }
960
848
  }
961
- // Register keybinding for settings dialog (configurable)
849
+ }
850
+ }
851
+ /**
852
+ * OpenCode V2 entrypoint — satisfies the V2 default-export schema
853
+ * (`{id, setup}`), which the server-role loader validates (OpenCode ≥ 2.x
854
+ * rejects `{id, tui}`-only modules with `err_*` "Plugin must export a default
855
+ * definition with an id and an effect or setup function").
856
+ *
857
+ * The server role calls this with a server context (no `ui`/`keymap`) → no-op.
858
+ * The TUI role calls it with the V2 TUI context → registers the sidebar slot,
859
+ * keybindings, and the settings dialog. Returns a cleanup that unclaims the slot.
860
+ */
861
+ async function setup(context) {
862
+ const ui = context.ui;
863
+ const keymap = context.keymap;
864
+ if (!ui?.slot || !keymap)
865
+ return undefined; // server-role load: nothing to register
866
+ const version = context.app?.version ?? getVersion();
867
+ const worktree = context.location?.directory;
868
+ let cachedStatus = DEFAULT_STATUS;
869
+ let lastRefresh = 0;
870
+ const REFRESH_INTERVAL_MS = Number(process.env.OPENCODE_RAG_TUI_REFRESH_MS) || 30000;
871
+ let tuiConfig;
872
+ const tuiConfigPath = worktree ? getConfigPath(worktree) : undefined;
873
+ if (tuiConfigPath) {
962
874
  try {
963
- const settingsKey = tuiConfig?.settingsKeybinding ?? "ctrl+shift+r";
964
- api.keymap.registerLayer({
965
- bindings: [{ key: settingsKey, cmd: "opencode-rag:settings" }],
966
- commands: [
967
- {
968
- name: "opencode-rag:settings",
969
- run: () => {
970
- openSettingsDialog({
971
- ui: api.ui,
972
- state: api.state,
973
- onSettingsChanged: () => {
974
- refreshStatus();
975
- },
976
- });
977
- return undefined;
978
- },
979
- },
980
- ],
981
- });
875
+ tuiConfig = loadConfig(tuiConfigPath).tui;
876
+ }
877
+ catch {
878
+ // use defaults
982
879
  }
983
- catch (err) {
984
- // Keymap registration may fail in older OpenCode versions; silently skip
880
+ }
881
+ /** Refresh the cached RAG status from disk. */
882
+ function refreshStatus() {
883
+ if (worktree) {
884
+ cachedStatus = loadRagStatus(worktree);
885
+ lastRefresh = Date.now();
985
886
  }
986
- // Register keybinding for "Add File List" (configurable)
887
+ }
888
+ refreshStatus();
889
+ // Register sidebar slot (V2 slot tree; the V1 prompt slots are unnecessary
890
+ // here — not claiming them leaves the host's default prompt intact).
891
+ const unclaimSidebar = ui.slot({
892
+ append: "sidebar.content",
893
+ render: () => {
894
+ if (Date.now() - lastRefresh > REFRESH_INTERVAL_MS)
895
+ refreshStatus();
896
+ const tokenStats = worktree ? readTokenStats(worktree) : undefined;
897
+ return renderSidebar(v2Theme(context.theme), version, cachedStatus, tuiConfig, tokenStats);
898
+ },
899
+ });
900
+ // Compute storePath for flag-based IPC with the server plugin.
901
+ let flagStorePath;
902
+ if (worktree) {
987
903
  try {
988
- const fileListKey = tuiConfig?.fileListKeybinding ?? "ctrl+enter";
989
- api.keymap.registerLayer({
990
- priority: 1000,
991
- bindings: [{ key: fileListKey, cmd: "opencode-rag:show-file-list" }],
992
- commands: [
993
- {
994
- name: "opencode-rag:show-file-list",
995
- run: () => {
996
- if (flagStorePath) {
997
- setPendingRagInjection(flagStorePath, "files");
998
- setTimeout(() => { api.keymap.dispatchCommand("prompt.submit"); }, 0);
999
- }
1000
- return undefined;
1001
- },
1002
- },
1003
- ],
1004
- });
904
+ const flagConfigPath = getConfigPath(worktree);
905
+ if (flagConfigPath) {
906
+ const flagCfg = loadConfig(flagConfigPath);
907
+ const vs = flagCfg.vectorStore;
908
+ const storeRelPath = vs?.path ?? ".opencode/rag_db";
909
+ flagStorePath = resolve(worktree, storeRelPath);
910
+ }
1005
911
  }
1006
- catch (err) {
1007
- // Keymap registration may fail in older OpenCode versions; silently skip
912
+ catch {
913
+ // ignore
1008
914
  }
1009
- // Register keybinding for "Add RAG Chunks" (configurable)
1010
- try {
1011
- const chunksKey = tuiConfig?.chunksKeybinding ?? "ctrl+alt+enter";
1012
- api.keymap.registerLayer({
1013
- priority: 1000,
1014
- bindings: [{ key: chunksKey, cmd: "opencode-rag:add-chunks" }],
1015
- commands: [
1016
- {
1017
- name: "opencode-rag:add-chunks",
1018
- run: () => {
1019
- if (flagStorePath) {
1020
- setPendingRagInjection(flagStorePath, "chunks");
1021
- setTimeout(() => { api.keymap.dispatchCommand("prompt.submit"); }, 0);
1022
- }
1023
- return undefined;
1024
- },
915
+ }
916
+ const settingsKey = tuiConfig?.settingsKeybinding ?? "ctrl+shift+r";
917
+ const fileListKey = tuiConfig?.fileListKeybinding ?? "ctrl+enter";
918
+ const chunksKey = tuiConfig?.chunksKeybinding ?? "ctrl+alt+enter";
919
+ try {
920
+ keymap.layer(() => ({
921
+ mode: "global",
922
+ priority: 1000,
923
+ commands: [
924
+ {
925
+ id: "opencode-rag:settings",
926
+ title: "OpenCodeRAG Settings",
927
+ bind: v2Bind(settingsKey),
928
+ run: () => {
929
+ if (worktree) {
930
+ void openSettingsDialogV2(context, worktree, v2LegacyProviders(context), () => refreshStatus());
931
+ }
1025
932
  },
1026
- ],
1027
- });
933
+ },
934
+ {
935
+ id: "opencode-rag:show-file-list",
936
+ title: "Add File List",
937
+ bind: v2Bind(fileListKey),
938
+ run: () => {
939
+ if (flagStorePath) {
940
+ setPendingRagInjection(flagStorePath, "files");
941
+ setTimeout(() => keymap.dispatch("prompt.submit"), 0);
942
+ }
943
+ },
944
+ },
945
+ {
946
+ id: "opencode-rag:add-chunks",
947
+ title: "Add RAG Chunks",
948
+ bind: v2Bind(chunksKey),
949
+ run: () => {
950
+ if (flagStorePath) {
951
+ setPendingRagInjection(flagStorePath, "chunks");
952
+ setTimeout(() => keymap.dispatch("prompt.submit"), 0);
953
+ }
954
+ },
955
+ },
956
+ ],
957
+ bindings: ["opencode-rag:settings", "opencode-rag:show-file-list", "opencode-rag:add-chunks"],
958
+ }));
959
+ }
960
+ catch {
961
+ // Keymap registration failure must never break the sidebar slot.
962
+ }
963
+ return () => {
964
+ try {
965
+ unclaimSidebar();
1028
966
  }
1029
- catch (err) {
1030
- // Keymap registration may fail in older OpenCode versions; silently skip
967
+ catch {
968
+ // ignore
1031
969
  }
1032
- },
970
+ };
971
+ }
972
+ // ── Plugin export ──────────────────────────────────────────────────
973
+ /**
974
+ * The OpenCodeRAG TUI plugin module.
975
+ * Registers sidebar panels, keybindings, and the settings dialog with OpenCode's
976
+ * terminal UI framework.
977
+ */
978
+ const plugin = {
979
+ id: `${PLUGIN_NAME}:tui`,
980
+ /** V2 entrypoint (schema `{id, setup}`); no-op under the server role, TUI registration under the TUI role. */
981
+ setup,
1033
982
  };
1034
983
  export default plugin;
1035
984
  //# sourceMappingURL=tui.js.map