opencode-codebase-index 0.17.0 → 0.18.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.
package/dist/cli.js CHANGED
@@ -7,13 +7,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
8
  var __getProtoOf = Object.getPrototypeOf;
9
9
  var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
- }) : x)(function(x) {
13
- if (typeof require !== "undefined") return require.apply(this, arguments);
14
- throw Error('Dynamic require of "' + x + '" is not supported');
15
- });
16
- var __commonJS = (cb, mod) => function __require2() {
10
+ var __commonJS = (cb, mod) => function __require() {
17
11
  try {
18
12
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
13
  } catch (e) {
@@ -657,470 +651,9 @@ var require_ignore = __commonJS({
657
651
  }
658
652
  });
659
653
 
660
- // node_modules/tiktoken/tiktoken_bg.cjs
661
- var require_tiktoken_bg = __commonJS({
662
- "node_modules/tiktoken/tiktoken_bg.cjs"(exports, module2) {
663
- "use strict";
664
- var wasm;
665
- module2.exports.__wbg_set_wasm = function(val) {
666
- wasm = val;
667
- };
668
- var lTextDecoder = typeof TextDecoder === "undefined" ? (0, module2.require)("util").TextDecoder : TextDecoder;
669
- var cachedTextDecoder = new lTextDecoder("utf-8", { ignoreBOM: true, fatal: true });
670
- cachedTextDecoder.decode();
671
- var cachedUint8ArrayMemory0 = null;
672
- function getUint8ArrayMemory0() {
673
- if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
674
- cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
675
- }
676
- return cachedUint8ArrayMemory0;
677
- }
678
- function getStringFromWasm0(ptr, len) {
679
- ptr = ptr >>> 0;
680
- return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
681
- }
682
- var heap = new Array(128).fill(void 0);
683
- heap.push(void 0, null, true, false);
684
- var heap_next = heap.length;
685
- function addHeapObject(obj) {
686
- if (heap_next === heap.length) heap.push(heap.length + 1);
687
- const idx = heap_next;
688
- heap_next = heap[idx];
689
- heap[idx] = obj;
690
- return idx;
691
- }
692
- function handleError(f, args) {
693
- try {
694
- return f.apply(this, args);
695
- } catch (e) {
696
- wasm.__wbindgen_export_0(addHeapObject(e));
697
- }
698
- }
699
- function getObject(idx) {
700
- return heap[idx];
701
- }
702
- function dropObject(idx) {
703
- if (idx < 132) return;
704
- heap[idx] = heap_next;
705
- heap_next = idx;
706
- }
707
- function takeObject(idx) {
708
- const ret = getObject(idx);
709
- dropObject(idx);
710
- return ret;
711
- }
712
- var WASM_VECTOR_LEN = 0;
713
- var lTextEncoder = typeof TextEncoder === "undefined" ? (0, module2.require)("util").TextEncoder : TextEncoder;
714
- var cachedTextEncoder = new lTextEncoder("utf-8");
715
- var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
716
- return cachedTextEncoder.encodeInto(arg, view);
717
- } : function(arg, view) {
718
- const buf = cachedTextEncoder.encode(arg);
719
- view.set(buf);
720
- return {
721
- read: arg.length,
722
- written: buf.length
723
- };
724
- };
725
- function passStringToWasm0(arg, malloc, realloc) {
726
- if (realloc === void 0) {
727
- const buf = cachedTextEncoder.encode(arg);
728
- const ptr2 = malloc(buf.length, 1) >>> 0;
729
- getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
730
- WASM_VECTOR_LEN = buf.length;
731
- return ptr2;
732
- }
733
- let len = arg.length;
734
- let ptr = malloc(len, 1) >>> 0;
735
- const mem = getUint8ArrayMemory0();
736
- let offset = 0;
737
- for (; offset < len; offset++) {
738
- const code = arg.charCodeAt(offset);
739
- if (code > 127) break;
740
- mem[ptr + offset] = code;
741
- }
742
- if (offset !== len) {
743
- if (offset !== 0) {
744
- arg = arg.slice(offset);
745
- }
746
- ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
747
- const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
748
- const ret = encodeString(arg, view);
749
- offset += ret.written;
750
- ptr = realloc(ptr, len, offset, 1) >>> 0;
751
- }
752
- WASM_VECTOR_LEN = offset;
753
- return ptr;
754
- }
755
- function isLikeNone(x) {
756
- return x === void 0 || x === null;
757
- }
758
- var cachedDataViewMemory0 = null;
759
- function getDataViewMemory0() {
760
- if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
761
- cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
762
- }
763
- return cachedDataViewMemory0;
764
- }
765
- var cachedUint32ArrayMemory0 = null;
766
- function getUint32ArrayMemory0() {
767
- if (cachedUint32ArrayMemory0 === null || cachedUint32ArrayMemory0.byteLength === 0) {
768
- cachedUint32ArrayMemory0 = new Uint32Array(wasm.memory.buffer);
769
- }
770
- return cachedUint32ArrayMemory0;
771
- }
772
- function getArrayU32FromWasm0(ptr, len) {
773
- ptr = ptr >>> 0;
774
- return getUint32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);
775
- }
776
- function passArray8ToWasm0(arg, malloc) {
777
- const ptr = malloc(arg.length * 1, 1) >>> 0;
778
- getUint8ArrayMemory0().set(arg, ptr / 1);
779
- WASM_VECTOR_LEN = arg.length;
780
- return ptr;
781
- }
782
- function passArray32ToWasm0(arg, malloc) {
783
- const ptr = malloc(arg.length * 4, 4) >>> 0;
784
- getUint32ArrayMemory0().set(arg, ptr / 4);
785
- WASM_VECTOR_LEN = arg.length;
786
- return ptr;
787
- }
788
- function getArrayU8FromWasm0(ptr, len) {
789
- ptr = ptr >>> 0;
790
- return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
791
- }
792
- module2.exports.get_encoding = function(encoding, extend_special_tokens) {
793
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
794
- try {
795
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
796
- const ptr0 = passStringToWasm0(encoding, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
797
- const len0 = WASM_VECTOR_LEN;
798
- wasm.get_encoding(retptr, ptr0, len0, addHeapObject(extend_special_tokens));
799
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
800
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
801
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
802
- if (r2) {
803
- throw takeObject(r1);
804
- }
805
- return Tiktoken.__wrap(r0);
806
- } finally {
807
- wasm.__wbindgen_add_to_stack_pointer(16);
808
- }
809
- };
810
- module2.exports.encoding_for_model = function(model, extend_special_tokens) {
811
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
812
- try {
813
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
814
- const ptr0 = passStringToWasm0(model, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
815
- const len0 = WASM_VECTOR_LEN;
816
- wasm.encoding_for_model(retptr, ptr0, len0, addHeapObject(extend_special_tokens));
817
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
818
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
819
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
820
- if (r2) {
821
- throw takeObject(r1);
822
- }
823
- return Tiktoken.__wrap(r0);
824
- } finally {
825
- wasm.__wbindgen_add_to_stack_pointer(16);
826
- }
827
- };
828
- module2.exports.get_encoding_name_for_model = function(model) {
829
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
830
- let deferred3_0;
831
- let deferred3_1;
832
- try {
833
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
834
- const ptr0 = passStringToWasm0(model, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
835
- const len0 = WASM_VECTOR_LEN;
836
- wasm.get_encoding_name_for_model(retptr, ptr0, len0);
837
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
838
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
839
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
840
- var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
841
- var ptr2 = r0;
842
- var len2 = r1;
843
- if (r3) {
844
- ptr2 = 0;
845
- len2 = 0;
846
- throw takeObject(r2);
847
- }
848
- deferred3_0 = ptr2;
849
- deferred3_1 = len2;
850
- return getStringFromWasm0(ptr2, len2);
851
- } finally {
852
- wasm.__wbindgen_add_to_stack_pointer(16);
853
- wasm.__wbindgen_export_3(deferred3_0, deferred3_1, 1);
854
- }
855
- };
856
- var TiktokenFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
857
- }, unregister: () => {
858
- } } : new FinalizationRegistry((ptr) => wasm.__wbg_tiktoken_free(ptr >>> 0, 1));
859
- var Tiktoken = class _Tiktoken {
860
- /**
861
- * @param {string} tiktoken_bfe
862
- * @param {any} special_tokens
863
- * @param {string} pat_str
864
- */
865
- constructor(tiktoken_bfe, special_tokens, pat_str) {
866
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
867
- const ptr0 = passStringToWasm0(tiktoken_bfe, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
868
- const len0 = WASM_VECTOR_LEN;
869
- const ptr1 = passStringToWasm0(pat_str, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
870
- const len1 = WASM_VECTOR_LEN;
871
- const ret = wasm.tiktoken_new(ptr0, len0, addHeapObject(special_tokens), ptr1, len1);
872
- this.__wbg_ptr = ret >>> 0;
873
- TiktokenFinalization.register(this, this.__wbg_ptr, this);
874
- return this;
875
- }
876
- /** @returns {string | undefined} */
877
- get name() {
878
- try {
879
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
880
- wasm.tiktoken_name(retptr, this.__wbg_ptr);
881
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
882
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
883
- let v1;
884
- if (r0 !== 0) {
885
- v1 = getStringFromWasm0(r0, r1).slice();
886
- wasm.__wbindgen_export_3(r0, r1 * 1, 1);
887
- }
888
- return v1;
889
- } finally {
890
- wasm.__wbindgen_add_to_stack_pointer(16);
891
- }
892
- }
893
- static __wrap(ptr) {
894
- ptr = ptr >>> 0;
895
- const obj = Object.create(_Tiktoken.prototype);
896
- obj.__wbg_ptr = ptr;
897
- TiktokenFinalization.register(obj, obj.__wbg_ptr, obj);
898
- return obj;
899
- }
900
- __destroy_into_raw() {
901
- const ptr = this.__wbg_ptr;
902
- this.__wbg_ptr = 0;
903
- TiktokenFinalization.unregister(this);
904
- return ptr;
905
- }
906
- free() {
907
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
908
- const ptr = this.__destroy_into_raw();
909
- wasm.__wbg_tiktoken_free(ptr, 0);
910
- }
911
- /**
912
- * @param {string} text
913
- * @param {any} allowed_special
914
- * @param {any} disallowed_special
915
- * @returns {Uint32Array}
916
- */
917
- encode(text, allowed_special, disallowed_special) {
918
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
919
- try {
920
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
921
- const ptr0 = passStringToWasm0(text, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
922
- const len0 = WASM_VECTOR_LEN;
923
- wasm.tiktoken_encode(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(allowed_special), addHeapObject(disallowed_special));
924
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
925
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
926
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
927
- var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
928
- if (r3) {
929
- throw takeObject(r2);
930
- }
931
- var v2 = getArrayU32FromWasm0(r0, r1).slice();
932
- wasm.__wbindgen_export_3(r0, r1 * 4, 4);
933
- return v2;
934
- } finally {
935
- wasm.__wbindgen_add_to_stack_pointer(16);
936
- }
937
- }
938
- /**
939
- * @param {string} text
940
- * @returns {Uint32Array}
941
- */
942
- encode_ordinary(text) {
943
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
944
- try {
945
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
946
- const ptr0 = passStringToWasm0(text, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
947
- const len0 = WASM_VECTOR_LEN;
948
- wasm.tiktoken_encode_ordinary(retptr, this.__wbg_ptr, ptr0, len0);
949
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
950
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
951
- var v2 = getArrayU32FromWasm0(r0, r1).slice();
952
- wasm.__wbindgen_export_3(r0, r1 * 4, 4);
953
- return v2;
954
- } finally {
955
- wasm.__wbindgen_add_to_stack_pointer(16);
956
- }
957
- }
958
- /**
959
- * @param {string} text
960
- * @param {any} allowed_special
961
- * @param {any} disallowed_special
962
- * @returns {any}
963
- */
964
- encode_with_unstable(text, allowed_special, disallowed_special) {
965
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
966
- try {
967
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
968
- const ptr0 = passStringToWasm0(text, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
969
- const len0 = WASM_VECTOR_LEN;
970
- wasm.tiktoken_encode_with_unstable(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(allowed_special), addHeapObject(disallowed_special));
971
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
972
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
973
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
974
- if (r2) {
975
- throw takeObject(r1);
976
- }
977
- return takeObject(r0);
978
- } finally {
979
- wasm.__wbindgen_add_to_stack_pointer(16);
980
- }
981
- }
982
- /**
983
- * @param {Uint8Array} bytes
984
- * @returns {number}
985
- */
986
- encode_single_token(bytes) {
987
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
988
- const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_export_1);
989
- const len0 = WASM_VECTOR_LEN;
990
- const ret = wasm.tiktoken_encode_single_token(this.__wbg_ptr, ptr0, len0);
991
- return ret >>> 0;
992
- }
993
- /**
994
- * @param {Uint32Array} tokens
995
- * @returns {Uint8Array}
996
- */
997
- decode(tokens) {
998
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
999
- try {
1000
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1001
- const ptr0 = passArray32ToWasm0(tokens, wasm.__wbindgen_export_1);
1002
- const len0 = WASM_VECTOR_LEN;
1003
- wasm.tiktoken_decode(retptr, this.__wbg_ptr, ptr0, len0);
1004
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1005
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1006
- var v2 = getArrayU8FromWasm0(r0, r1).slice();
1007
- wasm.__wbindgen_export_3(r0, r1 * 1, 1);
1008
- return v2;
1009
- } finally {
1010
- wasm.__wbindgen_add_to_stack_pointer(16);
1011
- }
1012
- }
1013
- /**
1014
- * @param {number} token
1015
- * @returns {Uint8Array}
1016
- */
1017
- decode_single_token_bytes(token) {
1018
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
1019
- try {
1020
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1021
- wasm.tiktoken_decode_single_token_bytes(retptr, this.__wbg_ptr, token);
1022
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1023
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1024
- var v1 = getArrayU8FromWasm0(r0, r1).slice();
1025
- wasm.__wbindgen_export_3(r0, r1 * 1, 1);
1026
- return v1;
1027
- } finally {
1028
- wasm.__wbindgen_add_to_stack_pointer(16);
1029
- }
1030
- }
1031
- /** @returns {any} */
1032
- token_byte_values() {
1033
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
1034
- const ret = wasm.tiktoken_token_byte_values(this.__wbg_ptr);
1035
- return takeObject(ret);
1036
- }
1037
- };
1038
- module2.exports.Tiktoken = Tiktoken;
1039
- module2.exports.__wbg_parse_def2e24ef1252aff = function() {
1040
- return handleError(function(arg0, arg1) {
1041
- const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
1042
- return addHeapObject(ret);
1043
- }, arguments);
1044
- };
1045
- module2.exports.__wbg_stringify_f7ed6987935b4a24 = function() {
1046
- return handleError(function(arg0) {
1047
- const ret = JSON.stringify(getObject(arg0));
1048
- return addHeapObject(ret);
1049
- }, arguments);
1050
- };
1051
- module2.exports.__wbindgen_error_new = function(arg0, arg1) {
1052
- const ret = new Error(getStringFromWasm0(arg0, arg1));
1053
- return addHeapObject(ret);
1054
- };
1055
- module2.exports.__wbindgen_is_undefined = function(arg0) {
1056
- const ret = getObject(arg0) === void 0;
1057
- return ret;
1058
- };
1059
- module2.exports.__wbindgen_object_drop_ref = function(arg0) {
1060
- takeObject(arg0);
1061
- };
1062
- module2.exports.__wbindgen_string_get = function(arg0, arg1) {
1063
- if (wasm == null) throw new Error("tiktoken: WASM binary has not been propery initialized.");
1064
- const obj = getObject(arg1);
1065
- const ret = typeof obj === "string" ? obj : void 0;
1066
- var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
1067
- var len1 = WASM_VECTOR_LEN;
1068
- getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
1069
- getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
1070
- };
1071
- module2.exports.__wbindgen_throw = function(arg0, arg1) {
1072
- throw new Error(getStringFromWasm0(arg0, arg1));
1073
- };
1074
- }
1075
- });
1076
-
1077
- // node_modules/tiktoken/tiktoken.cjs
1078
- var require_tiktoken = __commonJS({
1079
- "node_modules/tiktoken/tiktoken.cjs"(exports) {
1080
- "use strict";
1081
- var wasm = require_tiktoken_bg();
1082
- var imports = {};
1083
- imports["./tiktoken_bg.js"] = wasm;
1084
- var path27 = __require("path");
1085
- var fs = __require("fs");
1086
- var candidates = __dirname.split(path27.sep).reduce((memo, _, index, array) => {
1087
- const prefix = array.slice(0, index + 1).join(path27.sep) + path27.sep;
1088
- if (!prefix.includes("node_modules" + path27.sep)) {
1089
- memo.unshift(
1090
- path27.join(
1091
- prefix,
1092
- "node_modules",
1093
- "tiktoken",
1094
- "",
1095
- "./tiktoken_bg.wasm"
1096
- )
1097
- );
1098
- }
1099
- return memo;
1100
- }, []);
1101
- candidates.unshift(path27.join(__dirname, "./tiktoken_bg.wasm"));
1102
- var bytes = null;
1103
- for (const candidate of candidates) {
1104
- try {
1105
- bytes = fs.readFileSync(candidate);
1106
- break;
1107
- } catch {
1108
- }
1109
- }
1110
- if (bytes == null) throw new Error("Missing tiktoken_bg.wasm");
1111
- var wasmModule = new WebAssembly.Module(bytes);
1112
- var wasmInstance = new WebAssembly.Instance(wasmModule, imports);
1113
- wasm.__wbg_set_wasm(wasmInstance.exports);
1114
- exports["get_encoding"] = wasm["get_encoding"];
1115
- exports["encoding_for_model"] = wasm["encoding_for_model"];
1116
- exports["get_encoding_name_for_model"] = wasm["get_encoding_name_for_model"];
1117
- exports["Tiktoken"] = wasm["Tiktoken"];
1118
- }
1119
- });
1120
-
1121
654
  // src/cli.ts
1122
655
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1123
- import { realpathSync as realpathSync3, writeFileSync as writeFileSync7 } from "fs";
656
+ import { realpathSync as realpathSync3, writeFileSync as writeFileSync6 } from "fs";
1124
657
  import * as os6 from "os";
1125
658
  import * as path26 from "path";
1126
659
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -1140,7 +673,8 @@ var DEFAULT_INCLUDE = [
1140
673
  "**/*.{sh,bash,zsh}",
1141
674
  "**/*.{txt,html,htm}",
1142
675
  "**/*.zig",
1143
- "**/*.gd"
676
+ "**/*.gd",
677
+ "**/*.metal"
1144
678
  ];
1145
679
  var DEFAULT_EXCLUDE = [
1146
680
  "**/node_modules/**",
@@ -1331,6 +865,9 @@ function isValidProvider(value) {
1331
865
  return typeof value === "string" && Object.keys(EMBEDDING_MODELS).includes(value);
1332
866
  }
1333
867
  function isValidModel(value, provider) {
868
+ if (typeof value === "string" && provider === "ollama" && value.trim().length > 0) {
869
+ return true;
870
+ }
1334
871
  return typeof value === "string" && Object.keys(EMBEDDING_MODELS[provider]).includes(value);
1335
872
  }
1336
873
  function isValidScope(value) {
@@ -2913,6 +2450,9 @@ function loadOpenCodeAuth() {
2913
2450
  return {};
2914
2451
  }
2915
2452
  async function detectEmbeddingProvider(preferredProvider, model) {
2453
+ if (preferredProvider === "ollama") {
2454
+ return detectOllamaProvider(model);
2455
+ }
2916
2456
  const credentials = await getProviderCredentials(preferredProvider);
2917
2457
  if (credentials) {
2918
2458
  if (!model) {
@@ -2928,10 +2468,16 @@ async function detectEmbeddingProvider(preferredProvider, model) {
2928
2468
  );
2929
2469
  }
2930
2470
  const providerModels = EMBEDDING_MODELS[preferredProvider];
2471
+ const modelInfo = Object.values(providerModels).find((candidate) => candidate.model === model);
2472
+ if (!modelInfo) {
2473
+ throw new Error(
2474
+ `Model '${model}' is not supported by provider '${preferredProvider}'`
2475
+ );
2476
+ }
2931
2477
  return {
2932
2478
  provider: preferredProvider,
2933
2479
  credentials,
2934
- modelInfo: providerModels[model]
2480
+ modelInfo
2935
2481
  };
2936
2482
  }
2937
2483
  throw new Error(
@@ -2940,6 +2486,13 @@ async function detectEmbeddingProvider(preferredProvider, model) {
2940
2486
  }
2941
2487
  async function tryDetectProvider() {
2942
2488
  for (const provider of autoDetectProviders) {
2489
+ if (provider === "ollama") {
2490
+ const ollamaProvider = await tryDetectOllamaProvider();
2491
+ if (ollamaProvider) {
2492
+ return ollamaProvider;
2493
+ }
2494
+ continue;
2495
+ }
2943
2496
  const credentials = await getProviderCredentials(provider);
2944
2497
  if (credentials) {
2945
2498
  return {
@@ -3007,32 +2560,105 @@ function getGoogleCredentials() {
3007
2560
  }
3008
2561
  return null;
3009
2562
  }
3010
- async function getOllamaCredentials() {
3011
- const baseUrl = process.env.OLLAMA_HOST || "http://localhost:11434";
2563
+ async function fetchOllama(url, init) {
2564
+ const controller = new AbortController();
2565
+ const timeoutId = setTimeout(() => controller.abort(), 2e3);
3012
2566
  try {
3013
- const controller = new AbortController();
3014
- const timeoutId = setTimeout(() => controller.abort(), 2e3);
3015
- const response = await fetch(`${baseUrl}/api/tags`, {
3016
- signal: controller.signal
3017
- });
2567
+ return await fetch(url, { ...init, signal: controller.signal });
2568
+ } finally {
3018
2569
  clearTimeout(timeoutId);
2570
+ }
2571
+ }
2572
+ async function getOllamaCredentials() {
2573
+ const baseUrl = (process.env.OLLAMA_HOST || "http://localhost:11434").replace(/\/+$/, "");
2574
+ try {
2575
+ const response = await fetchOllama(`${baseUrl}/api/tags`);
3019
2576
  if (response.ok) {
3020
- const data = await response.json();
3021
- const hasEmbeddingModel = data.models?.some(
3022
- (m) => m.name.includes("nomic-embed") || m.name.includes("mxbai-embed") || m.name.includes("all-minilm")
3023
- );
3024
- if (hasEmbeddingModel) {
3025
- return {
3026
- provider: "ollama",
3027
- baseUrl
3028
- };
3029
- }
2577
+ return {
2578
+ provider: "ollama",
2579
+ baseUrl
2580
+ };
3030
2581
  }
3031
2582
  } catch {
3032
2583
  return null;
3033
2584
  }
3034
2585
  return null;
3035
2586
  }
2587
+ function findCatalogOllamaModel(model) {
2588
+ const stableName = model.endsWith(":latest") ? model.slice(0, -":latest".length) : model;
2589
+ return Object.values(EMBEDDING_MODELS.ollama).find((candidate) => candidate.model === stableName) ?? null;
2590
+ }
2591
+ function getPositiveIntegerMetadata(modelInfo, suffix) {
2592
+ const values = Object.entries(modelInfo).filter(([key]) => key.endsWith(suffix)).map(([, value]) => value).filter((value) => typeof value === "number" && Number.isInteger(value) && value > 0);
2593
+ return values.length === 1 ? values[0] : null;
2594
+ }
2595
+ async function fetchOllamaModelInfo(credentials, model) {
2596
+ const response = await fetchOllama(`${credentials.baseUrl}/api/show`, {
2597
+ method: "POST",
2598
+ headers: { "Content-Type": "application/json" },
2599
+ body: JSON.stringify({ model })
2600
+ });
2601
+ if (!response.ok) {
2602
+ return null;
2603
+ }
2604
+ const data = await response.json();
2605
+ if (!data.capabilities?.includes("embedding") || !data.model_info) {
2606
+ return null;
2607
+ }
2608
+ const dimensions = getPositiveIntegerMetadata(data.model_info, ".embedding_length");
2609
+ const maxTokens = getPositiveIntegerMetadata(data.model_info, ".context_length");
2610
+ if (!dimensions || !maxTokens) {
2611
+ return null;
2612
+ }
2613
+ return {
2614
+ provider: "ollama",
2615
+ model,
2616
+ dimensions,
2617
+ maxTokens,
2618
+ costPer1MTokens: 0
2619
+ };
2620
+ }
2621
+ async function listOllamaModels(credentials) {
2622
+ const response = await fetchOllama(`${credentials.baseUrl}/api/tags`);
2623
+ if (!response.ok) {
2624
+ return [];
2625
+ }
2626
+ const data = await response.json();
2627
+ return [...new Set((data.models ?? []).map((entry) => entry.name ?? entry.model).filter((name) => typeof name === "string" && name.trim().length > 0))];
2628
+ }
2629
+ async function detectOllamaProvider(model) {
2630
+ const credentials = await getOllamaCredentials();
2631
+ if (!credentials) {
2632
+ throw new Error("Preferred provider 'ollama' is not configured or authenticated");
2633
+ }
2634
+ const requestedModel = model?.trim();
2635
+ if (requestedModel) {
2636
+ const catalogModel = findCatalogOllamaModel(requestedModel);
2637
+ if (catalogModel) {
2638
+ return { provider: "ollama", credentials, modelInfo: catalogModel };
2639
+ }
2640
+ }
2641
+ const candidates = requestedModel ? [requestedModel] : await listOllamaModels(credentials);
2642
+ for (const candidate of candidates) {
2643
+ const modelInfo = await fetchOllamaModelInfo(credentials, candidate);
2644
+ if (modelInfo) {
2645
+ return {
2646
+ provider: "ollama",
2647
+ credentials,
2648
+ modelInfo: findCatalogOllamaModel(candidate) ?? modelInfo
2649
+ };
2650
+ }
2651
+ }
2652
+ const detail = model ? `Model '${model}' is not installed or is not embedding-capable` : "No installed embedding-capable Ollama model was found";
2653
+ throw new Error(detail);
2654
+ }
2655
+ async function tryDetectOllamaProvider() {
2656
+ try {
2657
+ return await detectOllamaProvider();
2658
+ } catch {
2659
+ return null;
2660
+ }
2661
+ }
3036
2662
  function getProviderDisplayName(provider) {
3037
2663
  switch (provider) {
3038
2664
  case "github-copilot":
@@ -3372,6 +2998,7 @@ var GoogleEmbeddingProvider = class _GoogleEmbeddingProvider extends BaseEmbeddi
3372
2998
  // src/embeddings/providers/ollama.ts
3373
2999
  var OllamaEmbeddingProvider = class _OllamaEmbeddingProvider extends BaseEmbeddingProvider {
3374
3000
  static MIN_TRUNCATION_CHARS = 512;
3001
+ static REQUEST_TIMEOUT_MS = 12e4;
3375
3002
  constructor(credentials, modelInfo) {
3376
3003
  super(credentials, modelInfo);
3377
3004
  }
@@ -3446,22 +3073,45 @@ var OllamaEmbeddingProvider = class _OllamaEmbeddingProvider extends BaseEmbeddi
3446
3073
  }
3447
3074
  }
3448
3075
  async embedSingle(text) {
3449
- const response = await fetch(`${this.credentials.baseUrl}/api/embeddings`, {
3450
- method: "POST",
3451
- headers: {
3452
- "Content-Type": "application/json"
3453
- },
3454
- body: JSON.stringify({
3455
- model: this.modelInfo.model,
3456
- prompt: text,
3457
- truncate: false
3458
- })
3459
- });
3076
+ const controller = new AbortController();
3077
+ const timeout = setTimeout(
3078
+ () => controller.abort(),
3079
+ _OllamaEmbeddingProvider.REQUEST_TIMEOUT_MS
3080
+ );
3081
+ let response;
3082
+ try {
3083
+ response = await fetch(`${this.credentials.baseUrl}/api/embeddings`, {
3084
+ method: "POST",
3085
+ headers: {
3086
+ "Content-Type": "application/json"
3087
+ },
3088
+ body: JSON.stringify({
3089
+ model: this.modelInfo.model,
3090
+ prompt: text,
3091
+ truncate: false
3092
+ }),
3093
+ signal: controller.signal
3094
+ });
3095
+ } catch (error) {
3096
+ if (error instanceof Error && error.name === "AbortError") {
3097
+ throw new Error(
3098
+ `Ollama embedding request timed out after ${_OllamaEmbeddingProvider.REQUEST_TIMEOUT_MS}ms`
3099
+ );
3100
+ }
3101
+ throw error;
3102
+ } finally {
3103
+ clearTimeout(timeout);
3104
+ }
3460
3105
  if (!response.ok) {
3461
3106
  const error = (await response.text()).slice(0, 500);
3462
3107
  throw new Error(`Ollama embedding API error: ${response.status} - ${error}`);
3463
3108
  }
3464
3109
  const data = await response.json();
3110
+ if (!Array.isArray(data.embedding) || data.embedding.length !== this.modelInfo.dimensions || data.embedding.some((value) => typeof value !== "number" || !Number.isFinite(value))) {
3111
+ throw new Error(
3112
+ `Ollama returned an invalid embedding; expected ${this.modelInfo.dimensions} finite dimensions`
3113
+ );
3114
+ }
3465
3115
  return {
3466
3116
  embedding: data.embedding,
3467
3117
  tokensUsed: this.estimateTokens(text)
@@ -4372,7 +4022,9 @@ function mapChunk(c) {
4372
4022
  return {
4373
4023
  content: c.content,
4374
4024
  startLine: c.startLine ?? c.start_line,
4025
+ startCol: c.startCol ?? c.start_col,
4375
4026
  endLine: c.endLine ?? c.end_line,
4027
+ endCol: c.endCol ?? c.end_col,
4376
4028
  chunkType: c.chunkType ?? c.chunk_type,
4377
4029
  name: c.name ?? void 0,
4378
4030
  language: c.language
@@ -4493,6 +4145,7 @@ function getEmbeddingHeaderParts(chunk, filePath) {
4493
4145
  javascript: "JavaScript",
4494
4146
  python: "Python",
4495
4147
  rust: "Rust",
4148
+ swift: "Swift",
4496
4149
  go: "Go",
4497
4150
  java: "Java"
4498
4151
  };
@@ -4501,7 +4154,16 @@ function getEmbeddingHeaderParts(chunk, filePath) {
4501
4154
  function: "function",
4502
4155
  arrow_function: "arrow function",
4503
4156
  method_definition: "method",
4157
+ method_declaration: "method",
4158
+ protocol_function_declaration: "protocol requirement",
4159
+ init_declaration: "initializer",
4160
+ deinit_declaration: "deinitializer",
4161
+ subscript_declaration: "subscript",
4504
4162
  class_declaration: "class",
4163
+ actor_declaration: "actor",
4164
+ extension_declaration: "extension",
4165
+ protocol_declaration: "protocol",
4166
+ struct_declaration: "struct",
4505
4167
  interface_declaration: "interface",
4506
4168
  type_alias_declaration: "type alias",
4507
4169
  enum_declaration: "enum",
@@ -5195,16 +4857,6 @@ function resolveWorktreeFallbackPath(projectRoot, relativePath) {
5195
4857
  const fallbackPath = path8.join(mainRepoRoot, relativePath);
5196
4858
  return existsSync5(fallbackPath) ? fallbackPath : null;
5197
4859
  }
5198
- function resolveWorktreeFallbackProjectIndexPath(projectRoot, host) {
5199
- const inheritedHostPath = resolveWorktreeFallbackPath(projectRoot, getProjectIndexRelativePath(host));
5200
- if (inheritedHostPath) {
5201
- return inheritedHostPath;
5202
- }
5203
- if (host !== "opencode") {
5204
- return resolveWorktreeFallbackPath(projectRoot, OPENCODE_PROJECT_INDEX_RELATIVE_PATH);
5205
- }
5206
- return null;
5207
- }
5208
4860
  function getHostProjectIndexRelativePath(host) {
5209
4861
  return getProjectIndexRelativePath(host);
5210
4862
  }
@@ -5306,6 +4958,9 @@ function resolveProjectIndexPath(projectRoot, scope, host = "opencode") {
5306
4958
  if (hasHostProjectConfig(projectRoot, host)) {
5307
4959
  return localIndexPath;
5308
4960
  }
4961
+ if (resolveWorktreeMainRepoRoot(projectRoot)) {
4962
+ return localIndexPath;
4963
+ }
5309
4964
  const hostFallback = resolveWorktreeFallbackPath(projectRoot, getProjectIndexRelativePath(host));
5310
4965
  if (hostFallback) {
5311
4966
  return hostFallback;
@@ -5840,40 +5495,6 @@ function releaseIndexLock(lease) {
5840
5495
  }
5841
5496
  return true;
5842
5497
  }
5843
- async function withIndexLock(indexPath, operation, callback, options = {}) {
5844
- const lease = acquireIndexLock(indexPath, operation);
5845
- let result;
5846
- let callbackError;
5847
- let callbackFailed = false;
5848
- try {
5849
- result = await callback(lease);
5850
- } catch (error) {
5851
- callbackFailed = true;
5852
- callbackError = error;
5853
- }
5854
- if (!callbackFailed && options.completeRecoveries !== false) {
5855
- try {
5856
- completeLeaseRecovery(lease);
5857
- } catch (error) {
5858
- callbackFailed = true;
5859
- callbackError = error;
5860
- }
5861
- }
5862
- let releaseError;
5863
- try {
5864
- if (!releaseIndexLock(lease)) {
5865
- releaseError = new Error(`Lost ownership of index mutation lease ${lease.owner.token}`);
5866
- }
5867
- } catch (error) {
5868
- releaseError = error;
5869
- }
5870
- if (releaseError !== void 0) {
5871
- if (callbackFailed) throw new AggregateError([callbackError, releaseError], "Index mutation and lease release both failed");
5872
- throw releaseError;
5873
- }
5874
- if (callbackFailed) throw callbackError;
5875
- return result;
5876
- }
5877
5498
  function createLeaseTemporaryPath(targetPath, owner, kind = "tmp") {
5878
5499
  if (kind === "bak") return `${targetPath}.bak.${owner.pid}.${owner.token}`;
5879
5500
  temporaryCounter += 1;
@@ -5908,8 +5529,18 @@ function completeLeaseRecovery(lease) {
5908
5529
  }
5909
5530
 
5910
5531
  // src/indexer/index.ts
5911
- var CALL_GRAPH_LANGUAGES = /* @__PURE__ */ new Set(["typescript", "tsx", "javascript", "jsx", "python", "go", "rust", "php", "apex", "zig", "gdscript", "matlab", "bash"]);
5912
- var CASE_INSENSITIVE_LANGUAGES = /* @__PURE__ */ new Set(["apex"]);
5532
+ var CALL_GRAPH_LANGUAGES = /* @__PURE__ */ new Set(["typescript", "tsx", "javascript", "jsx", "python", "go", "rust", "swift", "php", "apex", "zig", "gdscript", "matlab", "bash", "c", "cpp", "metal"]);
5533
+ var CASE_INSENSITIVE_LANGUAGES = /* @__PURE__ */ new Set(["apex", "php"]);
5534
+ var CALL_GRAPH_RESOLUTION_VERSION = "4";
5535
+ var PHP_FUNCTION_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set([
5536
+ "function_declaration",
5537
+ "function",
5538
+ "function_definition"
5539
+ ]);
5540
+ var PHP_CLASS_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set([
5541
+ "class_declaration",
5542
+ "class_definition"
5543
+ ]);
5913
5544
  var CALL_GRAPH_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set([
5914
5545
  "function_declaration",
5915
5546
  "function",
@@ -5922,6 +5553,9 @@ var CALL_GRAPH_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set([
5922
5553
  "enum_declaration",
5923
5554
  "function_definition",
5924
5555
  "class_definition",
5556
+ "class_specifier",
5557
+ "struct_specifier",
5558
+ "namespace_definition",
5925
5559
  "decorated_definition",
5926
5560
  "method_declaration",
5927
5561
  "type_declaration",
@@ -5937,6 +5571,14 @@ var CALL_GRAPH_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set([
5937
5571
  "test_declaration",
5938
5572
  "struct_declaration",
5939
5573
  "union_declaration",
5574
+ // Synthetic Swift declarations or declarations specific to tree-sitter-swift.
5575
+ "actor_declaration",
5576
+ "extension_declaration",
5577
+ "protocol_declaration",
5578
+ "protocol_function_declaration",
5579
+ "init_declaration",
5580
+ "deinit_declaration",
5581
+ "subscript_declaration",
5940
5582
  // GDScript declarations whose names participate in the call graph.
5941
5583
  // `function_definition` and `class_definition` are already in the set
5942
5584
  // above (shared with Python/C/Bash and Python, respectively).
@@ -5946,6 +5588,53 @@ var CALL_GRAPH_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set([
5946
5588
  "const_statement",
5947
5589
  "class_name_statement"
5948
5590
  ]);
5591
+ var C_FAMILY_TYPE_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set(["class_specifier", "struct_specifier"]);
5592
+ function isCompatibleCFamilyCallTarget(language, callType, symbolKind) {
5593
+ if (language !== "c" && language !== "cpp") return true;
5594
+ if (symbolKind === "namespace_definition") return callType === "Import";
5595
+ const isTypeSymbol = C_FAMILY_TYPE_SYMBOL_CHUNK_TYPES.has(symbolKind);
5596
+ if (callType === "Constructor" || callType === "Inherits" || callType === "Implements") {
5597
+ return isTypeSymbol;
5598
+ }
5599
+ return !isTypeSymbol;
5600
+ }
5601
+ var EXECUTABLE_SYMBOL_CHUNK_TYPES = /* @__PURE__ */ new Set([
5602
+ "function_declaration",
5603
+ "function",
5604
+ "arrow_function",
5605
+ "method_definition",
5606
+ "function_definition",
5607
+ "method_declaration",
5608
+ "function_item",
5609
+ "protocol_function_declaration",
5610
+ "init_declaration",
5611
+ "deinit_declaration",
5612
+ "subscript_declaration",
5613
+ "constructor_definition",
5614
+ "trigger_declaration",
5615
+ "test_declaration"
5616
+ ]);
5617
+ function findEnclosingSymbol(symbols, line, column) {
5618
+ let best;
5619
+ for (const symbol of symbols) {
5620
+ if (line < symbol.startLine || line > symbol.endLine) continue;
5621
+ if (column !== void 0 && (line === symbol.startLine && column < symbol.startCol || line === symbol.endLine && column >= symbol.endCol)) {
5622
+ continue;
5623
+ }
5624
+ if (!best) {
5625
+ best = symbol;
5626
+ continue;
5627
+ }
5628
+ const span = symbol.endLine - symbol.startLine;
5629
+ const bestSpan = best.endLine - best.startLine;
5630
+ const isNarrowerPositionRange = column !== void 0 && span === bestSpan && symbol.startLine === best.startLine && symbol.endLine === best.endLine && symbol.startCol >= best.startCol && symbol.endCol <= best.endCol && (symbol.startCol > best.startCol || symbol.endCol < best.endCol);
5631
+ const isMoreSpecificTie = span === bestSpan && symbol.startLine === best.startLine && EXECUTABLE_SYMBOL_CHUNK_TYPES.has(symbol.kind) && !EXECUTABLE_SYMBOL_CHUNK_TYPES.has(best.kind);
5632
+ if (span < bestSpan || span === bestSpan && symbol.startLine > best.startLine || isNarrowerPositionRange || isMoreSpecificTie) {
5633
+ best = symbol;
5634
+ }
5635
+ }
5636
+ return best;
5637
+ }
5949
5638
  function float32ArrayToBuffer(arr) {
5950
5639
  const float32 = new Float32Array(arr);
5951
5640
  return Buffer.from(float32.buffer);
@@ -6030,6 +5719,8 @@ function hasBlameMetadata(metadata) {
6030
5719
  }
6031
5720
  var INDEX_METADATA_VERSION = "1";
6032
5721
  var EMBEDDING_STRATEGY_VERSION = "2";
5722
+ var SWIFT_PARSER_VERSION = "1";
5723
+ var METAL_PARSER_VERSION = "1";
6033
5724
  var RANKING_TOKEN_CACHE_LIMIT = 4096;
6034
5725
  var RANK_HYBRID_CACHE_LIMIT = 256;
6035
5726
  function createPendingChunkStorageText(texts) {
@@ -6352,15 +6043,25 @@ function chunkTypeBoost(chunkType) {
6352
6043
  case "function_declaration":
6353
6044
  case "method":
6354
6045
  case "method_definition":
6046
+ case "method_declaration":
6047
+ case "protocol_function_declaration":
6048
+ case "init_declaration":
6049
+ case "deinit_declaration":
6050
+ case "subscript_declaration":
6355
6051
  case "class":
6356
6052
  case "class_declaration":
6053
+ case "actor_declaration":
6054
+ case "extension_declaration":
6357
6055
  return 0.2;
6358
6056
  case "interface":
6359
6057
  case "type":
6360
6058
  case "enum":
6059
+ case "enum_declaration":
6361
6060
  case "struct":
6061
+ case "struct_declaration":
6362
6062
  case "impl":
6363
6063
  case "trait":
6064
+ case "protocol_declaration":
6364
6065
  case "module":
6365
6066
  return 0.1;
6366
6067
  default:
@@ -6467,11 +6168,21 @@ function isImplementationChunkType(chunkType) {
6467
6168
  "function_declaration",
6468
6169
  "method",
6469
6170
  "method_definition",
6171
+ "method_declaration",
6172
+ "protocol_function_declaration",
6173
+ "init_declaration",
6174
+ "deinit_declaration",
6175
+ "subscript_declaration",
6470
6176
  "class",
6471
6177
  "class_declaration",
6178
+ "actor_declaration",
6179
+ "extension_declaration",
6472
6180
  "interface",
6181
+ "protocol_declaration",
6473
6182
  "type",
6474
6183
  "enum",
6184
+ "enum_declaration",
6185
+ "struct_declaration",
6475
6186
  "module"
6476
6187
  ].includes(chunkType);
6477
6188
  }
@@ -7474,6 +7185,29 @@ var Indexer = class {
7474
7185
  const projectHash = hashContent(path12.resolve(this.projectRoot)).slice(0, 16);
7475
7186
  return `index.forceReembed.${projectHash}`;
7476
7187
  }
7188
+ getCallGraphResolutionMetadataKey() {
7189
+ if (this.config.scope !== "global") {
7190
+ return "index.callGraphResolutionVersion";
7191
+ }
7192
+ const projectHash = hashContent(path12.resolve(this.projectRoot)).slice(0, 16);
7193
+ return `index.callGraphResolutionVersion.${projectHash}`;
7194
+ }
7195
+ getSwiftParserVersionMetadataKey() {
7196
+ const key = "index.parser.swiftVersion";
7197
+ if (this.config.scope !== "global") {
7198
+ return key;
7199
+ }
7200
+ const projectHash = hashContent(path12.resolve(this.projectRoot)).slice(0, 16);
7201
+ return `${key}.${projectHash}`;
7202
+ }
7203
+ getMetalParserVersionMetadataKey() {
7204
+ const key = "index.parser.metalVersion";
7205
+ if (this.config.scope !== "global") {
7206
+ return key;
7207
+ }
7208
+ const projectHash = hashContent(path12.resolve(this.projectRoot)).slice(0, 16);
7209
+ return `${key}.${projectHash}`;
7210
+ }
7477
7211
  hasProjectForceReembedPending() {
7478
7212
  return this.config.scope === "global" && this.database?.getMetadata(this.getProjectForceReembedMetadataKey()) === "true";
7479
7213
  }
@@ -8634,6 +8368,7 @@ var Indexer = class {
8634
8368
  this.database.setMetadata("index.embeddingProvider", provider.provider);
8635
8369
  this.database.setMetadata("index.embeddingModel", provider.modelInfo.model);
8636
8370
  this.database.setMetadata("index.embeddingDimensions", provider.modelInfo.dimensions.toString());
8371
+ this.database.setMetadata(this.getCallGraphResolutionMetadataKey(), CALL_GRAPH_RESOLUTION_VERSION);
8637
8372
  if (this.config.scope === "global") {
8638
8373
  if (completeProjectEmbeddingStrategyReset) {
8639
8374
  this.database.setMetadata(this.getProjectEmbeddingStrategyMetadataKey(), EMBEDDING_STRATEGY_VERSION);
@@ -8821,6 +8556,20 @@ var Indexer = class {
8821
8556
  totalChunks: 0
8822
8557
  });
8823
8558
  this.loadFileHashCache();
8559
+ const swiftParserMetadataKey = this.getSwiftParserVersionMetadataKey();
8560
+ const reparseCachedSwiftFiles = database.getMetadata(swiftParserMetadataKey) !== SWIFT_PARSER_VERSION;
8561
+ const metalParserMetadataKey = this.getMetalParserVersionMetadataKey();
8562
+ const reparseCachedMetalFiles = database.getMetadata(metalParserMetadataKey) !== METAL_PARSER_VERSION;
8563
+ if (reparseCachedSwiftFiles && Array.from(this.fileHashCache.keys()).some(
8564
+ (filePath) => path12.extname(filePath).toLowerCase() === ".swift"
8565
+ )) {
8566
+ this.logger.info("Reindexing cached Swift files for parser support");
8567
+ }
8568
+ if (reparseCachedMetalFiles && Array.from(this.fileHashCache.keys()).some(
8569
+ (filePath) => path12.extname(filePath).toLowerCase() === ".metal"
8570
+ )) {
8571
+ this.logger.info("Reindexing cached Metal files for parser support");
8572
+ }
8824
8573
  const includePatterns = [...this.config.include, ...this.config.additionalInclude];
8825
8574
  const { files, skipped } = await collectFiles(
8826
8575
  this.projectRoot,
@@ -8840,10 +8589,17 @@ var Indexer = class {
8840
8589
  const changedFiles = [];
8841
8590
  const unchangedFilePaths = /* @__PURE__ */ new Set();
8842
8591
  const currentFileHashes = /* @__PURE__ */ new Map();
8592
+ const needsCallGraphResolutionMigration = database.getMetadata(this.getCallGraphResolutionMetadataKey()) !== CALL_GRAPH_RESOLUTION_VERSION;
8843
8593
  for (const f of files) {
8844
8594
  const currentHash = hashFile(f.path);
8845
8595
  currentFileHashes.set(f.path, currentHash);
8846
- if (this.fileHashCache.get(f.path) === currentHash) {
8596
+ const cachedHashMatches = this.fileHashCache.get(f.path) === currentHash;
8597
+ const needsCallGraphRefresh = cachedHashMatches && needsCallGraphResolutionMigration && database.getChunksByFile(f.path).some(
8598
+ (chunk) => chunk.language === "php" || chunk.language === "c" || chunk.language === "cpp"
8599
+ );
8600
+ const requiresSwiftParserUpgrade = reparseCachedSwiftFiles && path12.extname(f.path).toLowerCase() === ".swift";
8601
+ const requiresMetalParserUpgrade = reparseCachedMetalFiles && path12.extname(f.path).toLowerCase() === ".metal";
8602
+ if (cachedHashMatches && !needsCallGraphRefresh && !requiresSwiftParserUpgrade && !requiresMetalParserUpgrade) {
8847
8603
  unchangedFilePaths.add(f.path);
8848
8604
  this.logger.recordCacheHit();
8849
8605
  } else {
@@ -9045,16 +8801,28 @@ var Indexer = class {
9045
8801
  const fileSymbols = [];
9046
8802
  for (const chunk of parsed.chunks) {
9047
8803
  if (!chunk.name || !CALL_GRAPH_SYMBOL_CHUNK_TYPES.has(chunk.chunkType)) continue;
9048
- const symbolId = `sym_${hashContent(parsed.path + ":" + chunk.name + ":" + chunk.chunkType + ":" + chunk.startLine).slice(0, 16)}`;
8804
+ const existingMetalSymbol = chunk.language === "metal" ? fileSymbols.find(
8805
+ (symbol2) => symbol2.name === chunk.name && symbol2.kind === chunk.chunkType && symbol2.startLine <= chunk.endLine && chunk.startLine <= symbol2.endLine
8806
+ ) : void 0;
8807
+ if (existingMetalSymbol) {
8808
+ existingMetalSymbol.startLine = Math.min(existingMetalSymbol.startLine, chunk.startLine);
8809
+ existingMetalSymbol.endLine = Math.max(existingMetalSymbol.endLine, chunk.endLine);
8810
+ existingMetalSymbol.startCol = Math.min(existingMetalSymbol.startCol, chunk.startCol ?? 0);
8811
+ existingMetalSymbol.endCol = Math.max(existingMetalSymbol.endCol, chunk.endCol ?? 0);
8812
+ continue;
8813
+ }
8814
+ const symbolId = `sym_${hashContent(
8815
+ parsed.path + ":" + chunk.name + ":" + chunk.chunkType + ":" + chunk.startLine + ":" + (chunk.startCol ?? 0)
8816
+ ).slice(0, 16)}`;
9049
8817
  const symbol = {
9050
8818
  id: symbolId,
9051
8819
  filePath: parsed.path,
9052
8820
  name: chunk.name,
9053
8821
  kind: chunk.chunkType,
9054
8822
  startLine: chunk.startLine,
9055
- startCol: 0,
8823
+ startCol: chunk.startCol ?? 0,
9056
8824
  endLine: chunk.endLine,
9057
- endCol: 0,
8825
+ endCol: chunk.endCol ?? 0,
9058
8826
  language: chunk.language
9059
8827
  };
9060
8828
  fileSymbols.push(symbol);
@@ -9079,8 +8847,10 @@ var Indexer = class {
9079
8847
  if (callSites.length === 0) continue;
9080
8848
  const edges = [];
9081
8849
  for (const site of callSites) {
9082
- const enclosingSymbol = fileSymbols.find(
9083
- (sym) => site.line >= sym.startLine && site.line <= sym.endLine
8850
+ const enclosingSymbol = findEnclosingSymbol(
8851
+ fileSymbols,
8852
+ site.line,
8853
+ site.column
9084
8854
  );
9085
8855
  if (!enclosingSymbol) continue;
9086
8856
  const edgeId = `edge_${hashContent(enclosingSymbol.id + ":" + site.calleeName + ":" + site.line + ":" + site.column).slice(0, 16)}`;
@@ -9099,7 +8869,21 @@ var Indexer = class {
9099
8869
  if (edges.length > 0) {
9100
8870
  database.upsertCallEdgesBatch(edges);
9101
8871
  for (const edge of edges) {
9102
- const candidates = symbolsByName.get(normalizeSymbolKey(edge.targetName));
8872
+ let candidates = symbolsByName.get(normalizeSymbolKey(edge.targetName));
8873
+ if (fileLanguage === "php" && candidates) {
8874
+ if (edge.callType === "Constructor") {
8875
+ candidates = candidates.filter(
8876
+ (candidate) => PHP_CLASS_SYMBOL_CHUNK_TYPES.has(candidate.kind)
8877
+ );
8878
+ } else if (edge.callType === "Call") {
8879
+ candidates = candidates.filter(
8880
+ (candidate) => PHP_FUNCTION_SYMBOL_CHUNK_TYPES.has(candidate.kind)
8881
+ );
8882
+ }
8883
+ }
8884
+ candidates = candidates?.filter(
8885
+ (symbol) => isCompatibleCFamilyCallTarget(fileLanguage, edge.callType, symbol.kind)
8886
+ );
9103
8887
  if (candidates && candidates.length === 1) {
9104
8888
  database.resolveCallEdge(edge.id, candidates[0].id);
9105
8889
  }
@@ -9154,6 +8938,8 @@ var Indexer = class {
9154
8938
  this.saveFileHashCache();
9155
8939
  this.saveFailedBatches([]);
9156
8940
  }
8941
+ database.setMetadata(swiftParserMetadataKey, SWIFT_PARSER_VERSION);
8942
+ database.setMetadata(metalParserMetadataKey, METAL_PARSER_VERSION);
9157
8943
  this.saveIndexMetadata(configuredProviderInfo);
9158
8944
  this.indexCompatibility = { compatible: true };
9159
8945
  stats.durationMs = Date.now() - startTime;
@@ -9181,6 +8967,8 @@ var Indexer = class {
9181
8967
  this.saveFileHashCache();
9182
8968
  this.saveFailedBatches([]);
9183
8969
  }
8970
+ database.setMetadata(swiftParserMetadataKey, SWIFT_PARSER_VERSION);
8971
+ database.setMetadata(metalParserMetadataKey, METAL_PARSER_VERSION);
9184
8972
  this.saveIndexMetadata(configuredProviderInfo);
9185
8973
  this.indexCompatibility = { compatible: true };
9186
8974
  stats.durationMs = Date.now() - startTime;
@@ -9451,6 +9239,8 @@ var Indexer = class {
9451
9239
  if (forceScopedReembed && failedForcedChunkIds.size === 0) {
9452
9240
  database.deleteMetadata(this.getProjectForceReembedMetadataKey());
9453
9241
  }
9242
+ database.setMetadata(swiftParserMetadataKey, SWIFT_PARSER_VERSION);
9243
+ database.setMetadata(metalParserMetadataKey, METAL_PARSER_VERSION);
9454
9244
  this.saveIndexMetadata(configuredProviderInfo);
9455
9245
  this.indexCompatibility = { compatible: true };
9456
9246
  this.logger.recordIndexingEnd();
@@ -10561,232 +10351,26 @@ var Indexer = class {
10561
10351
  import { existsSync as existsSync10, realpathSync as realpathSync2, statSync as statSync4 } from "fs";
10562
10352
  import * as path17 from "path";
10563
10353
 
10564
- // src/config/merger.ts
10565
- import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
10566
- import * as path14 from "path";
10567
-
10568
- // src/config/rebase.ts
10354
+ // src/tools/knowledge-base-paths.ts
10569
10355
  import * as path13 from "path";
10570
- function isWithinRoot(rootDir, targetPath) {
10571
- const relativePath = path13.relative(rootDir, targetPath);
10572
- return relativePath === "" || !relativePath.startsWith("..") && !path13.isAbsolute(relativePath);
10573
- }
10574
- function rebasePathEntries(values, fromDir, toDir) {
10575
- if (!Array.isArray(values)) {
10576
- return [];
10356
+ function resolveConfigPathValue(value, baseDir) {
10357
+ const trimmed = value.trim();
10358
+ if (!trimmed) {
10359
+ return trimmed;
10577
10360
  }
10578
- return values.filter((value) => typeof value === "string").map((value) => {
10579
- const trimmed = value.trim();
10580
- if (!trimmed || path13.isAbsolute(trimmed)) {
10581
- return trimmed;
10582
- }
10583
- return normalizePathSeparators(path13.normalize(path13.relative(toDir, path13.resolve(fromDir, trimmed))));
10584
- }).filter(Boolean);
10361
+ const absolutePath = path13.isAbsolute(trimmed) ? trimmed : path13.resolve(baseDir, trimmed);
10362
+ return path13.normalize(absolutePath);
10585
10363
  }
10586
- function resolveInheritedKnowledgeBaseEntries(values, sourceRoot, targetRoot) {
10587
- if (!Array.isArray(values)) {
10588
- return [];
10589
- }
10590
- return values.filter((value) => typeof value === "string").map((value) => {
10591
- const trimmed = value.trim();
10592
- if (!trimmed) {
10593
- return trimmed;
10594
- }
10595
- if (path13.isAbsolute(trimmed)) {
10596
- if (isWithinRoot(sourceRoot, trimmed)) {
10597
- return normalizePathSeparators(path13.normalize(path13.relative(sourceRoot, trimmed) || "."));
10598
- }
10599
- return path13.normalize(trimmed);
10600
- }
10601
- const resolvedFromSource = path13.resolve(sourceRoot, trimmed);
10602
- if (isWithinRoot(sourceRoot, resolvedFromSource)) {
10603
- return normalizePathSeparators(path13.normalize(trimmed));
10604
- }
10605
- return normalizePathSeparators(path13.normalize(path13.relative(targetRoot, resolvedFromSource)));
10606
- }).filter(Boolean);
10607
- }
10608
-
10609
- // src/config/merger.ts
10610
- var PROJECT_OVERRIDE_KEYS = [
10611
- "embeddingProvider",
10612
- "customProvider",
10613
- "embeddingModel",
10614
- "reranker",
10615
- "include",
10616
- "exclude",
10617
- "indexing",
10618
- "search",
10619
- "debug",
10620
- "scope"
10621
- ];
10622
- var MERGE_ARRAY_KEYS = ["knowledgeBases", "additionalInclude"];
10623
- function isRecord(value) {
10624
- return typeof value === "object" && value !== null && !Array.isArray(value);
10625
- }
10626
- function isStringArray2(value) {
10627
- return Array.isArray(value) && value.every((item) => typeof item === "string");
10628
- }
10629
- function applyProjectOverride(merged, normalizedProjectConfig, globalConfig, key) {
10630
- if (key in normalizedProjectConfig) {
10631
- merged[key] = normalizedProjectConfig[key];
10632
- return;
10633
- }
10634
- if (key in globalConfig) {
10635
- merged[key] = globalConfig[key];
10636
- }
10637
- }
10638
- function mergeUniqueStringArray(values) {
10639
- return [...new Set(values.map((value) => String(value).trim()))];
10640
- }
10641
- function normalizeKnowledgeBasePath(value) {
10642
- let normalized = path14.normalize(String(value).trim());
10643
- const root = path14.parse(normalized).root;
10644
- while (normalized.length > root.length && /[\\/]$/.test(normalized)) {
10645
- normalized = normalized.slice(0, -1);
10646
- }
10647
- return normalized;
10648
- }
10649
- function mergeKnowledgeBasePaths(values) {
10650
- return [...new Set(values.map((value) => normalizeKnowledgeBasePath(value)).filter((value) => value.length > 0))];
10651
- }
10652
- function validateConfigLayerShape(rawConfig, filePath) {
10653
- if (!isRecord(rawConfig)) {
10654
- throw new Error(`Config file ${filePath} must contain a JSON object at the root.`);
10655
- }
10656
- if (rawConfig.knowledgeBases !== void 0 && !isStringArray2(rawConfig.knowledgeBases)) {
10657
- throw new Error(`Config file ${filePath} field 'knowledgeBases' must be an array of strings.`);
10658
- }
10659
- if (rawConfig.additionalInclude !== void 0 && !isStringArray2(rawConfig.additionalInclude)) {
10660
- throw new Error(`Config file ${filePath} field 'additionalInclude' must be an array of strings.`);
10661
- }
10662
- if (rawConfig.include !== void 0 && !isStringArray2(rawConfig.include)) {
10663
- throw new Error(`Config file ${filePath} field 'include' must be an array of strings.`);
10664
- }
10665
- if (rawConfig.exclude !== void 0 && !isStringArray2(rawConfig.exclude)) {
10666
- throw new Error(`Config file ${filePath} field 'exclude' must be an array of strings.`);
10667
- }
10668
- for (const section of ["customProvider", "indexing", "search", "debug", "reranker"]) {
10669
- const value = rawConfig[section];
10670
- if (value !== void 0 && !isRecord(value)) {
10671
- throw new Error(`Config file ${filePath} field '${section}' must be an object.`);
10672
- }
10673
- }
10674
- return rawConfig;
10675
- }
10676
- function loadJsonFile(filePath) {
10677
- if (!existsSync8(filePath)) {
10678
- return null;
10679
- }
10680
- try {
10681
- const content = readFileSync8(filePath, "utf-8");
10682
- return validateConfigLayerShape(JSON.parse(content), filePath);
10683
- } catch (error) {
10684
- if (error instanceof Error && error.message.startsWith("Config file ")) {
10685
- throw error;
10686
- }
10687
- const message = error instanceof Error ? error.message : String(error);
10688
- throw new Error(`Failed to load config file ${filePath}: ${message}`);
10689
- }
10690
- }
10691
- function loadConfigFile(filePath) {
10692
- return loadJsonFile(filePath);
10693
- }
10694
- function materializeLocalProjectConfig(projectRoot, config, host = "opencode") {
10695
- const localConfigPath = resolveWritableProjectConfigPath(projectRoot, host);
10696
- mkdirSync4(path14.dirname(localConfigPath), { recursive: true });
10697
- writeFileSync4(localConfigPath, JSON.stringify(config, null, 2), "utf-8");
10698
- return localConfigPath;
10699
- }
10700
- function loadProjectConfigLayer(projectRoot, host = "opencode") {
10701
- const projectConfigPath = resolveProjectConfigPath(projectRoot, host);
10702
- const projectConfig = loadJsonFile(projectConfigPath);
10703
- if (!projectConfig) {
10704
- return {};
10705
- }
10706
- const normalizedConfig = { ...projectConfig };
10707
- const projectConfigBaseDir = path14.dirname(path14.dirname(projectConfigPath));
10708
- if (Array.isArray(normalizedConfig.knowledgeBases)) {
10709
- normalizedConfig.knowledgeBases = resolveInheritedKnowledgeBaseEntries(
10710
- normalizedConfig.knowledgeBases,
10711
- projectConfigBaseDir,
10712
- projectRoot
10713
- );
10714
- }
10715
- return normalizedConfig;
10716
- }
10717
- function loadMergedConfig(projectRoot, host = "opencode") {
10718
- const globalConfigPath = resolveGlobalConfigPath(host);
10719
- const projectConfigPath = resolveProjectConfigPath(projectRoot, host);
10720
- let globalConfig = null;
10721
- let globalConfigError = null;
10722
- try {
10723
- globalConfig = loadJsonFile(globalConfigPath);
10724
- } catch (error) {
10725
- globalConfigError = error instanceof Error ? error : new Error(String(error));
10726
- }
10727
- const projectConfig = loadJsonFile(projectConfigPath);
10728
- const normalizedProjectConfig = loadProjectConfigLayer(projectRoot, host);
10729
- if (globalConfigError) {
10730
- if (!projectConfig) {
10731
- throw globalConfigError;
10732
- }
10733
- globalConfig = null;
10734
- }
10735
- if (!globalConfig && !projectConfig) {
10736
- return {};
10737
- }
10738
- if (!projectConfig && globalConfig) {
10739
- return globalConfig;
10740
- }
10741
- if (!globalConfig && projectConfig) {
10742
- return normalizedProjectConfig;
10743
- }
10744
- if (!globalConfig || !projectConfig) {
10745
- return globalConfig ?? normalizedProjectConfig;
10746
- }
10747
- const merged = { ...globalConfig };
10748
- for (const key of PROJECT_OVERRIDE_KEYS) {
10749
- applyProjectOverride(merged, normalizedProjectConfig, globalConfig, key);
10750
- }
10751
- if (projectConfig) {
10752
- for (const key of Object.keys(projectConfig)) {
10753
- if (PROJECT_OVERRIDE_KEYS.includes(key) || MERGE_ARRAY_KEYS.includes(key)) {
10754
- continue;
10755
- }
10756
- merged[key] = normalizedProjectConfig[key];
10757
- }
10758
- }
10759
- const globalKbs = globalConfig && Array.isArray(globalConfig.knowledgeBases) ? globalConfig.knowledgeBases : [];
10760
- const projectKbs = projectConfig ? Array.isArray(normalizedProjectConfig.knowledgeBases) ? normalizedProjectConfig.knowledgeBases : [] : [];
10761
- const allKbs = [...globalKbs, ...projectKbs];
10762
- merged.knowledgeBases = mergeKnowledgeBasePaths(allKbs);
10763
- const globalAdditional = globalConfig && Array.isArray(globalConfig.additionalInclude) ? globalConfig.additionalInclude : [];
10764
- const projectAdditional = projectConfig && Array.isArray(projectConfig.additionalInclude) ? projectConfig.additionalInclude : [];
10765
- const allAdditional = [...globalAdditional, ...projectAdditional];
10766
- merged.additionalInclude = mergeUniqueStringArray(allAdditional);
10767
- return merged;
10768
- }
10769
-
10770
- // src/tools/knowledge-base-paths.ts
10771
- import * as path15 from "path";
10772
- function resolveConfigPathValue(value, baseDir) {
10773
- const trimmed = value.trim();
10774
- if (!trimmed) {
10775
- return trimmed;
10776
- }
10777
- const absolutePath = path15.isAbsolute(trimmed) ? trimmed : path15.resolve(baseDir, trimmed);
10778
- return path15.normalize(absolutePath);
10779
- }
10780
-
10781
- // src/tools/utils.ts
10782
- var import_tiktoken = __toESM(require_tiktoken(), 1);
10783
- var MIN_CONTEXT_PACK_TOKEN_BUDGET = 128;
10784
- var MAX_CONTEXT_PACK_TOKEN_BUDGET = 4e3;
10785
- var DEFAULT_CONTEXT_PACK_TOKEN_BUDGET = 1200;
10786
- var CONTEXT_TOKENIZER = (0, import_tiktoken.get_encoding)("cl100k_base");
10787
- function clampContextPackTokenBudget(tokenBudget) {
10788
- if (tokenBudget === void 0 || !Number.isFinite(tokenBudget)) {
10789
- return DEFAULT_CONTEXT_PACK_TOKEN_BUDGET;
10364
+
10365
+ // src/tools/utils.ts
10366
+ import { get_encoding } from "tiktoken";
10367
+ var MIN_CONTEXT_PACK_TOKEN_BUDGET = 128;
10368
+ var MAX_CONTEXT_PACK_TOKEN_BUDGET = 4e3;
10369
+ var DEFAULT_CONTEXT_PACK_TOKEN_BUDGET = 1200;
10370
+ var CONTEXT_TOKENIZER = get_encoding("cl100k_base");
10371
+ function clampContextPackTokenBudget(tokenBudget) {
10372
+ if (tokenBudget === void 0 || !Number.isFinite(tokenBudget)) {
10373
+ return DEFAULT_CONTEXT_PACK_TOKEN_BUDGET;
10790
10374
  }
10791
10375
  return Math.min(
10792
10376
  MAX_CONTEXT_PACK_TOKEN_BUDGET,
@@ -11185,8 +10769,210 @@ ${truncateContent(r.content)}
11185
10769
  }
11186
10770
 
11187
10771
  // src/tools/config-state.ts
11188
- import { existsSync as existsSync9, mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from "fs";
10772
+ import { existsSync as existsSync9, mkdirSync as mkdirSync4, writeFileSync as writeFileSync4 } from "fs";
11189
10773
  import * as path16 from "path";
10774
+
10775
+ // src/config/merger.ts
10776
+ import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
10777
+ import * as path15 from "path";
10778
+
10779
+ // src/config/rebase.ts
10780
+ import * as path14 from "path";
10781
+ function isWithinRoot(rootDir, targetPath) {
10782
+ const relativePath = path14.relative(rootDir, targetPath);
10783
+ return relativePath === "" || !relativePath.startsWith("..") && !path14.isAbsolute(relativePath);
10784
+ }
10785
+ function rebasePathEntries(values, fromDir, toDir) {
10786
+ if (!Array.isArray(values)) {
10787
+ return [];
10788
+ }
10789
+ return values.filter((value) => typeof value === "string").map((value) => {
10790
+ const trimmed = value.trim();
10791
+ if (!trimmed || path14.isAbsolute(trimmed)) {
10792
+ return trimmed;
10793
+ }
10794
+ return normalizePathSeparators(path14.normalize(path14.relative(toDir, path14.resolve(fromDir, trimmed))));
10795
+ }).filter(Boolean);
10796
+ }
10797
+ function resolveInheritedKnowledgeBaseEntries(values, sourceRoot, targetRoot) {
10798
+ if (!Array.isArray(values)) {
10799
+ return [];
10800
+ }
10801
+ return values.filter((value) => typeof value === "string").map((value) => {
10802
+ const trimmed = value.trim();
10803
+ if (!trimmed) {
10804
+ return trimmed;
10805
+ }
10806
+ if (path14.isAbsolute(trimmed)) {
10807
+ if (isWithinRoot(sourceRoot, trimmed)) {
10808
+ return normalizePathSeparators(path14.normalize(path14.relative(sourceRoot, trimmed) || "."));
10809
+ }
10810
+ return path14.normalize(trimmed);
10811
+ }
10812
+ const resolvedFromSource = path14.resolve(sourceRoot, trimmed);
10813
+ if (isWithinRoot(sourceRoot, resolvedFromSource)) {
10814
+ return normalizePathSeparators(path14.normalize(trimmed));
10815
+ }
10816
+ return normalizePathSeparators(path14.normalize(path14.relative(targetRoot, resolvedFromSource)));
10817
+ }).filter(Boolean);
10818
+ }
10819
+
10820
+ // src/config/merger.ts
10821
+ var PROJECT_OVERRIDE_KEYS = [
10822
+ "embeddingProvider",
10823
+ "customProvider",
10824
+ "embeddingModel",
10825
+ "reranker",
10826
+ "include",
10827
+ "exclude",
10828
+ "indexing",
10829
+ "search",
10830
+ "debug",
10831
+ "scope"
10832
+ ];
10833
+ var MERGE_ARRAY_KEYS = ["knowledgeBases", "additionalInclude"];
10834
+ function isRecord(value) {
10835
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10836
+ }
10837
+ function isStringArray2(value) {
10838
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
10839
+ }
10840
+ function applyProjectOverride(merged, normalizedProjectConfig, globalConfig, key) {
10841
+ if (key in normalizedProjectConfig) {
10842
+ merged[key] = normalizedProjectConfig[key];
10843
+ return;
10844
+ }
10845
+ if (key in globalConfig) {
10846
+ merged[key] = globalConfig[key];
10847
+ }
10848
+ }
10849
+ function mergeUniqueStringArray(values) {
10850
+ return [...new Set(values.map((value) => String(value).trim()))];
10851
+ }
10852
+ function normalizeKnowledgeBasePath(value) {
10853
+ let normalized = path15.normalize(String(value).trim());
10854
+ const root = path15.parse(normalized).root;
10855
+ while (normalized.length > root.length && /[\\/]$/.test(normalized)) {
10856
+ normalized = normalized.slice(0, -1);
10857
+ }
10858
+ return normalized;
10859
+ }
10860
+ function mergeKnowledgeBasePaths(values) {
10861
+ return [...new Set(values.map((value) => normalizeKnowledgeBasePath(value)).filter((value) => value.length > 0))];
10862
+ }
10863
+ function validateConfigLayerShape(rawConfig, filePath) {
10864
+ if (!isRecord(rawConfig)) {
10865
+ throw new Error(`Config file ${filePath} must contain a JSON object at the root.`);
10866
+ }
10867
+ if (rawConfig.knowledgeBases !== void 0 && !isStringArray2(rawConfig.knowledgeBases)) {
10868
+ throw new Error(`Config file ${filePath} field 'knowledgeBases' must be an array of strings.`);
10869
+ }
10870
+ if (rawConfig.additionalInclude !== void 0 && !isStringArray2(rawConfig.additionalInclude)) {
10871
+ throw new Error(`Config file ${filePath} field 'additionalInclude' must be an array of strings.`);
10872
+ }
10873
+ if (rawConfig.include !== void 0 && !isStringArray2(rawConfig.include)) {
10874
+ throw new Error(`Config file ${filePath} field 'include' must be an array of strings.`);
10875
+ }
10876
+ if (rawConfig.exclude !== void 0 && !isStringArray2(rawConfig.exclude)) {
10877
+ throw new Error(`Config file ${filePath} field 'exclude' must be an array of strings.`);
10878
+ }
10879
+ for (const section of ["customProvider", "indexing", "search", "debug", "reranker"]) {
10880
+ const value = rawConfig[section];
10881
+ if (value !== void 0 && !isRecord(value)) {
10882
+ throw new Error(`Config file ${filePath} field '${section}' must be an object.`);
10883
+ }
10884
+ }
10885
+ return rawConfig;
10886
+ }
10887
+ function loadJsonFile(filePath) {
10888
+ if (!existsSync8(filePath)) {
10889
+ return null;
10890
+ }
10891
+ try {
10892
+ const content = readFileSync8(filePath, "utf-8");
10893
+ return validateConfigLayerShape(JSON.parse(content), filePath);
10894
+ } catch (error) {
10895
+ if (error instanceof Error && error.message.startsWith("Config file ")) {
10896
+ throw error;
10897
+ }
10898
+ const message = error instanceof Error ? error.message : String(error);
10899
+ throw new Error(`Failed to load config file ${filePath}: ${message}`);
10900
+ }
10901
+ }
10902
+ function loadConfigFile(filePath) {
10903
+ return loadJsonFile(filePath);
10904
+ }
10905
+ function loadProjectConfigLayer(projectRoot, host = "opencode") {
10906
+ const projectConfigPath = resolveProjectConfigPath(projectRoot, host);
10907
+ const projectConfig = loadJsonFile(projectConfigPath);
10908
+ if (!projectConfig) {
10909
+ return {};
10910
+ }
10911
+ const normalizedConfig = { ...projectConfig };
10912
+ const projectConfigBaseDir = path15.dirname(path15.dirname(projectConfigPath));
10913
+ if (Array.isArray(normalizedConfig.knowledgeBases)) {
10914
+ normalizedConfig.knowledgeBases = resolveInheritedKnowledgeBaseEntries(
10915
+ normalizedConfig.knowledgeBases,
10916
+ projectConfigBaseDir,
10917
+ projectRoot
10918
+ );
10919
+ }
10920
+ return normalizedConfig;
10921
+ }
10922
+ function loadMergedConfig(projectRoot, host = "opencode") {
10923
+ const globalConfigPath = resolveGlobalConfigPath(host);
10924
+ const projectConfigPath = resolveProjectConfigPath(projectRoot, host);
10925
+ let globalConfig = null;
10926
+ let globalConfigError = null;
10927
+ try {
10928
+ globalConfig = loadJsonFile(globalConfigPath);
10929
+ } catch (error) {
10930
+ globalConfigError = error instanceof Error ? error : new Error(String(error));
10931
+ }
10932
+ const projectConfig = loadJsonFile(projectConfigPath);
10933
+ const normalizedProjectConfig = loadProjectConfigLayer(projectRoot, host);
10934
+ if (globalConfigError) {
10935
+ if (!projectConfig) {
10936
+ throw globalConfigError;
10937
+ }
10938
+ globalConfig = null;
10939
+ }
10940
+ if (!globalConfig && !projectConfig) {
10941
+ return {};
10942
+ }
10943
+ if (!projectConfig && globalConfig) {
10944
+ return globalConfig;
10945
+ }
10946
+ if (!globalConfig && projectConfig) {
10947
+ return normalizedProjectConfig;
10948
+ }
10949
+ if (!globalConfig || !projectConfig) {
10950
+ return globalConfig ?? normalizedProjectConfig;
10951
+ }
10952
+ const merged = { ...globalConfig };
10953
+ for (const key of PROJECT_OVERRIDE_KEYS) {
10954
+ applyProjectOverride(merged, normalizedProjectConfig, globalConfig, key);
10955
+ }
10956
+ if (projectConfig) {
10957
+ for (const key of Object.keys(projectConfig)) {
10958
+ if (PROJECT_OVERRIDE_KEYS.includes(key) || MERGE_ARRAY_KEYS.includes(key)) {
10959
+ continue;
10960
+ }
10961
+ merged[key] = normalizedProjectConfig[key];
10962
+ }
10963
+ }
10964
+ const globalKbs = globalConfig && Array.isArray(globalConfig.knowledgeBases) ? globalConfig.knowledgeBases : [];
10965
+ const projectKbs = projectConfig ? Array.isArray(normalizedProjectConfig.knowledgeBases) ? normalizedProjectConfig.knowledgeBases : [] : [];
10966
+ const allKbs = [...globalKbs, ...projectKbs];
10967
+ merged.knowledgeBases = mergeKnowledgeBasePaths(allKbs);
10968
+ const globalAdditional = globalConfig && Array.isArray(globalConfig.additionalInclude) ? globalConfig.additionalInclude : [];
10969
+ const projectAdditional = projectConfig && Array.isArray(projectConfig.additionalInclude) ? projectConfig.additionalInclude : [];
10970
+ const allAdditional = [...globalAdditional, ...projectAdditional];
10971
+ merged.additionalInclude = mergeUniqueStringArray(allAdditional);
10972
+ return merged;
10973
+ }
10974
+
10975
+ // src/tools/config-state.ts
11190
10976
  function normalizeKnowledgeBasePaths(config, projectRoot) {
11191
10977
  const normalized = { ...config };
11192
10978
  if (Array.isArray(normalized.knowledgeBases)) {
@@ -11270,15 +11056,6 @@ function refreshIndexerForDirectory(projectRoot, host = "opencode", config = par
11270
11056
  indexerCache.set(key, indexer);
11271
11057
  configCache.set(key, config);
11272
11058
  }
11273
- function shouldForceLocalizeProjectIndex(projectRoot, host = "opencode") {
11274
- const root = getProjectRoot(projectRoot, host);
11275
- const localIndexPath = path17.join(root, getHostProjectIndexRelativePath(host));
11276
- if (existsSync10(localIndexPath)) {
11277
- return false;
11278
- }
11279
- const inheritedIndexPath = resolveWorktreeFallbackProjectIndexPath(root, host);
11280
- return inheritedIndexPath !== null;
11281
- }
11282
11059
  async function searchCodebase(projectRoot, host, query, options = {}) {
11283
11060
  const indexer = getIndexerForProject(projectRoot, host);
11284
11061
  return indexer.search(query, options.limit, {
@@ -11328,9 +11105,7 @@ async function getCallGraphPath(projectRoot, host, from, to, maxDepth) {
11328
11105
  }
11329
11106
  async function runIndexCodebase(projectRoot, host, args, onProgress) {
11330
11107
  const root = getProjectRoot(projectRoot, host);
11331
- const key = getIndexerCacheKey(root, host);
11332
- let indexer = getIndexerForProject(root, host);
11333
- const runtimeConfig = configCache.get(key);
11108
+ const indexer = getIndexerForProject(root, host);
11334
11109
  try {
11335
11110
  if (args.estimateOnly) {
11336
11111
  return { kind: "estimate", estimate: await indexer.estimateCost() };
@@ -11351,19 +11126,7 @@ async function runIndexCodebase(projectRoot, host, args, onProgress) {
11351
11126
  return Promise.resolve();
11352
11127
  });
11353
11128
  };
11354
- let stats;
11355
- if (args.force && shouldForceLocalizeProjectIndex(root, host)) {
11356
- const inheritedIndexPath = resolveProjectIndexPath(root, runtimeConfig.scope, host);
11357
- stats = await withIndexLock(inheritedIndexPath, "force-index", async () => {
11358
- materializeLocalProjectConfig(root, loadProjectConfigLayer(root, host), host);
11359
- refreshIndexerForDirectory(root, host, runtimeConfig);
11360
- indexer = getIndexerForProject(root, host);
11361
- return runIndex(indexer);
11362
- }, { completeRecoveries: false });
11363
- } else {
11364
- stats = await runIndex(indexer);
11365
- }
11366
- return { kind: "stats", stats };
11129
+ return { kind: "stats", stats: await runIndex(indexer) };
11367
11130
  } catch (error) {
11368
11131
  const busyResult = getIndexBusyResult(error);
11369
11132
  if (!busyResult) throw error;
@@ -12021,7 +11784,7 @@ function computeEvalMetrics(queries, perQuery, embeddingCallCount, embeddingToke
12021
11784
  }
12022
11785
 
12023
11786
  // src/eval/runner-config.ts
12024
- import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync9, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
11787
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5, readFileSync as readFileSync9, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "fs";
12025
11788
  import * as os5 from "os";
12026
11789
  import * as path18 from "path";
12027
11790
  function isRecord2(value) {
@@ -12143,8 +11906,8 @@ function ensureLocalEvalProjectConfig(projectRoot, configPath) {
12143
11906
  projectRoot,
12144
11907
  resolvedConfigPath
12145
11908
  );
12146
- mkdirSync6(path18.dirname(localConfigPath), { recursive: true });
12147
- writeFileSync6(localConfigPath, JSON.stringify(sourceConfig, null, 2), "utf-8");
11909
+ mkdirSync5(path18.dirname(localConfigPath), { recursive: true });
11910
+ writeFileSync5(localConfigPath, JSON.stringify(sourceConfig, null, 2), "utf-8");
12148
11911
  return localConfigPath;
12149
11912
  }
12150
11913
  function loadParsedConfig(projectRoot, configPath) {
@@ -16257,7 +16020,7 @@ async function handleVisualizeCommand(argv, cwd) {
16257
16020
  return 1;
16258
16021
  }
16259
16022
  const outputPath = path26.join(os6.tmpdir(), `call-graph-${Date.now()}.html`);
16260
- writeFileSync7(outputPath, generateVisualizationHtml(vizData), "utf-8");
16023
+ writeFileSync6(outputPath, generateVisualizationHtml(vizData), "utf-8");
16261
16024
  console.log(`Temporal call graph visualization generated: ${outputPath}`);
16262
16025
  console.log(`Nodes: ${vizData.nodes.length} | Edges: ${vizData.edges.length}`);
16263
16026
  console.log(`Recent change lenses: ${vizData.changes?.length ?? 0}`);