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