vidpipe 1.3.11 → 1.3.12

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
@@ -1,13 +1,43 @@
1
1
  #!/usr/bin/env node
2
+ import{createRequire as __cjsRequire}from"module";const require=__cjsRequire(import.meta.url);
3
+ var __create = Object.create;
2
4
  var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
4
15
  var __esm = (fn, res) => function __init() {
5
16
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
17
  };
18
+ var __commonJS = (cb, mod) => function __require2() {
19
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
+ };
7
21
  var __export = (target, all) => {
8
22
  for (var name in all)
9
23
  __defProp(target, name, { get: all[name], enumerable: true });
10
24
  };
25
+ var __copyProps = (to, from, except, desc) => {
26
+ if (from && typeof from === "object" || typeof from === "function") {
27
+ for (let key of __getOwnPropNames(from))
28
+ if (!__hasOwnProp.call(to, key) && key !== except)
29
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
30
+ }
31
+ return to;
32
+ };
33
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
34
+ // If the importer is in node compatibility mode or this is not an ESM
35
+ // file that has been converted to a CommonJS file using a Babel-
36
+ // compatible transform (i.e. "__esModule" has not been set), then set
37
+ // "default" to the CommonJS "module.exports" for node compatibility.
38
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
39
+ mod
40
+ ));
11
41
 
12
42
  // src/L1-infra/paths/paths.ts
13
43
  import { join, resolve, dirname, basename, extname, parse, sep, relative, normalize } from "path";
@@ -778,11 +808,4714 @@ var init_anthropic = __esm({
778
808
  }
779
809
  });
780
810
 
811
+ // node_modules/vscode-jsonrpc/lib/common/is.js
812
+ var require_is = __commonJS({
813
+ "node_modules/vscode-jsonrpc/lib/common/is.js"(exports) {
814
+ "use strict";
815
+ Object.defineProperty(exports, "__esModule", { value: true });
816
+ exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
817
+ function boolean(value) {
818
+ return value === true || value === false;
819
+ }
820
+ exports.boolean = boolean;
821
+ function string(value) {
822
+ return typeof value === "string" || value instanceof String;
823
+ }
824
+ exports.string = string;
825
+ function number(value) {
826
+ return typeof value === "number" || value instanceof Number;
827
+ }
828
+ exports.number = number;
829
+ function error(value) {
830
+ return value instanceof Error;
831
+ }
832
+ exports.error = error;
833
+ function func(value) {
834
+ return typeof value === "function";
835
+ }
836
+ exports.func = func;
837
+ function array(value) {
838
+ return Array.isArray(value);
839
+ }
840
+ exports.array = array;
841
+ function stringArray(value) {
842
+ return array(value) && value.every((elem) => string(elem));
843
+ }
844
+ exports.stringArray = stringArray;
845
+ }
846
+ });
847
+
848
+ // node_modules/vscode-jsonrpc/lib/common/messages.js
849
+ var require_messages = __commonJS({
850
+ "node_modules/vscode-jsonrpc/lib/common/messages.js"(exports) {
851
+ "use strict";
852
+ Object.defineProperty(exports, "__esModule", { value: true });
853
+ exports.Message = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = void 0;
854
+ var is = require_is();
855
+ var ErrorCodes;
856
+ (function(ErrorCodes2) {
857
+ ErrorCodes2.ParseError = -32700;
858
+ ErrorCodes2.InvalidRequest = -32600;
859
+ ErrorCodes2.MethodNotFound = -32601;
860
+ ErrorCodes2.InvalidParams = -32602;
861
+ ErrorCodes2.InternalError = -32603;
862
+ ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099;
863
+ ErrorCodes2.serverErrorStart = -32099;
864
+ ErrorCodes2.MessageWriteError = -32099;
865
+ ErrorCodes2.MessageReadError = -32098;
866
+ ErrorCodes2.PendingResponseRejected = -32097;
867
+ ErrorCodes2.ConnectionInactive = -32096;
868
+ ErrorCodes2.ServerNotInitialized = -32002;
869
+ ErrorCodes2.UnknownErrorCode = -32001;
870
+ ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32e3;
871
+ ErrorCodes2.serverErrorEnd = -32e3;
872
+ })(ErrorCodes || (exports.ErrorCodes = ErrorCodes = {}));
873
+ var ResponseError = class _ResponseError extends Error {
874
+ constructor(code, message, data) {
875
+ super(message);
876
+ this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
877
+ this.data = data;
878
+ Object.setPrototypeOf(this, _ResponseError.prototype);
879
+ }
880
+ toJson() {
881
+ const result = {
882
+ code: this.code,
883
+ message: this.message
884
+ };
885
+ if (this.data !== void 0) {
886
+ result.data = this.data;
887
+ }
888
+ return result;
889
+ }
890
+ };
891
+ exports.ResponseError = ResponseError;
892
+ var ParameterStructures = class _ParameterStructures {
893
+ constructor(kind) {
894
+ this.kind = kind;
895
+ }
896
+ static is(value) {
897
+ return value === _ParameterStructures.auto || value === _ParameterStructures.byName || value === _ParameterStructures.byPosition;
898
+ }
899
+ toString() {
900
+ return this.kind;
901
+ }
902
+ };
903
+ exports.ParameterStructures = ParameterStructures;
904
+ ParameterStructures.auto = new ParameterStructures("auto");
905
+ ParameterStructures.byPosition = new ParameterStructures("byPosition");
906
+ ParameterStructures.byName = new ParameterStructures("byName");
907
+ var AbstractMessageSignature = class {
908
+ constructor(method, numberOfParams) {
909
+ this.method = method;
910
+ this.numberOfParams = numberOfParams;
911
+ }
912
+ get parameterStructures() {
913
+ return ParameterStructures.auto;
914
+ }
915
+ };
916
+ exports.AbstractMessageSignature = AbstractMessageSignature;
917
+ var RequestType0 = class extends AbstractMessageSignature {
918
+ constructor(method) {
919
+ super(method, 0);
920
+ }
921
+ };
922
+ exports.RequestType0 = RequestType0;
923
+ var RequestType = class extends AbstractMessageSignature {
924
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
925
+ super(method, 1);
926
+ this._parameterStructures = _parameterStructures;
927
+ }
928
+ get parameterStructures() {
929
+ return this._parameterStructures;
930
+ }
931
+ };
932
+ exports.RequestType = RequestType;
933
+ var RequestType1 = class extends AbstractMessageSignature {
934
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
935
+ super(method, 1);
936
+ this._parameterStructures = _parameterStructures;
937
+ }
938
+ get parameterStructures() {
939
+ return this._parameterStructures;
940
+ }
941
+ };
942
+ exports.RequestType1 = RequestType1;
943
+ var RequestType2 = class extends AbstractMessageSignature {
944
+ constructor(method) {
945
+ super(method, 2);
946
+ }
947
+ };
948
+ exports.RequestType2 = RequestType2;
949
+ var RequestType3 = class extends AbstractMessageSignature {
950
+ constructor(method) {
951
+ super(method, 3);
952
+ }
953
+ };
954
+ exports.RequestType3 = RequestType3;
955
+ var RequestType4 = class extends AbstractMessageSignature {
956
+ constructor(method) {
957
+ super(method, 4);
958
+ }
959
+ };
960
+ exports.RequestType4 = RequestType4;
961
+ var RequestType5 = class extends AbstractMessageSignature {
962
+ constructor(method) {
963
+ super(method, 5);
964
+ }
965
+ };
966
+ exports.RequestType5 = RequestType5;
967
+ var RequestType6 = class extends AbstractMessageSignature {
968
+ constructor(method) {
969
+ super(method, 6);
970
+ }
971
+ };
972
+ exports.RequestType6 = RequestType6;
973
+ var RequestType7 = class extends AbstractMessageSignature {
974
+ constructor(method) {
975
+ super(method, 7);
976
+ }
977
+ };
978
+ exports.RequestType7 = RequestType7;
979
+ var RequestType8 = class extends AbstractMessageSignature {
980
+ constructor(method) {
981
+ super(method, 8);
982
+ }
983
+ };
984
+ exports.RequestType8 = RequestType8;
985
+ var RequestType9 = class extends AbstractMessageSignature {
986
+ constructor(method) {
987
+ super(method, 9);
988
+ }
989
+ };
990
+ exports.RequestType9 = RequestType9;
991
+ var NotificationType = class extends AbstractMessageSignature {
992
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
993
+ super(method, 1);
994
+ this._parameterStructures = _parameterStructures;
995
+ }
996
+ get parameterStructures() {
997
+ return this._parameterStructures;
998
+ }
999
+ };
1000
+ exports.NotificationType = NotificationType;
1001
+ var NotificationType0 = class extends AbstractMessageSignature {
1002
+ constructor(method) {
1003
+ super(method, 0);
1004
+ }
1005
+ };
1006
+ exports.NotificationType0 = NotificationType0;
1007
+ var NotificationType1 = class extends AbstractMessageSignature {
1008
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
1009
+ super(method, 1);
1010
+ this._parameterStructures = _parameterStructures;
1011
+ }
1012
+ get parameterStructures() {
1013
+ return this._parameterStructures;
1014
+ }
1015
+ };
1016
+ exports.NotificationType1 = NotificationType1;
1017
+ var NotificationType2 = class extends AbstractMessageSignature {
1018
+ constructor(method) {
1019
+ super(method, 2);
1020
+ }
1021
+ };
1022
+ exports.NotificationType2 = NotificationType2;
1023
+ var NotificationType3 = class extends AbstractMessageSignature {
1024
+ constructor(method) {
1025
+ super(method, 3);
1026
+ }
1027
+ };
1028
+ exports.NotificationType3 = NotificationType3;
1029
+ var NotificationType4 = class extends AbstractMessageSignature {
1030
+ constructor(method) {
1031
+ super(method, 4);
1032
+ }
1033
+ };
1034
+ exports.NotificationType4 = NotificationType4;
1035
+ var NotificationType5 = class extends AbstractMessageSignature {
1036
+ constructor(method) {
1037
+ super(method, 5);
1038
+ }
1039
+ };
1040
+ exports.NotificationType5 = NotificationType5;
1041
+ var NotificationType6 = class extends AbstractMessageSignature {
1042
+ constructor(method) {
1043
+ super(method, 6);
1044
+ }
1045
+ };
1046
+ exports.NotificationType6 = NotificationType6;
1047
+ var NotificationType7 = class extends AbstractMessageSignature {
1048
+ constructor(method) {
1049
+ super(method, 7);
1050
+ }
1051
+ };
1052
+ exports.NotificationType7 = NotificationType7;
1053
+ var NotificationType8 = class extends AbstractMessageSignature {
1054
+ constructor(method) {
1055
+ super(method, 8);
1056
+ }
1057
+ };
1058
+ exports.NotificationType8 = NotificationType8;
1059
+ var NotificationType9 = class extends AbstractMessageSignature {
1060
+ constructor(method) {
1061
+ super(method, 9);
1062
+ }
1063
+ };
1064
+ exports.NotificationType9 = NotificationType9;
1065
+ var Message;
1066
+ (function(Message2) {
1067
+ function isRequest(message) {
1068
+ const candidate = message;
1069
+ return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
1070
+ }
1071
+ Message2.isRequest = isRequest;
1072
+ function isNotification(message) {
1073
+ const candidate = message;
1074
+ return candidate && is.string(candidate.method) && message.id === void 0;
1075
+ }
1076
+ Message2.isNotification = isNotification;
1077
+ function isResponse(message) {
1078
+ const candidate = message;
1079
+ return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
1080
+ }
1081
+ Message2.isResponse = isResponse;
1082
+ })(Message || (exports.Message = Message = {}));
1083
+ }
1084
+ });
1085
+
1086
+ // node_modules/vscode-jsonrpc/lib/common/linkedMap.js
1087
+ var require_linkedMap = __commonJS({
1088
+ "node_modules/vscode-jsonrpc/lib/common/linkedMap.js"(exports) {
1089
+ "use strict";
1090
+ var _a;
1091
+ Object.defineProperty(exports, "__esModule", { value: true });
1092
+ exports.LRUCache = exports.LinkedMap = exports.Touch = void 0;
1093
+ var Touch;
1094
+ (function(Touch2) {
1095
+ Touch2.None = 0;
1096
+ Touch2.First = 1;
1097
+ Touch2.AsOld = Touch2.First;
1098
+ Touch2.Last = 2;
1099
+ Touch2.AsNew = Touch2.Last;
1100
+ })(Touch || (exports.Touch = Touch = {}));
1101
+ var LinkedMap = class {
1102
+ constructor() {
1103
+ this[_a] = "LinkedMap";
1104
+ this._map = /* @__PURE__ */ new Map();
1105
+ this._head = void 0;
1106
+ this._tail = void 0;
1107
+ this._size = 0;
1108
+ this._state = 0;
1109
+ }
1110
+ clear() {
1111
+ this._map.clear();
1112
+ this._head = void 0;
1113
+ this._tail = void 0;
1114
+ this._size = 0;
1115
+ this._state++;
1116
+ }
1117
+ isEmpty() {
1118
+ return !this._head && !this._tail;
1119
+ }
1120
+ get size() {
1121
+ return this._size;
1122
+ }
1123
+ get first() {
1124
+ return this._head?.value;
1125
+ }
1126
+ get last() {
1127
+ return this._tail?.value;
1128
+ }
1129
+ has(key) {
1130
+ return this._map.has(key);
1131
+ }
1132
+ get(key, touch = Touch.None) {
1133
+ const item = this._map.get(key);
1134
+ if (!item) {
1135
+ return void 0;
1136
+ }
1137
+ if (touch !== Touch.None) {
1138
+ this.touch(item, touch);
1139
+ }
1140
+ return item.value;
1141
+ }
1142
+ set(key, value, touch = Touch.None) {
1143
+ let item = this._map.get(key);
1144
+ if (item) {
1145
+ item.value = value;
1146
+ if (touch !== Touch.None) {
1147
+ this.touch(item, touch);
1148
+ }
1149
+ } else {
1150
+ item = { key, value, next: void 0, previous: void 0 };
1151
+ switch (touch) {
1152
+ case Touch.None:
1153
+ this.addItemLast(item);
1154
+ break;
1155
+ case Touch.First:
1156
+ this.addItemFirst(item);
1157
+ break;
1158
+ case Touch.Last:
1159
+ this.addItemLast(item);
1160
+ break;
1161
+ default:
1162
+ this.addItemLast(item);
1163
+ break;
1164
+ }
1165
+ this._map.set(key, item);
1166
+ this._size++;
1167
+ }
1168
+ return this;
1169
+ }
1170
+ delete(key) {
1171
+ return !!this.remove(key);
1172
+ }
1173
+ remove(key) {
1174
+ const item = this._map.get(key);
1175
+ if (!item) {
1176
+ return void 0;
1177
+ }
1178
+ this._map.delete(key);
1179
+ this.removeItem(item);
1180
+ this._size--;
1181
+ return item.value;
1182
+ }
1183
+ shift() {
1184
+ if (!this._head && !this._tail) {
1185
+ return void 0;
1186
+ }
1187
+ if (!this._head || !this._tail) {
1188
+ throw new Error("Invalid list");
1189
+ }
1190
+ const item = this._head;
1191
+ this._map.delete(item.key);
1192
+ this.removeItem(item);
1193
+ this._size--;
1194
+ return item.value;
1195
+ }
1196
+ forEach(callbackfn, thisArg) {
1197
+ const state = this._state;
1198
+ let current = this._head;
1199
+ while (current) {
1200
+ if (thisArg) {
1201
+ callbackfn.bind(thisArg)(current.value, current.key, this);
1202
+ } else {
1203
+ callbackfn(current.value, current.key, this);
1204
+ }
1205
+ if (this._state !== state) {
1206
+ throw new Error(`LinkedMap got modified during iteration.`);
1207
+ }
1208
+ current = current.next;
1209
+ }
1210
+ }
1211
+ keys() {
1212
+ const state = this._state;
1213
+ let current = this._head;
1214
+ const iterator = {
1215
+ [Symbol.iterator]: () => {
1216
+ return iterator;
1217
+ },
1218
+ next: () => {
1219
+ if (this._state !== state) {
1220
+ throw new Error(`LinkedMap got modified during iteration.`);
1221
+ }
1222
+ if (current) {
1223
+ const result = { value: current.key, done: false };
1224
+ current = current.next;
1225
+ return result;
1226
+ } else {
1227
+ return { value: void 0, done: true };
1228
+ }
1229
+ }
1230
+ };
1231
+ return iterator;
1232
+ }
1233
+ values() {
1234
+ const state = this._state;
1235
+ let current = this._head;
1236
+ const iterator = {
1237
+ [Symbol.iterator]: () => {
1238
+ return iterator;
1239
+ },
1240
+ next: () => {
1241
+ if (this._state !== state) {
1242
+ throw new Error(`LinkedMap got modified during iteration.`);
1243
+ }
1244
+ if (current) {
1245
+ const result = { value: current.value, done: false };
1246
+ current = current.next;
1247
+ return result;
1248
+ } else {
1249
+ return { value: void 0, done: true };
1250
+ }
1251
+ }
1252
+ };
1253
+ return iterator;
1254
+ }
1255
+ entries() {
1256
+ const state = this._state;
1257
+ let current = this._head;
1258
+ const iterator = {
1259
+ [Symbol.iterator]: () => {
1260
+ return iterator;
1261
+ },
1262
+ next: () => {
1263
+ if (this._state !== state) {
1264
+ throw new Error(`LinkedMap got modified during iteration.`);
1265
+ }
1266
+ if (current) {
1267
+ const result = { value: [current.key, current.value], done: false };
1268
+ current = current.next;
1269
+ return result;
1270
+ } else {
1271
+ return { value: void 0, done: true };
1272
+ }
1273
+ }
1274
+ };
1275
+ return iterator;
1276
+ }
1277
+ [(_a = Symbol.toStringTag, Symbol.iterator)]() {
1278
+ return this.entries();
1279
+ }
1280
+ trimOld(newSize) {
1281
+ if (newSize >= this.size) {
1282
+ return;
1283
+ }
1284
+ if (newSize === 0) {
1285
+ this.clear();
1286
+ return;
1287
+ }
1288
+ let current = this._head;
1289
+ let currentSize = this.size;
1290
+ while (current && currentSize > newSize) {
1291
+ this._map.delete(current.key);
1292
+ current = current.next;
1293
+ currentSize--;
1294
+ }
1295
+ this._head = current;
1296
+ this._size = currentSize;
1297
+ if (current) {
1298
+ current.previous = void 0;
1299
+ }
1300
+ this._state++;
1301
+ }
1302
+ addItemFirst(item) {
1303
+ if (!this._head && !this._tail) {
1304
+ this._tail = item;
1305
+ } else if (!this._head) {
1306
+ throw new Error("Invalid list");
1307
+ } else {
1308
+ item.next = this._head;
1309
+ this._head.previous = item;
1310
+ }
1311
+ this._head = item;
1312
+ this._state++;
1313
+ }
1314
+ addItemLast(item) {
1315
+ if (!this._head && !this._tail) {
1316
+ this._head = item;
1317
+ } else if (!this._tail) {
1318
+ throw new Error("Invalid list");
1319
+ } else {
1320
+ item.previous = this._tail;
1321
+ this._tail.next = item;
1322
+ }
1323
+ this._tail = item;
1324
+ this._state++;
1325
+ }
1326
+ removeItem(item) {
1327
+ if (item === this._head && item === this._tail) {
1328
+ this._head = void 0;
1329
+ this._tail = void 0;
1330
+ } else if (item === this._head) {
1331
+ if (!item.next) {
1332
+ throw new Error("Invalid list");
1333
+ }
1334
+ item.next.previous = void 0;
1335
+ this._head = item.next;
1336
+ } else if (item === this._tail) {
1337
+ if (!item.previous) {
1338
+ throw new Error("Invalid list");
1339
+ }
1340
+ item.previous.next = void 0;
1341
+ this._tail = item.previous;
1342
+ } else {
1343
+ const next = item.next;
1344
+ const previous = item.previous;
1345
+ if (!next || !previous) {
1346
+ throw new Error("Invalid list");
1347
+ }
1348
+ next.previous = previous;
1349
+ previous.next = next;
1350
+ }
1351
+ item.next = void 0;
1352
+ item.previous = void 0;
1353
+ this._state++;
1354
+ }
1355
+ touch(item, touch) {
1356
+ if (!this._head || !this._tail) {
1357
+ throw new Error("Invalid list");
1358
+ }
1359
+ if (touch !== Touch.First && touch !== Touch.Last) {
1360
+ return;
1361
+ }
1362
+ if (touch === Touch.First) {
1363
+ if (item === this._head) {
1364
+ return;
1365
+ }
1366
+ const next = item.next;
1367
+ const previous = item.previous;
1368
+ if (item === this._tail) {
1369
+ previous.next = void 0;
1370
+ this._tail = previous;
1371
+ } else {
1372
+ next.previous = previous;
1373
+ previous.next = next;
1374
+ }
1375
+ item.previous = void 0;
1376
+ item.next = this._head;
1377
+ this._head.previous = item;
1378
+ this._head = item;
1379
+ this._state++;
1380
+ } else if (touch === Touch.Last) {
1381
+ if (item === this._tail) {
1382
+ return;
1383
+ }
1384
+ const next = item.next;
1385
+ const previous = item.previous;
1386
+ if (item === this._head) {
1387
+ next.previous = void 0;
1388
+ this._head = next;
1389
+ } else {
1390
+ next.previous = previous;
1391
+ previous.next = next;
1392
+ }
1393
+ item.next = void 0;
1394
+ item.previous = this._tail;
1395
+ this._tail.next = item;
1396
+ this._tail = item;
1397
+ this._state++;
1398
+ }
1399
+ }
1400
+ toJSON() {
1401
+ const data = [];
1402
+ this.forEach((value, key) => {
1403
+ data.push([key, value]);
1404
+ });
1405
+ return data;
1406
+ }
1407
+ fromJSON(data) {
1408
+ this.clear();
1409
+ for (const [key, value] of data) {
1410
+ this.set(key, value);
1411
+ }
1412
+ }
1413
+ };
1414
+ exports.LinkedMap = LinkedMap;
1415
+ var LRUCache = class extends LinkedMap {
1416
+ constructor(limit, ratio = 1) {
1417
+ super();
1418
+ this._limit = limit;
1419
+ this._ratio = Math.min(Math.max(0, ratio), 1);
1420
+ }
1421
+ get limit() {
1422
+ return this._limit;
1423
+ }
1424
+ set limit(limit) {
1425
+ this._limit = limit;
1426
+ this.checkTrim();
1427
+ }
1428
+ get ratio() {
1429
+ return this._ratio;
1430
+ }
1431
+ set ratio(ratio) {
1432
+ this._ratio = Math.min(Math.max(0, ratio), 1);
1433
+ this.checkTrim();
1434
+ }
1435
+ get(key, touch = Touch.AsNew) {
1436
+ return super.get(key, touch);
1437
+ }
1438
+ peek(key) {
1439
+ return super.get(key, Touch.None);
1440
+ }
1441
+ set(key, value) {
1442
+ super.set(key, value, Touch.Last);
1443
+ this.checkTrim();
1444
+ return this;
1445
+ }
1446
+ checkTrim() {
1447
+ if (this.size > this._limit) {
1448
+ this.trimOld(Math.round(this._limit * this._ratio));
1449
+ }
1450
+ }
1451
+ };
1452
+ exports.LRUCache = LRUCache;
1453
+ }
1454
+ });
1455
+
1456
+ // node_modules/vscode-jsonrpc/lib/common/disposable.js
1457
+ var require_disposable = __commonJS({
1458
+ "node_modules/vscode-jsonrpc/lib/common/disposable.js"(exports) {
1459
+ "use strict";
1460
+ Object.defineProperty(exports, "__esModule", { value: true });
1461
+ exports.Disposable = void 0;
1462
+ var Disposable;
1463
+ (function(Disposable2) {
1464
+ function create(func) {
1465
+ return {
1466
+ dispose: func
1467
+ };
1468
+ }
1469
+ Disposable2.create = create;
1470
+ })(Disposable || (exports.Disposable = Disposable = {}));
1471
+ }
1472
+ });
1473
+
1474
+ // node_modules/vscode-jsonrpc/lib/common/ral.js
1475
+ var require_ral = __commonJS({
1476
+ "node_modules/vscode-jsonrpc/lib/common/ral.js"(exports) {
1477
+ "use strict";
1478
+ Object.defineProperty(exports, "__esModule", { value: true });
1479
+ var _ral;
1480
+ function RAL() {
1481
+ if (_ral === void 0) {
1482
+ throw new Error(`No runtime abstraction layer installed`);
1483
+ }
1484
+ return _ral;
1485
+ }
1486
+ (function(RAL2) {
1487
+ function install(ral) {
1488
+ if (ral === void 0) {
1489
+ throw new Error(`No runtime abstraction layer provided`);
1490
+ }
1491
+ _ral = ral;
1492
+ }
1493
+ RAL2.install = install;
1494
+ })(RAL || (RAL = {}));
1495
+ exports.default = RAL;
1496
+ }
1497
+ });
1498
+
1499
+ // node_modules/vscode-jsonrpc/lib/common/events.js
1500
+ var require_events = __commonJS({
1501
+ "node_modules/vscode-jsonrpc/lib/common/events.js"(exports) {
1502
+ "use strict";
1503
+ Object.defineProperty(exports, "__esModule", { value: true });
1504
+ exports.Emitter = exports.Event = void 0;
1505
+ var ral_1 = require_ral();
1506
+ var Event;
1507
+ (function(Event2) {
1508
+ const _disposable = { dispose() {
1509
+ } };
1510
+ Event2.None = function() {
1511
+ return _disposable;
1512
+ };
1513
+ })(Event || (exports.Event = Event = {}));
1514
+ var CallbackList = class {
1515
+ add(callback, context = null, bucket) {
1516
+ if (!this._callbacks) {
1517
+ this._callbacks = [];
1518
+ this._contexts = [];
1519
+ }
1520
+ this._callbacks.push(callback);
1521
+ this._contexts.push(context);
1522
+ if (Array.isArray(bucket)) {
1523
+ bucket.push({ dispose: () => this.remove(callback, context) });
1524
+ }
1525
+ }
1526
+ remove(callback, context = null) {
1527
+ if (!this._callbacks) {
1528
+ return;
1529
+ }
1530
+ let foundCallbackWithDifferentContext = false;
1531
+ for (let i = 0, len = this._callbacks.length; i < len; i++) {
1532
+ if (this._callbacks[i] === callback) {
1533
+ if (this._contexts[i] === context) {
1534
+ this._callbacks.splice(i, 1);
1535
+ this._contexts.splice(i, 1);
1536
+ return;
1537
+ } else {
1538
+ foundCallbackWithDifferentContext = true;
1539
+ }
1540
+ }
1541
+ }
1542
+ if (foundCallbackWithDifferentContext) {
1543
+ throw new Error("When adding a listener with a context, you should remove it with the same context");
1544
+ }
1545
+ }
1546
+ invoke(...args) {
1547
+ if (!this._callbacks) {
1548
+ return [];
1549
+ }
1550
+ const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
1551
+ for (let i = 0, len = callbacks.length; i < len; i++) {
1552
+ try {
1553
+ ret.push(callbacks[i].apply(contexts[i], args));
1554
+ } catch (e) {
1555
+ (0, ral_1.default)().console.error(e);
1556
+ }
1557
+ }
1558
+ return ret;
1559
+ }
1560
+ isEmpty() {
1561
+ return !this._callbacks || this._callbacks.length === 0;
1562
+ }
1563
+ dispose() {
1564
+ this._callbacks = void 0;
1565
+ this._contexts = void 0;
1566
+ }
1567
+ };
1568
+ var Emitter = class _Emitter {
1569
+ constructor(_options) {
1570
+ this._options = _options;
1571
+ }
1572
+ /**
1573
+ * For the public to allow to subscribe
1574
+ * to events from this Emitter
1575
+ */
1576
+ get event() {
1577
+ if (!this._event) {
1578
+ this._event = (listener, thisArgs, disposables) => {
1579
+ if (!this._callbacks) {
1580
+ this._callbacks = new CallbackList();
1581
+ }
1582
+ if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
1583
+ this._options.onFirstListenerAdd(this);
1584
+ }
1585
+ this._callbacks.add(listener, thisArgs);
1586
+ const result = {
1587
+ dispose: () => {
1588
+ if (!this._callbacks) {
1589
+ return;
1590
+ }
1591
+ this._callbacks.remove(listener, thisArgs);
1592
+ result.dispose = _Emitter._noop;
1593
+ if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
1594
+ this._options.onLastListenerRemove(this);
1595
+ }
1596
+ }
1597
+ };
1598
+ if (Array.isArray(disposables)) {
1599
+ disposables.push(result);
1600
+ }
1601
+ return result;
1602
+ };
1603
+ }
1604
+ return this._event;
1605
+ }
1606
+ /**
1607
+ * To be kept private to fire an event to
1608
+ * subscribers
1609
+ */
1610
+ fire(event) {
1611
+ if (this._callbacks) {
1612
+ this._callbacks.invoke.call(this._callbacks, event);
1613
+ }
1614
+ }
1615
+ dispose() {
1616
+ if (this._callbacks) {
1617
+ this._callbacks.dispose();
1618
+ this._callbacks = void 0;
1619
+ }
1620
+ }
1621
+ };
1622
+ exports.Emitter = Emitter;
1623
+ Emitter._noop = function() {
1624
+ };
1625
+ }
1626
+ });
1627
+
1628
+ // node_modules/vscode-jsonrpc/lib/common/cancellation.js
1629
+ var require_cancellation = __commonJS({
1630
+ "node_modules/vscode-jsonrpc/lib/common/cancellation.js"(exports) {
1631
+ "use strict";
1632
+ Object.defineProperty(exports, "__esModule", { value: true });
1633
+ exports.CancellationTokenSource = exports.CancellationToken = void 0;
1634
+ var ral_1 = require_ral();
1635
+ var Is = require_is();
1636
+ var events_1 = require_events();
1637
+ var CancellationToken;
1638
+ (function(CancellationToken2) {
1639
+ CancellationToken2.None = Object.freeze({
1640
+ isCancellationRequested: false,
1641
+ onCancellationRequested: events_1.Event.None
1642
+ });
1643
+ CancellationToken2.Cancelled = Object.freeze({
1644
+ isCancellationRequested: true,
1645
+ onCancellationRequested: events_1.Event.None
1646
+ });
1647
+ function is(value) {
1648
+ const candidate = value;
1649
+ return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
1650
+ }
1651
+ CancellationToken2.is = is;
1652
+ })(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
1653
+ var shortcutEvent = Object.freeze(function(callback, context) {
1654
+ const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
1655
+ return { dispose() {
1656
+ handle.dispose();
1657
+ } };
1658
+ });
1659
+ var MutableToken = class {
1660
+ constructor() {
1661
+ this._isCancelled = false;
1662
+ }
1663
+ cancel() {
1664
+ if (!this._isCancelled) {
1665
+ this._isCancelled = true;
1666
+ if (this._emitter) {
1667
+ this._emitter.fire(void 0);
1668
+ this.dispose();
1669
+ }
1670
+ }
1671
+ }
1672
+ get isCancellationRequested() {
1673
+ return this._isCancelled;
1674
+ }
1675
+ get onCancellationRequested() {
1676
+ if (this._isCancelled) {
1677
+ return shortcutEvent;
1678
+ }
1679
+ if (!this._emitter) {
1680
+ this._emitter = new events_1.Emitter();
1681
+ }
1682
+ return this._emitter.event;
1683
+ }
1684
+ dispose() {
1685
+ if (this._emitter) {
1686
+ this._emitter.dispose();
1687
+ this._emitter = void 0;
1688
+ }
1689
+ }
1690
+ };
1691
+ var CancellationTokenSource = class {
1692
+ get token() {
1693
+ if (!this._token) {
1694
+ this._token = new MutableToken();
1695
+ }
1696
+ return this._token;
1697
+ }
1698
+ cancel() {
1699
+ if (!this._token) {
1700
+ this._token = CancellationToken.Cancelled;
1701
+ } else {
1702
+ this._token.cancel();
1703
+ }
1704
+ }
1705
+ dispose() {
1706
+ if (!this._token) {
1707
+ this._token = CancellationToken.None;
1708
+ } else if (this._token instanceof MutableToken) {
1709
+ this._token.dispose();
1710
+ }
1711
+ }
1712
+ };
1713
+ exports.CancellationTokenSource = CancellationTokenSource;
1714
+ }
1715
+ });
1716
+
1717
+ // node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js
1718
+ var require_sharedArrayCancellation = __commonJS({
1719
+ "node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js"(exports) {
1720
+ "use strict";
1721
+ Object.defineProperty(exports, "__esModule", { value: true });
1722
+ exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = void 0;
1723
+ var cancellation_1 = require_cancellation();
1724
+ var CancellationState;
1725
+ (function(CancellationState2) {
1726
+ CancellationState2.Continue = 0;
1727
+ CancellationState2.Cancelled = 1;
1728
+ })(CancellationState || (CancellationState = {}));
1729
+ var SharedArraySenderStrategy = class {
1730
+ constructor() {
1731
+ this.buffers = /* @__PURE__ */ new Map();
1732
+ }
1733
+ enableCancellation(request) {
1734
+ if (request.id === null) {
1735
+ return;
1736
+ }
1737
+ const buffer = new SharedArrayBuffer(4);
1738
+ const data = new Int32Array(buffer, 0, 1);
1739
+ data[0] = CancellationState.Continue;
1740
+ this.buffers.set(request.id, buffer);
1741
+ request.$cancellationData = buffer;
1742
+ }
1743
+ async sendCancellation(_conn, id) {
1744
+ const buffer = this.buffers.get(id);
1745
+ if (buffer === void 0) {
1746
+ return;
1747
+ }
1748
+ const data = new Int32Array(buffer, 0, 1);
1749
+ Atomics.store(data, 0, CancellationState.Cancelled);
1750
+ }
1751
+ cleanup(id) {
1752
+ this.buffers.delete(id);
1753
+ }
1754
+ dispose() {
1755
+ this.buffers.clear();
1756
+ }
1757
+ };
1758
+ exports.SharedArraySenderStrategy = SharedArraySenderStrategy;
1759
+ var SharedArrayBufferCancellationToken = class {
1760
+ constructor(buffer) {
1761
+ this.data = new Int32Array(buffer, 0, 1);
1762
+ }
1763
+ get isCancellationRequested() {
1764
+ return Atomics.load(this.data, 0) === CancellationState.Cancelled;
1765
+ }
1766
+ get onCancellationRequested() {
1767
+ throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
1768
+ }
1769
+ };
1770
+ var SharedArrayBufferCancellationTokenSource = class {
1771
+ constructor(buffer) {
1772
+ this.token = new SharedArrayBufferCancellationToken(buffer);
1773
+ }
1774
+ cancel() {
1775
+ }
1776
+ dispose() {
1777
+ }
1778
+ };
1779
+ var SharedArrayReceiverStrategy = class {
1780
+ constructor() {
1781
+ this.kind = "request";
1782
+ }
1783
+ createCancellationTokenSource(request) {
1784
+ const buffer = request.$cancellationData;
1785
+ if (buffer === void 0) {
1786
+ return new cancellation_1.CancellationTokenSource();
1787
+ }
1788
+ return new SharedArrayBufferCancellationTokenSource(buffer);
1789
+ }
1790
+ };
1791
+ exports.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
1792
+ }
1793
+ });
1794
+
1795
+ // node_modules/vscode-jsonrpc/lib/common/semaphore.js
1796
+ var require_semaphore = __commonJS({
1797
+ "node_modules/vscode-jsonrpc/lib/common/semaphore.js"(exports) {
1798
+ "use strict";
1799
+ Object.defineProperty(exports, "__esModule", { value: true });
1800
+ exports.Semaphore = void 0;
1801
+ var ral_1 = require_ral();
1802
+ var Semaphore = class {
1803
+ constructor(capacity = 1) {
1804
+ if (capacity <= 0) {
1805
+ throw new Error("Capacity must be greater than 0");
1806
+ }
1807
+ this._capacity = capacity;
1808
+ this._active = 0;
1809
+ this._waiting = [];
1810
+ }
1811
+ lock(thunk) {
1812
+ return new Promise((resolve3, reject) => {
1813
+ this._waiting.push({ thunk, resolve: resolve3, reject });
1814
+ this.runNext();
1815
+ });
1816
+ }
1817
+ get active() {
1818
+ return this._active;
1819
+ }
1820
+ runNext() {
1821
+ if (this._waiting.length === 0 || this._active === this._capacity) {
1822
+ return;
1823
+ }
1824
+ (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
1825
+ }
1826
+ doRunNext() {
1827
+ if (this._waiting.length === 0 || this._active === this._capacity) {
1828
+ return;
1829
+ }
1830
+ const next = this._waiting.shift();
1831
+ this._active++;
1832
+ if (this._active > this._capacity) {
1833
+ throw new Error(`To many thunks active`);
1834
+ }
1835
+ try {
1836
+ const result = next.thunk();
1837
+ if (result instanceof Promise) {
1838
+ result.then((value) => {
1839
+ this._active--;
1840
+ next.resolve(value);
1841
+ this.runNext();
1842
+ }, (err) => {
1843
+ this._active--;
1844
+ next.reject(err);
1845
+ this.runNext();
1846
+ });
1847
+ } else {
1848
+ this._active--;
1849
+ next.resolve(result);
1850
+ this.runNext();
1851
+ }
1852
+ } catch (err) {
1853
+ this._active--;
1854
+ next.reject(err);
1855
+ this.runNext();
1856
+ }
1857
+ }
1858
+ };
1859
+ exports.Semaphore = Semaphore;
1860
+ }
1861
+ });
1862
+
1863
+ // node_modules/vscode-jsonrpc/lib/common/messageReader.js
1864
+ var require_messageReader = __commonJS({
1865
+ "node_modules/vscode-jsonrpc/lib/common/messageReader.js"(exports) {
1866
+ "use strict";
1867
+ Object.defineProperty(exports, "__esModule", { value: true });
1868
+ exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = void 0;
1869
+ var ral_1 = require_ral();
1870
+ var Is = require_is();
1871
+ var events_1 = require_events();
1872
+ var semaphore_1 = require_semaphore();
1873
+ var MessageReader;
1874
+ (function(MessageReader2) {
1875
+ function is(value) {
1876
+ let candidate = value;
1877
+ return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
1878
+ }
1879
+ MessageReader2.is = is;
1880
+ })(MessageReader || (exports.MessageReader = MessageReader = {}));
1881
+ var AbstractMessageReader = class {
1882
+ constructor() {
1883
+ this.errorEmitter = new events_1.Emitter();
1884
+ this.closeEmitter = new events_1.Emitter();
1885
+ this.partialMessageEmitter = new events_1.Emitter();
1886
+ }
1887
+ dispose() {
1888
+ this.errorEmitter.dispose();
1889
+ this.closeEmitter.dispose();
1890
+ }
1891
+ get onError() {
1892
+ return this.errorEmitter.event;
1893
+ }
1894
+ fireError(error) {
1895
+ this.errorEmitter.fire(this.asError(error));
1896
+ }
1897
+ get onClose() {
1898
+ return this.closeEmitter.event;
1899
+ }
1900
+ fireClose() {
1901
+ this.closeEmitter.fire(void 0);
1902
+ }
1903
+ get onPartialMessage() {
1904
+ return this.partialMessageEmitter.event;
1905
+ }
1906
+ firePartialMessage(info) {
1907
+ this.partialMessageEmitter.fire(info);
1908
+ }
1909
+ asError(error) {
1910
+ if (error instanceof Error) {
1911
+ return error;
1912
+ } else {
1913
+ return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
1914
+ }
1915
+ }
1916
+ };
1917
+ exports.AbstractMessageReader = AbstractMessageReader;
1918
+ var ResolvedMessageReaderOptions;
1919
+ (function(ResolvedMessageReaderOptions2) {
1920
+ function fromOptions(options) {
1921
+ let charset;
1922
+ let result;
1923
+ let contentDecoder;
1924
+ const contentDecoders = /* @__PURE__ */ new Map();
1925
+ let contentTypeDecoder;
1926
+ const contentTypeDecoders = /* @__PURE__ */ new Map();
1927
+ if (options === void 0 || typeof options === "string") {
1928
+ charset = options ?? "utf-8";
1929
+ } else {
1930
+ charset = options.charset ?? "utf-8";
1931
+ if (options.contentDecoder !== void 0) {
1932
+ contentDecoder = options.contentDecoder;
1933
+ contentDecoders.set(contentDecoder.name, contentDecoder);
1934
+ }
1935
+ if (options.contentDecoders !== void 0) {
1936
+ for (const decoder of options.contentDecoders) {
1937
+ contentDecoders.set(decoder.name, decoder);
1938
+ }
1939
+ }
1940
+ if (options.contentTypeDecoder !== void 0) {
1941
+ contentTypeDecoder = options.contentTypeDecoder;
1942
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
1943
+ }
1944
+ if (options.contentTypeDecoders !== void 0) {
1945
+ for (const decoder of options.contentTypeDecoders) {
1946
+ contentTypeDecoders.set(decoder.name, decoder);
1947
+ }
1948
+ }
1949
+ }
1950
+ if (contentTypeDecoder === void 0) {
1951
+ contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
1952
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
1953
+ }
1954
+ return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
1955
+ }
1956
+ ResolvedMessageReaderOptions2.fromOptions = fromOptions;
1957
+ })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
1958
+ var ReadableStreamMessageReader = class extends AbstractMessageReader {
1959
+ constructor(readable, options) {
1960
+ super();
1961
+ this.readable = readable;
1962
+ this.options = ResolvedMessageReaderOptions.fromOptions(options);
1963
+ this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
1964
+ this._partialMessageTimeout = 1e4;
1965
+ this.nextMessageLength = -1;
1966
+ this.messageToken = 0;
1967
+ this.readSemaphore = new semaphore_1.Semaphore(1);
1968
+ }
1969
+ set partialMessageTimeout(timeout) {
1970
+ this._partialMessageTimeout = timeout;
1971
+ }
1972
+ get partialMessageTimeout() {
1973
+ return this._partialMessageTimeout;
1974
+ }
1975
+ listen(callback) {
1976
+ this.nextMessageLength = -1;
1977
+ this.messageToken = 0;
1978
+ this.partialMessageTimer = void 0;
1979
+ this.callback = callback;
1980
+ const result = this.readable.onData((data) => {
1981
+ this.onData(data);
1982
+ });
1983
+ this.readable.onError((error) => this.fireError(error));
1984
+ this.readable.onClose(() => this.fireClose());
1985
+ return result;
1986
+ }
1987
+ onData(data) {
1988
+ try {
1989
+ this.buffer.append(data);
1990
+ while (true) {
1991
+ if (this.nextMessageLength === -1) {
1992
+ const headers = this.buffer.tryReadHeaders(true);
1993
+ if (!headers) {
1994
+ return;
1995
+ }
1996
+ const contentLength = headers.get("content-length");
1997
+ if (!contentLength) {
1998
+ this.fireError(new Error(`Header must provide a Content-Length property.
1999
+ ${JSON.stringify(Object.fromEntries(headers))}`));
2000
+ return;
2001
+ }
2002
+ const length = parseInt(contentLength);
2003
+ if (isNaN(length)) {
2004
+ this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));
2005
+ return;
2006
+ }
2007
+ this.nextMessageLength = length;
2008
+ }
2009
+ const body = this.buffer.tryReadBody(this.nextMessageLength);
2010
+ if (body === void 0) {
2011
+ this.setPartialMessageTimer();
2012
+ return;
2013
+ }
2014
+ this.clearPartialMessageTimer();
2015
+ this.nextMessageLength = -1;
2016
+ this.readSemaphore.lock(async () => {
2017
+ const bytes = this.options.contentDecoder !== void 0 ? await this.options.contentDecoder.decode(body) : body;
2018
+ const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
2019
+ this.callback(message);
2020
+ }).catch((error) => {
2021
+ this.fireError(error);
2022
+ });
2023
+ }
2024
+ } catch (error) {
2025
+ this.fireError(error);
2026
+ }
2027
+ }
2028
+ clearPartialMessageTimer() {
2029
+ if (this.partialMessageTimer) {
2030
+ this.partialMessageTimer.dispose();
2031
+ this.partialMessageTimer = void 0;
2032
+ }
2033
+ }
2034
+ setPartialMessageTimer() {
2035
+ this.clearPartialMessageTimer();
2036
+ if (this._partialMessageTimeout <= 0) {
2037
+ return;
2038
+ }
2039
+ this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
2040
+ this.partialMessageTimer = void 0;
2041
+ if (token === this.messageToken) {
2042
+ this.firePartialMessage({ messageToken: token, waitingTime: timeout });
2043
+ this.setPartialMessageTimer();
2044
+ }
2045
+ }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
2046
+ }
2047
+ };
2048
+ exports.ReadableStreamMessageReader = ReadableStreamMessageReader;
2049
+ }
2050
+ });
2051
+
2052
+ // node_modules/vscode-jsonrpc/lib/common/messageWriter.js
2053
+ var require_messageWriter = __commonJS({
2054
+ "node_modules/vscode-jsonrpc/lib/common/messageWriter.js"(exports) {
2055
+ "use strict";
2056
+ Object.defineProperty(exports, "__esModule", { value: true });
2057
+ exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0;
2058
+ var ral_1 = require_ral();
2059
+ var Is = require_is();
2060
+ var semaphore_1 = require_semaphore();
2061
+ var events_1 = require_events();
2062
+ var ContentLength = "Content-Length: ";
2063
+ var CRLF = "\r\n";
2064
+ var MessageWriter;
2065
+ (function(MessageWriter2) {
2066
+ function is(value) {
2067
+ let candidate = value;
2068
+ return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write);
2069
+ }
2070
+ MessageWriter2.is = is;
2071
+ })(MessageWriter || (exports.MessageWriter = MessageWriter = {}));
2072
+ var AbstractMessageWriter = class {
2073
+ constructor() {
2074
+ this.errorEmitter = new events_1.Emitter();
2075
+ this.closeEmitter = new events_1.Emitter();
2076
+ }
2077
+ dispose() {
2078
+ this.errorEmitter.dispose();
2079
+ this.closeEmitter.dispose();
2080
+ }
2081
+ get onError() {
2082
+ return this.errorEmitter.event;
2083
+ }
2084
+ fireError(error, message, count) {
2085
+ this.errorEmitter.fire([this.asError(error), message, count]);
2086
+ }
2087
+ get onClose() {
2088
+ return this.closeEmitter.event;
2089
+ }
2090
+ fireClose() {
2091
+ this.closeEmitter.fire(void 0);
2092
+ }
2093
+ asError(error) {
2094
+ if (error instanceof Error) {
2095
+ return error;
2096
+ } else {
2097
+ return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
2098
+ }
2099
+ }
2100
+ };
2101
+ exports.AbstractMessageWriter = AbstractMessageWriter;
2102
+ var ResolvedMessageWriterOptions;
2103
+ (function(ResolvedMessageWriterOptions2) {
2104
+ function fromOptions(options) {
2105
+ if (options === void 0 || typeof options === "string") {
2106
+ return { charset: options ?? "utf-8", contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
2107
+ } else {
2108
+ return { charset: options.charset ?? "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
2109
+ }
2110
+ }
2111
+ ResolvedMessageWriterOptions2.fromOptions = fromOptions;
2112
+ })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
2113
+ var WriteableStreamMessageWriter = class extends AbstractMessageWriter {
2114
+ constructor(writable, options) {
2115
+ super();
2116
+ this.writable = writable;
2117
+ this.options = ResolvedMessageWriterOptions.fromOptions(options);
2118
+ this.errorCount = 0;
2119
+ this.writeSemaphore = new semaphore_1.Semaphore(1);
2120
+ this.writable.onError((error) => this.fireError(error));
2121
+ this.writable.onClose(() => this.fireClose());
2122
+ }
2123
+ async write(msg) {
2124
+ return this.writeSemaphore.lock(async () => {
2125
+ const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
2126
+ if (this.options.contentEncoder !== void 0) {
2127
+ return this.options.contentEncoder.encode(buffer);
2128
+ } else {
2129
+ return buffer;
2130
+ }
2131
+ });
2132
+ return payload.then((buffer) => {
2133
+ const headers = [];
2134
+ headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
2135
+ headers.push(CRLF);
2136
+ return this.doWrite(msg, headers, buffer);
2137
+ }, (error) => {
2138
+ this.fireError(error);
2139
+ throw error;
2140
+ });
2141
+ });
2142
+ }
2143
+ async doWrite(msg, headers, data) {
2144
+ try {
2145
+ await this.writable.write(headers.join(""), "ascii");
2146
+ return this.writable.write(data);
2147
+ } catch (error) {
2148
+ this.handleError(error, msg);
2149
+ return Promise.reject(error);
2150
+ }
2151
+ }
2152
+ handleError(error, msg) {
2153
+ this.errorCount++;
2154
+ this.fireError(error, msg, this.errorCount);
2155
+ }
2156
+ end() {
2157
+ this.writable.end();
2158
+ }
2159
+ };
2160
+ exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
2161
+ }
2162
+ });
2163
+
2164
+ // node_modules/vscode-jsonrpc/lib/common/messageBuffer.js
2165
+ var require_messageBuffer = __commonJS({
2166
+ "node_modules/vscode-jsonrpc/lib/common/messageBuffer.js"(exports) {
2167
+ "use strict";
2168
+ Object.defineProperty(exports, "__esModule", { value: true });
2169
+ exports.AbstractMessageBuffer = void 0;
2170
+ var CR = 13;
2171
+ var LF = 10;
2172
+ var CRLF = "\r\n";
2173
+ var AbstractMessageBuffer = class {
2174
+ constructor(encoding = "utf-8") {
2175
+ this._encoding = encoding;
2176
+ this._chunks = [];
2177
+ this._totalLength = 0;
2178
+ }
2179
+ get encoding() {
2180
+ return this._encoding;
2181
+ }
2182
+ append(chunk) {
2183
+ const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
2184
+ this._chunks.push(toAppend);
2185
+ this._totalLength += toAppend.byteLength;
2186
+ }
2187
+ tryReadHeaders(lowerCaseKeys = false) {
2188
+ if (this._chunks.length === 0) {
2189
+ return void 0;
2190
+ }
2191
+ let state = 0;
2192
+ let chunkIndex = 0;
2193
+ let offset = 0;
2194
+ let chunkBytesRead = 0;
2195
+ row: while (chunkIndex < this._chunks.length) {
2196
+ const chunk = this._chunks[chunkIndex];
2197
+ offset = 0;
2198
+ column: while (offset < chunk.length) {
2199
+ const value = chunk[offset];
2200
+ switch (value) {
2201
+ case CR:
2202
+ switch (state) {
2203
+ case 0:
2204
+ state = 1;
2205
+ break;
2206
+ case 2:
2207
+ state = 3;
2208
+ break;
2209
+ default:
2210
+ state = 0;
2211
+ }
2212
+ break;
2213
+ case LF:
2214
+ switch (state) {
2215
+ case 1:
2216
+ state = 2;
2217
+ break;
2218
+ case 3:
2219
+ state = 4;
2220
+ offset++;
2221
+ break row;
2222
+ default:
2223
+ state = 0;
2224
+ }
2225
+ break;
2226
+ default:
2227
+ state = 0;
2228
+ }
2229
+ offset++;
2230
+ }
2231
+ chunkBytesRead += chunk.byteLength;
2232
+ chunkIndex++;
2233
+ }
2234
+ if (state !== 4) {
2235
+ return void 0;
2236
+ }
2237
+ const buffer = this._read(chunkBytesRead + offset);
2238
+ const result = /* @__PURE__ */ new Map();
2239
+ const headers = this.toString(buffer, "ascii").split(CRLF);
2240
+ if (headers.length < 2) {
2241
+ return result;
2242
+ }
2243
+ for (let i = 0; i < headers.length - 2; i++) {
2244
+ const header = headers[i];
2245
+ const index = header.indexOf(":");
2246
+ if (index === -1) {
2247
+ throw new Error(`Message header must separate key and value using ':'
2248
+ ${header}`);
2249
+ }
2250
+ const key = header.substr(0, index);
2251
+ const value = header.substr(index + 1).trim();
2252
+ result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
2253
+ }
2254
+ return result;
2255
+ }
2256
+ tryReadBody(length) {
2257
+ if (this._totalLength < length) {
2258
+ return void 0;
2259
+ }
2260
+ return this._read(length);
2261
+ }
2262
+ get numberOfBytes() {
2263
+ return this._totalLength;
2264
+ }
2265
+ _read(byteCount) {
2266
+ if (byteCount === 0) {
2267
+ return this.emptyBuffer();
2268
+ }
2269
+ if (byteCount > this._totalLength) {
2270
+ throw new Error(`Cannot read so many bytes!`);
2271
+ }
2272
+ if (this._chunks[0].byteLength === byteCount) {
2273
+ const chunk = this._chunks[0];
2274
+ this._chunks.shift();
2275
+ this._totalLength -= byteCount;
2276
+ return this.asNative(chunk);
2277
+ }
2278
+ if (this._chunks[0].byteLength > byteCount) {
2279
+ const chunk = this._chunks[0];
2280
+ const result2 = this.asNative(chunk, byteCount);
2281
+ this._chunks[0] = chunk.slice(byteCount);
2282
+ this._totalLength -= byteCount;
2283
+ return result2;
2284
+ }
2285
+ const result = this.allocNative(byteCount);
2286
+ let resultOffset = 0;
2287
+ let chunkIndex = 0;
2288
+ while (byteCount > 0) {
2289
+ const chunk = this._chunks[chunkIndex];
2290
+ if (chunk.byteLength > byteCount) {
2291
+ const chunkPart = chunk.slice(0, byteCount);
2292
+ result.set(chunkPart, resultOffset);
2293
+ resultOffset += byteCount;
2294
+ this._chunks[chunkIndex] = chunk.slice(byteCount);
2295
+ this._totalLength -= byteCount;
2296
+ byteCount -= byteCount;
2297
+ } else {
2298
+ result.set(chunk, resultOffset);
2299
+ resultOffset += chunk.byteLength;
2300
+ this._chunks.shift();
2301
+ this._totalLength -= chunk.byteLength;
2302
+ byteCount -= chunk.byteLength;
2303
+ }
2304
+ }
2305
+ return result;
2306
+ }
2307
+ };
2308
+ exports.AbstractMessageBuffer = AbstractMessageBuffer;
2309
+ }
2310
+ });
2311
+
2312
+ // node_modules/vscode-jsonrpc/lib/common/connection.js
2313
+ var require_connection = __commonJS({
2314
+ "node_modules/vscode-jsonrpc/lib/common/connection.js"(exports) {
2315
+ "use strict";
2316
+ Object.defineProperty(exports, "__esModule", { value: true });
2317
+ exports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;
2318
+ var ral_1 = require_ral();
2319
+ var Is = require_is();
2320
+ var messages_1 = require_messages();
2321
+ var linkedMap_1 = require_linkedMap();
2322
+ var events_1 = require_events();
2323
+ var cancellation_1 = require_cancellation();
2324
+ var CancelNotification;
2325
+ (function(CancelNotification2) {
2326
+ CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
2327
+ })(CancelNotification || (CancelNotification = {}));
2328
+ var ProgressToken;
2329
+ (function(ProgressToken2) {
2330
+ function is(value) {
2331
+ return typeof value === "string" || typeof value === "number";
2332
+ }
2333
+ ProgressToken2.is = is;
2334
+ })(ProgressToken || (exports.ProgressToken = ProgressToken = {}));
2335
+ var ProgressNotification;
2336
+ (function(ProgressNotification2) {
2337
+ ProgressNotification2.type = new messages_1.NotificationType("$/progress");
2338
+ })(ProgressNotification || (ProgressNotification = {}));
2339
+ var ProgressType = class {
2340
+ constructor() {
2341
+ }
2342
+ };
2343
+ exports.ProgressType = ProgressType;
2344
+ var StarRequestHandler;
2345
+ (function(StarRequestHandler2) {
2346
+ function is(value) {
2347
+ return Is.func(value);
2348
+ }
2349
+ StarRequestHandler2.is = is;
2350
+ })(StarRequestHandler || (StarRequestHandler = {}));
2351
+ exports.NullLogger = Object.freeze({
2352
+ error: () => {
2353
+ },
2354
+ warn: () => {
2355
+ },
2356
+ info: () => {
2357
+ },
2358
+ log: () => {
2359
+ }
2360
+ });
2361
+ var Trace;
2362
+ (function(Trace2) {
2363
+ Trace2[Trace2["Off"] = 0] = "Off";
2364
+ Trace2[Trace2["Messages"] = 1] = "Messages";
2365
+ Trace2[Trace2["Compact"] = 2] = "Compact";
2366
+ Trace2[Trace2["Verbose"] = 3] = "Verbose";
2367
+ })(Trace || (exports.Trace = Trace = {}));
2368
+ var TraceValues;
2369
+ (function(TraceValues2) {
2370
+ TraceValues2.Off = "off";
2371
+ TraceValues2.Messages = "messages";
2372
+ TraceValues2.Compact = "compact";
2373
+ TraceValues2.Verbose = "verbose";
2374
+ })(TraceValues || (exports.TraceValues = TraceValues = {}));
2375
+ (function(Trace2) {
2376
+ function fromString(value) {
2377
+ if (!Is.string(value)) {
2378
+ return Trace2.Off;
2379
+ }
2380
+ value = value.toLowerCase();
2381
+ switch (value) {
2382
+ case "off":
2383
+ return Trace2.Off;
2384
+ case "messages":
2385
+ return Trace2.Messages;
2386
+ case "compact":
2387
+ return Trace2.Compact;
2388
+ case "verbose":
2389
+ return Trace2.Verbose;
2390
+ default:
2391
+ return Trace2.Off;
2392
+ }
2393
+ }
2394
+ Trace2.fromString = fromString;
2395
+ function toString(value) {
2396
+ switch (value) {
2397
+ case Trace2.Off:
2398
+ return "off";
2399
+ case Trace2.Messages:
2400
+ return "messages";
2401
+ case Trace2.Compact:
2402
+ return "compact";
2403
+ case Trace2.Verbose:
2404
+ return "verbose";
2405
+ default:
2406
+ return "off";
2407
+ }
2408
+ }
2409
+ Trace2.toString = toString;
2410
+ })(Trace || (exports.Trace = Trace = {}));
2411
+ var TraceFormat;
2412
+ (function(TraceFormat2) {
2413
+ TraceFormat2["Text"] = "text";
2414
+ TraceFormat2["JSON"] = "json";
2415
+ })(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
2416
+ (function(TraceFormat2) {
2417
+ function fromString(value) {
2418
+ if (!Is.string(value)) {
2419
+ return TraceFormat2.Text;
2420
+ }
2421
+ value = value.toLowerCase();
2422
+ if (value === "json") {
2423
+ return TraceFormat2.JSON;
2424
+ } else {
2425
+ return TraceFormat2.Text;
2426
+ }
2427
+ }
2428
+ TraceFormat2.fromString = fromString;
2429
+ })(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
2430
+ var SetTraceNotification;
2431
+ (function(SetTraceNotification2) {
2432
+ SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace");
2433
+ })(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));
2434
+ var LogTraceNotification;
2435
+ (function(LogTraceNotification2) {
2436
+ LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace");
2437
+ })(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));
2438
+ var ConnectionErrors;
2439
+ (function(ConnectionErrors2) {
2440
+ ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
2441
+ ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
2442
+ ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
2443
+ })(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));
2444
+ var ConnectionError = class _ConnectionError extends Error {
2445
+ constructor(code, message) {
2446
+ super(message);
2447
+ this.code = code;
2448
+ Object.setPrototypeOf(this, _ConnectionError.prototype);
2449
+ }
2450
+ };
2451
+ exports.ConnectionError = ConnectionError;
2452
+ var ConnectionStrategy;
2453
+ (function(ConnectionStrategy2) {
2454
+ function is(value) {
2455
+ const candidate = value;
2456
+ return candidate && Is.func(candidate.cancelUndispatched);
2457
+ }
2458
+ ConnectionStrategy2.is = is;
2459
+ })(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));
2460
+ var IdCancellationReceiverStrategy;
2461
+ (function(IdCancellationReceiverStrategy2) {
2462
+ function is(value) {
2463
+ const candidate = value;
2464
+ return candidate && (candidate.kind === void 0 || candidate.kind === "id") && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose));
2465
+ }
2466
+ IdCancellationReceiverStrategy2.is = is;
2467
+ })(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
2468
+ var RequestCancellationReceiverStrategy;
2469
+ (function(RequestCancellationReceiverStrategy2) {
2470
+ function is(value) {
2471
+ const candidate = value;
2472
+ return candidate && candidate.kind === "request" && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose));
2473
+ }
2474
+ RequestCancellationReceiverStrategy2.is = is;
2475
+ })(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
2476
+ var CancellationReceiverStrategy;
2477
+ (function(CancellationReceiverStrategy2) {
2478
+ CancellationReceiverStrategy2.Message = Object.freeze({
2479
+ createCancellationTokenSource(_) {
2480
+ return new cancellation_1.CancellationTokenSource();
2481
+ }
2482
+ });
2483
+ function is(value) {
2484
+ return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
2485
+ }
2486
+ CancellationReceiverStrategy2.is = is;
2487
+ })(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
2488
+ var CancellationSenderStrategy;
2489
+ (function(CancellationSenderStrategy2) {
2490
+ CancellationSenderStrategy2.Message = Object.freeze({
2491
+ sendCancellation(conn, id) {
2492
+ return conn.sendNotification(CancelNotification.type, { id });
2493
+ },
2494
+ cleanup(_) {
2495
+ }
2496
+ });
2497
+ function is(value) {
2498
+ const candidate = value;
2499
+ return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
2500
+ }
2501
+ CancellationSenderStrategy2.is = is;
2502
+ })(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));
2503
+ var CancellationStrategy;
2504
+ (function(CancellationStrategy2) {
2505
+ CancellationStrategy2.Message = Object.freeze({
2506
+ receiver: CancellationReceiverStrategy.Message,
2507
+ sender: CancellationSenderStrategy.Message
2508
+ });
2509
+ function is(value) {
2510
+ const candidate = value;
2511
+ return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
2512
+ }
2513
+ CancellationStrategy2.is = is;
2514
+ })(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));
2515
+ var MessageStrategy;
2516
+ (function(MessageStrategy2) {
2517
+ function is(value) {
2518
+ const candidate = value;
2519
+ return candidate && Is.func(candidate.handleMessage);
2520
+ }
2521
+ MessageStrategy2.is = is;
2522
+ })(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));
2523
+ var ConnectionOptions;
2524
+ (function(ConnectionOptions2) {
2525
+ function is(value) {
2526
+ const candidate = value;
2527
+ return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));
2528
+ }
2529
+ ConnectionOptions2.is = is;
2530
+ })(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));
2531
+ var ConnectionState;
2532
+ (function(ConnectionState2) {
2533
+ ConnectionState2[ConnectionState2["New"] = 1] = "New";
2534
+ ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
2535
+ ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
2536
+ ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
2537
+ })(ConnectionState || (ConnectionState = {}));
2538
+ function createMessageConnection2(messageReader, messageWriter, _logger, options) {
2539
+ const logger2 = _logger !== void 0 ? _logger : exports.NullLogger;
2540
+ let sequenceNumber = 0;
2541
+ let notificationSequenceNumber = 0;
2542
+ let unknownResponseSequenceNumber = 0;
2543
+ const version = "2.0";
2544
+ let starRequestHandler = void 0;
2545
+ const requestHandlers = /* @__PURE__ */ new Map();
2546
+ let starNotificationHandler = void 0;
2547
+ const notificationHandlers = /* @__PURE__ */ new Map();
2548
+ const progressHandlers = /* @__PURE__ */ new Map();
2549
+ let timer;
2550
+ let messageQueue = new linkedMap_1.LinkedMap();
2551
+ let responsePromises = /* @__PURE__ */ new Map();
2552
+ let knownCanceledRequests = /* @__PURE__ */ new Set();
2553
+ let requestTokens = /* @__PURE__ */ new Map();
2554
+ let trace = Trace.Off;
2555
+ let traceFormat = TraceFormat.Text;
2556
+ let tracer;
2557
+ let state = ConnectionState.New;
2558
+ const errorEmitter = new events_1.Emitter();
2559
+ const closeEmitter = new events_1.Emitter();
2560
+ const unhandledNotificationEmitter = new events_1.Emitter();
2561
+ const unhandledProgressEmitter = new events_1.Emitter();
2562
+ const disposeEmitter = new events_1.Emitter();
2563
+ const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
2564
+ function createRequestQueueKey(id) {
2565
+ if (id === null) {
2566
+ throw new Error(`Can't send requests with id null since the response can't be correlated.`);
2567
+ }
2568
+ return "req-" + id.toString();
2569
+ }
2570
+ function createResponseQueueKey(id) {
2571
+ if (id === null) {
2572
+ return "res-unknown-" + (++unknownResponseSequenceNumber).toString();
2573
+ } else {
2574
+ return "res-" + id.toString();
2575
+ }
2576
+ }
2577
+ function createNotificationQueueKey() {
2578
+ return "not-" + (++notificationSequenceNumber).toString();
2579
+ }
2580
+ function addMessageToQueue(queue2, message) {
2581
+ if (messages_1.Message.isRequest(message)) {
2582
+ queue2.set(createRequestQueueKey(message.id), message);
2583
+ } else if (messages_1.Message.isResponse(message)) {
2584
+ queue2.set(createResponseQueueKey(message.id), message);
2585
+ } else {
2586
+ queue2.set(createNotificationQueueKey(), message);
2587
+ }
2588
+ }
2589
+ function cancelUndispatched(_message) {
2590
+ return void 0;
2591
+ }
2592
+ function isListening() {
2593
+ return state === ConnectionState.Listening;
2594
+ }
2595
+ function isClosed() {
2596
+ return state === ConnectionState.Closed;
2597
+ }
2598
+ function isDisposed() {
2599
+ return state === ConnectionState.Disposed;
2600
+ }
2601
+ function closeHandler() {
2602
+ if (state === ConnectionState.New || state === ConnectionState.Listening) {
2603
+ state = ConnectionState.Closed;
2604
+ closeEmitter.fire(void 0);
2605
+ }
2606
+ }
2607
+ function readErrorHandler(error) {
2608
+ errorEmitter.fire([error, void 0, void 0]);
2609
+ }
2610
+ function writeErrorHandler(data) {
2611
+ errorEmitter.fire(data);
2612
+ }
2613
+ messageReader.onClose(closeHandler);
2614
+ messageReader.onError(readErrorHandler);
2615
+ messageWriter.onClose(closeHandler);
2616
+ messageWriter.onError(writeErrorHandler);
2617
+ function triggerMessageQueue() {
2618
+ if (timer || messageQueue.size === 0) {
2619
+ return;
2620
+ }
2621
+ timer = (0, ral_1.default)().timer.setImmediate(() => {
2622
+ timer = void 0;
2623
+ processMessageQueue();
2624
+ });
2625
+ }
2626
+ function handleMessage(message) {
2627
+ if (messages_1.Message.isRequest(message)) {
2628
+ handleRequest(message);
2629
+ } else if (messages_1.Message.isNotification(message)) {
2630
+ handleNotification(message);
2631
+ } else if (messages_1.Message.isResponse(message)) {
2632
+ handleResponse(message);
2633
+ } else {
2634
+ handleInvalidMessage(message);
2635
+ }
2636
+ }
2637
+ function processMessageQueue() {
2638
+ if (messageQueue.size === 0) {
2639
+ return;
2640
+ }
2641
+ const message = messageQueue.shift();
2642
+ try {
2643
+ const messageStrategy = options?.messageStrategy;
2644
+ if (MessageStrategy.is(messageStrategy)) {
2645
+ messageStrategy.handleMessage(message, handleMessage);
2646
+ } else {
2647
+ handleMessage(message);
2648
+ }
2649
+ } finally {
2650
+ triggerMessageQueue();
2651
+ }
2652
+ }
2653
+ const callback = (message) => {
2654
+ try {
2655
+ if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
2656
+ const cancelId = message.params.id;
2657
+ const key = createRequestQueueKey(cancelId);
2658
+ const toCancel = messageQueue.get(key);
2659
+ if (messages_1.Message.isRequest(toCancel)) {
2660
+ const strategy = options?.connectionStrategy;
2661
+ const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
2662
+ if (response && (response.error !== void 0 || response.result !== void 0)) {
2663
+ messageQueue.delete(key);
2664
+ requestTokens.delete(cancelId);
2665
+ response.id = toCancel.id;
2666
+ traceSendingResponse(response, message.method, Date.now());
2667
+ messageWriter.write(response).catch(() => logger2.error(`Sending response for canceled message failed.`));
2668
+ return;
2669
+ }
2670
+ }
2671
+ const cancellationToken = requestTokens.get(cancelId);
2672
+ if (cancellationToken !== void 0) {
2673
+ cancellationToken.cancel();
2674
+ traceReceivedNotification(message);
2675
+ return;
2676
+ } else {
2677
+ knownCanceledRequests.add(cancelId);
2678
+ }
2679
+ }
2680
+ addMessageToQueue(messageQueue, message);
2681
+ } finally {
2682
+ triggerMessageQueue();
2683
+ }
2684
+ };
2685
+ function handleRequest(requestMessage) {
2686
+ if (isDisposed()) {
2687
+ return;
2688
+ }
2689
+ function reply(resultOrError, method, startTime2) {
2690
+ const message = {
2691
+ jsonrpc: version,
2692
+ id: requestMessage.id
2693
+ };
2694
+ if (resultOrError instanceof messages_1.ResponseError) {
2695
+ message.error = resultOrError.toJson();
2696
+ } else {
2697
+ message.result = resultOrError === void 0 ? null : resultOrError;
2698
+ }
2699
+ traceSendingResponse(message, method, startTime2);
2700
+ messageWriter.write(message).catch(() => logger2.error(`Sending response failed.`));
2701
+ }
2702
+ function replyError(error, method, startTime2) {
2703
+ const message = {
2704
+ jsonrpc: version,
2705
+ id: requestMessage.id,
2706
+ error: error.toJson()
2707
+ };
2708
+ traceSendingResponse(message, method, startTime2);
2709
+ messageWriter.write(message).catch(() => logger2.error(`Sending response failed.`));
2710
+ }
2711
+ function replySuccess(result, method, startTime2) {
2712
+ if (result === void 0) {
2713
+ result = null;
2714
+ }
2715
+ const message = {
2716
+ jsonrpc: version,
2717
+ id: requestMessage.id,
2718
+ result
2719
+ };
2720
+ traceSendingResponse(message, method, startTime2);
2721
+ messageWriter.write(message).catch(() => logger2.error(`Sending response failed.`));
2722
+ }
2723
+ traceReceivedRequest(requestMessage);
2724
+ const element = requestHandlers.get(requestMessage.method);
2725
+ let type;
2726
+ let requestHandler;
2727
+ if (element) {
2728
+ type = element.type;
2729
+ requestHandler = element.handler;
2730
+ }
2731
+ const startTime = Date.now();
2732
+ if (requestHandler || starRequestHandler) {
2733
+ const tokenKey = requestMessage.id ?? String(Date.now());
2734
+ const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
2735
+ if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
2736
+ cancellationSource.cancel();
2737
+ }
2738
+ if (requestMessage.id !== null) {
2739
+ requestTokens.set(tokenKey, cancellationSource);
2740
+ }
2741
+ try {
2742
+ let handlerResult;
2743
+ if (requestHandler) {
2744
+ if (requestMessage.params === void 0) {
2745
+ if (type !== void 0 && type.numberOfParams !== 0) {
2746
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
2747
+ return;
2748
+ }
2749
+ handlerResult = requestHandler(cancellationSource.token);
2750
+ } else if (Array.isArray(requestMessage.params)) {
2751
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) {
2752
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
2753
+ return;
2754
+ }
2755
+ handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
2756
+ } else {
2757
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
2758
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
2759
+ return;
2760
+ }
2761
+ handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
2762
+ }
2763
+ } else if (starRequestHandler) {
2764
+ handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
2765
+ }
2766
+ const promise = handlerResult;
2767
+ if (!handlerResult) {
2768
+ requestTokens.delete(tokenKey);
2769
+ replySuccess(handlerResult, requestMessage.method, startTime);
2770
+ } else if (promise.then) {
2771
+ promise.then((resultOrError) => {
2772
+ requestTokens.delete(tokenKey);
2773
+ reply(resultOrError, requestMessage.method, startTime);
2774
+ }, (error) => {
2775
+ requestTokens.delete(tokenKey);
2776
+ if (error instanceof messages_1.ResponseError) {
2777
+ replyError(error, requestMessage.method, startTime);
2778
+ } else if (error && Is.string(error.message)) {
2779
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
2780
+ } else {
2781
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
2782
+ }
2783
+ });
2784
+ } else {
2785
+ requestTokens.delete(tokenKey);
2786
+ reply(handlerResult, requestMessage.method, startTime);
2787
+ }
2788
+ } catch (error) {
2789
+ requestTokens.delete(tokenKey);
2790
+ if (error instanceof messages_1.ResponseError) {
2791
+ reply(error, requestMessage.method, startTime);
2792
+ } else if (error && Is.string(error.message)) {
2793
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
2794
+ } else {
2795
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
2796
+ }
2797
+ }
2798
+ } else {
2799
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
2800
+ }
2801
+ }
2802
+ function handleResponse(responseMessage) {
2803
+ if (isDisposed()) {
2804
+ return;
2805
+ }
2806
+ if (responseMessage.id === null) {
2807
+ if (responseMessage.error) {
2808
+ logger2.error(`Received response message without id: Error is:
2809
+ ${JSON.stringify(responseMessage.error, void 0, 4)}`);
2810
+ } else {
2811
+ logger2.error(`Received response message without id. No further error information provided.`);
2812
+ }
2813
+ } else {
2814
+ const key = responseMessage.id;
2815
+ const responsePromise = responsePromises.get(key);
2816
+ traceReceivedResponse(responseMessage, responsePromise);
2817
+ if (responsePromise !== void 0) {
2818
+ responsePromises.delete(key);
2819
+ try {
2820
+ if (responseMessage.error) {
2821
+ const error = responseMessage.error;
2822
+ responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
2823
+ } else if (responseMessage.result !== void 0) {
2824
+ responsePromise.resolve(responseMessage.result);
2825
+ } else {
2826
+ throw new Error("Should never happen.");
2827
+ }
2828
+ } catch (error) {
2829
+ if (error.message) {
2830
+ logger2.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
2831
+ } else {
2832
+ logger2.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
2833
+ }
2834
+ }
2835
+ }
2836
+ }
2837
+ }
2838
+ function handleNotification(message) {
2839
+ if (isDisposed()) {
2840
+ return;
2841
+ }
2842
+ let type = void 0;
2843
+ let notificationHandler;
2844
+ if (message.method === CancelNotification.type.method) {
2845
+ const cancelId = message.params.id;
2846
+ knownCanceledRequests.delete(cancelId);
2847
+ traceReceivedNotification(message);
2848
+ return;
2849
+ } else {
2850
+ const element = notificationHandlers.get(message.method);
2851
+ if (element) {
2852
+ notificationHandler = element.handler;
2853
+ type = element.type;
2854
+ }
2855
+ }
2856
+ if (notificationHandler || starNotificationHandler) {
2857
+ try {
2858
+ traceReceivedNotification(message);
2859
+ if (notificationHandler) {
2860
+ if (message.params === void 0) {
2861
+ if (type !== void 0) {
2862
+ if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
2863
+ logger2.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
2864
+ }
2865
+ }
2866
+ notificationHandler();
2867
+ } else if (Array.isArray(message.params)) {
2868
+ const params = message.params;
2869
+ if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
2870
+ notificationHandler({ token: params[0], value: params[1] });
2871
+ } else {
2872
+ if (type !== void 0) {
2873
+ if (type.parameterStructures === messages_1.ParameterStructures.byName) {
2874
+ logger2.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
2875
+ }
2876
+ if (type.numberOfParams !== message.params.length) {
2877
+ logger2.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
2878
+ }
2879
+ }
2880
+ notificationHandler(...params);
2881
+ }
2882
+ } else {
2883
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
2884
+ logger2.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
2885
+ }
2886
+ notificationHandler(message.params);
2887
+ }
2888
+ } else if (starNotificationHandler) {
2889
+ starNotificationHandler(message.method, message.params);
2890
+ }
2891
+ } catch (error) {
2892
+ if (error.message) {
2893
+ logger2.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
2894
+ } else {
2895
+ logger2.error(`Notification handler '${message.method}' failed unexpectedly.`);
2896
+ }
2897
+ }
2898
+ } else {
2899
+ unhandledNotificationEmitter.fire(message);
2900
+ }
2901
+ }
2902
+ function handleInvalidMessage(message) {
2903
+ if (!message) {
2904
+ logger2.error("Received empty message.");
2905
+ return;
2906
+ }
2907
+ logger2.error(`Received message which is neither a response nor a notification message:
2908
+ ${JSON.stringify(message, null, 4)}`);
2909
+ const responseMessage = message;
2910
+ if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
2911
+ const key = responseMessage.id;
2912
+ const responseHandler = responsePromises.get(key);
2913
+ if (responseHandler) {
2914
+ responseHandler.reject(new Error("The received response has neither a result nor an error property."));
2915
+ }
2916
+ }
2917
+ }
2918
+ function stringifyTrace(params) {
2919
+ if (params === void 0 || params === null) {
2920
+ return void 0;
2921
+ }
2922
+ switch (trace) {
2923
+ case Trace.Verbose:
2924
+ return JSON.stringify(params, null, 4);
2925
+ case Trace.Compact:
2926
+ return JSON.stringify(params);
2927
+ default:
2928
+ return void 0;
2929
+ }
2930
+ }
2931
+ function traceSendingRequest(message) {
2932
+ if (trace === Trace.Off || !tracer) {
2933
+ return;
2934
+ }
2935
+ if (traceFormat === TraceFormat.Text) {
2936
+ let data = void 0;
2937
+ if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
2938
+ data = `Params: ${stringifyTrace(message.params)}
2939
+
2940
+ `;
2941
+ }
2942
+ tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
2943
+ } else {
2944
+ logLSPMessage("send-request", message);
2945
+ }
2946
+ }
2947
+ function traceSendingNotification(message) {
2948
+ if (trace === Trace.Off || !tracer) {
2949
+ return;
2950
+ }
2951
+ if (traceFormat === TraceFormat.Text) {
2952
+ let data = void 0;
2953
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
2954
+ if (message.params) {
2955
+ data = `Params: ${stringifyTrace(message.params)}
2956
+
2957
+ `;
2958
+ } else {
2959
+ data = "No parameters provided.\n\n";
2960
+ }
2961
+ }
2962
+ tracer.log(`Sending notification '${message.method}'.`, data);
2963
+ } else {
2964
+ logLSPMessage("send-notification", message);
2965
+ }
2966
+ }
2967
+ function traceSendingResponse(message, method, startTime) {
2968
+ if (trace === Trace.Off || !tracer) {
2969
+ return;
2970
+ }
2971
+ if (traceFormat === TraceFormat.Text) {
2972
+ let data = void 0;
2973
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
2974
+ if (message.error && message.error.data) {
2975
+ data = `Error data: ${stringifyTrace(message.error.data)}
2976
+
2977
+ `;
2978
+ } else {
2979
+ if (message.result) {
2980
+ data = `Result: ${stringifyTrace(message.result)}
2981
+
2982
+ `;
2983
+ } else if (message.error === void 0) {
2984
+ data = "No result returned.\n\n";
2985
+ }
2986
+ }
2987
+ }
2988
+ tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
2989
+ } else {
2990
+ logLSPMessage("send-response", message);
2991
+ }
2992
+ }
2993
+ function traceReceivedRequest(message) {
2994
+ if (trace === Trace.Off || !tracer) {
2995
+ return;
2996
+ }
2997
+ if (traceFormat === TraceFormat.Text) {
2998
+ let data = void 0;
2999
+ if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
3000
+ data = `Params: ${stringifyTrace(message.params)}
3001
+
3002
+ `;
3003
+ }
3004
+ tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
3005
+ } else {
3006
+ logLSPMessage("receive-request", message);
3007
+ }
3008
+ }
3009
+ function traceReceivedNotification(message) {
3010
+ if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
3011
+ return;
3012
+ }
3013
+ if (traceFormat === TraceFormat.Text) {
3014
+ let data = void 0;
3015
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
3016
+ if (message.params) {
3017
+ data = `Params: ${stringifyTrace(message.params)}
3018
+
3019
+ `;
3020
+ } else {
3021
+ data = "No parameters provided.\n\n";
3022
+ }
3023
+ }
3024
+ tracer.log(`Received notification '${message.method}'.`, data);
3025
+ } else {
3026
+ logLSPMessage("receive-notification", message);
3027
+ }
3028
+ }
3029
+ function traceReceivedResponse(message, responsePromise) {
3030
+ if (trace === Trace.Off || !tracer) {
3031
+ return;
3032
+ }
3033
+ if (traceFormat === TraceFormat.Text) {
3034
+ let data = void 0;
3035
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
3036
+ if (message.error && message.error.data) {
3037
+ data = `Error data: ${stringifyTrace(message.error.data)}
3038
+
3039
+ `;
3040
+ } else {
3041
+ if (message.result) {
3042
+ data = `Result: ${stringifyTrace(message.result)}
3043
+
3044
+ `;
3045
+ } else if (message.error === void 0) {
3046
+ data = "No result returned.\n\n";
3047
+ }
3048
+ }
3049
+ }
3050
+ if (responsePromise) {
3051
+ const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
3052
+ tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
3053
+ } else {
3054
+ tracer.log(`Received response ${message.id} without active response promise.`, data);
3055
+ }
3056
+ } else {
3057
+ logLSPMessage("receive-response", message);
3058
+ }
3059
+ }
3060
+ function logLSPMessage(type, message) {
3061
+ if (!tracer || trace === Trace.Off) {
3062
+ return;
3063
+ }
3064
+ const lspMessage = {
3065
+ isLSPMessage: true,
3066
+ type,
3067
+ message,
3068
+ timestamp: Date.now()
3069
+ };
3070
+ tracer.log(lspMessage);
3071
+ }
3072
+ function throwIfClosedOrDisposed() {
3073
+ if (isClosed()) {
3074
+ throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
3075
+ }
3076
+ if (isDisposed()) {
3077
+ throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
3078
+ }
3079
+ }
3080
+ function throwIfListening() {
3081
+ if (isListening()) {
3082
+ throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
3083
+ }
3084
+ }
3085
+ function throwIfNotListening() {
3086
+ if (!isListening()) {
3087
+ throw new Error("Call listen() first.");
3088
+ }
3089
+ }
3090
+ function undefinedToNull(param) {
3091
+ if (param === void 0) {
3092
+ return null;
3093
+ } else {
3094
+ return param;
3095
+ }
3096
+ }
3097
+ function nullToUndefined(param) {
3098
+ if (param === null) {
3099
+ return void 0;
3100
+ } else {
3101
+ return param;
3102
+ }
3103
+ }
3104
+ function isNamedParam(param) {
3105
+ return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object";
3106
+ }
3107
+ function computeSingleParam(parameterStructures, param) {
3108
+ switch (parameterStructures) {
3109
+ case messages_1.ParameterStructures.auto:
3110
+ if (isNamedParam(param)) {
3111
+ return nullToUndefined(param);
3112
+ } else {
3113
+ return [undefinedToNull(param)];
3114
+ }
3115
+ case messages_1.ParameterStructures.byName:
3116
+ if (!isNamedParam(param)) {
3117
+ throw new Error(`Received parameters by name but param is not an object literal.`);
3118
+ }
3119
+ return nullToUndefined(param);
3120
+ case messages_1.ParameterStructures.byPosition:
3121
+ return [undefinedToNull(param)];
3122
+ default:
3123
+ throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
3124
+ }
3125
+ }
3126
+ function computeMessageParams(type, params) {
3127
+ let result;
3128
+ const numberOfParams = type.numberOfParams;
3129
+ switch (numberOfParams) {
3130
+ case 0:
3131
+ result = void 0;
3132
+ break;
3133
+ case 1:
3134
+ result = computeSingleParam(type.parameterStructures, params[0]);
3135
+ break;
3136
+ default:
3137
+ result = [];
3138
+ for (let i = 0; i < params.length && i < numberOfParams; i++) {
3139
+ result.push(undefinedToNull(params[i]));
3140
+ }
3141
+ if (params.length < numberOfParams) {
3142
+ for (let i = params.length; i < numberOfParams; i++) {
3143
+ result.push(null);
3144
+ }
3145
+ }
3146
+ break;
3147
+ }
3148
+ return result;
3149
+ }
3150
+ const connection = {
3151
+ sendNotification: (type, ...args) => {
3152
+ throwIfClosedOrDisposed();
3153
+ let method;
3154
+ let messageParams;
3155
+ if (Is.string(type)) {
3156
+ method = type;
3157
+ const first = args[0];
3158
+ let paramStart = 0;
3159
+ let parameterStructures = messages_1.ParameterStructures.auto;
3160
+ if (messages_1.ParameterStructures.is(first)) {
3161
+ paramStart = 1;
3162
+ parameterStructures = first;
3163
+ }
3164
+ let paramEnd = args.length;
3165
+ const numberOfParams = paramEnd - paramStart;
3166
+ switch (numberOfParams) {
3167
+ case 0:
3168
+ messageParams = void 0;
3169
+ break;
3170
+ case 1:
3171
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
3172
+ break;
3173
+ default:
3174
+ if (parameterStructures === messages_1.ParameterStructures.byName) {
3175
+ throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
3176
+ }
3177
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
3178
+ break;
3179
+ }
3180
+ } else {
3181
+ const params = args;
3182
+ method = type.method;
3183
+ messageParams = computeMessageParams(type, params);
3184
+ }
3185
+ const notificationMessage = {
3186
+ jsonrpc: version,
3187
+ method,
3188
+ params: messageParams
3189
+ };
3190
+ traceSendingNotification(notificationMessage);
3191
+ return messageWriter.write(notificationMessage).catch((error) => {
3192
+ logger2.error(`Sending notification failed.`);
3193
+ throw error;
3194
+ });
3195
+ },
3196
+ onNotification: (type, handler) => {
3197
+ throwIfClosedOrDisposed();
3198
+ let method;
3199
+ if (Is.func(type)) {
3200
+ starNotificationHandler = type;
3201
+ } else if (handler) {
3202
+ if (Is.string(type)) {
3203
+ method = type;
3204
+ notificationHandlers.set(type, { type: void 0, handler });
3205
+ } else {
3206
+ method = type.method;
3207
+ notificationHandlers.set(type.method, { type, handler });
3208
+ }
3209
+ }
3210
+ return {
3211
+ dispose: () => {
3212
+ if (method !== void 0) {
3213
+ notificationHandlers.delete(method);
3214
+ } else {
3215
+ starNotificationHandler = void 0;
3216
+ }
3217
+ }
3218
+ };
3219
+ },
3220
+ onProgress: (_type, token, handler) => {
3221
+ if (progressHandlers.has(token)) {
3222
+ throw new Error(`Progress handler for token ${token} already registered`);
3223
+ }
3224
+ progressHandlers.set(token, handler);
3225
+ return {
3226
+ dispose: () => {
3227
+ progressHandlers.delete(token);
3228
+ }
3229
+ };
3230
+ },
3231
+ sendProgress: (_type, token, value) => {
3232
+ return connection.sendNotification(ProgressNotification.type, { token, value });
3233
+ },
3234
+ onUnhandledProgress: unhandledProgressEmitter.event,
3235
+ sendRequest: (type, ...args) => {
3236
+ throwIfClosedOrDisposed();
3237
+ throwIfNotListening();
3238
+ let method;
3239
+ let messageParams;
3240
+ let token = void 0;
3241
+ if (Is.string(type)) {
3242
+ method = type;
3243
+ const first = args[0];
3244
+ const last = args[args.length - 1];
3245
+ let paramStart = 0;
3246
+ let parameterStructures = messages_1.ParameterStructures.auto;
3247
+ if (messages_1.ParameterStructures.is(first)) {
3248
+ paramStart = 1;
3249
+ parameterStructures = first;
3250
+ }
3251
+ let paramEnd = args.length;
3252
+ if (cancellation_1.CancellationToken.is(last)) {
3253
+ paramEnd = paramEnd - 1;
3254
+ token = last;
3255
+ }
3256
+ const numberOfParams = paramEnd - paramStart;
3257
+ switch (numberOfParams) {
3258
+ case 0:
3259
+ messageParams = void 0;
3260
+ break;
3261
+ case 1:
3262
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
3263
+ break;
3264
+ default:
3265
+ if (parameterStructures === messages_1.ParameterStructures.byName) {
3266
+ throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
3267
+ }
3268
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
3269
+ break;
3270
+ }
3271
+ } else {
3272
+ const params = args;
3273
+ method = type.method;
3274
+ messageParams = computeMessageParams(type, params);
3275
+ const numberOfParams = type.numberOfParams;
3276
+ token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
3277
+ }
3278
+ const id = sequenceNumber++;
3279
+ let disposable;
3280
+ if (token) {
3281
+ disposable = token.onCancellationRequested(() => {
3282
+ const p = cancellationStrategy.sender.sendCancellation(connection, id);
3283
+ if (p === void 0) {
3284
+ logger2.log(`Received no promise from cancellation strategy when cancelling id ${id}`);
3285
+ return Promise.resolve();
3286
+ } else {
3287
+ return p.catch(() => {
3288
+ logger2.log(`Sending cancellation messages for id ${id} failed`);
3289
+ });
3290
+ }
3291
+ });
3292
+ }
3293
+ const requestMessage = {
3294
+ jsonrpc: version,
3295
+ id,
3296
+ method,
3297
+ params: messageParams
3298
+ };
3299
+ traceSendingRequest(requestMessage);
3300
+ if (typeof cancellationStrategy.sender.enableCancellation === "function") {
3301
+ cancellationStrategy.sender.enableCancellation(requestMessage);
3302
+ }
3303
+ return new Promise(async (resolve3, reject) => {
3304
+ const resolveWithCleanup = (r) => {
3305
+ resolve3(r);
3306
+ cancellationStrategy.sender.cleanup(id);
3307
+ disposable?.dispose();
3308
+ };
3309
+ const rejectWithCleanup = (r) => {
3310
+ reject(r);
3311
+ cancellationStrategy.sender.cleanup(id);
3312
+ disposable?.dispose();
3313
+ };
3314
+ const responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
3315
+ try {
3316
+ responsePromises.set(id, responsePromise);
3317
+ await messageWriter.write(requestMessage);
3318
+ } catch (error) {
3319
+ responsePromises.delete(id);
3320
+ responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason"));
3321
+ logger2.error(`Sending request failed.`);
3322
+ throw error;
3323
+ }
3324
+ });
3325
+ },
3326
+ onRequest: (type, handler) => {
3327
+ throwIfClosedOrDisposed();
3328
+ let method = null;
3329
+ if (StarRequestHandler.is(type)) {
3330
+ method = void 0;
3331
+ starRequestHandler = type;
3332
+ } else if (Is.string(type)) {
3333
+ method = null;
3334
+ if (handler !== void 0) {
3335
+ method = type;
3336
+ requestHandlers.set(type, { handler, type: void 0 });
3337
+ }
3338
+ } else {
3339
+ if (handler !== void 0) {
3340
+ method = type.method;
3341
+ requestHandlers.set(type.method, { type, handler });
3342
+ }
3343
+ }
3344
+ return {
3345
+ dispose: () => {
3346
+ if (method === null) {
3347
+ return;
3348
+ }
3349
+ if (method !== void 0) {
3350
+ requestHandlers.delete(method);
3351
+ } else {
3352
+ starRequestHandler = void 0;
3353
+ }
3354
+ }
3355
+ };
3356
+ },
3357
+ hasPendingResponse: () => {
3358
+ return responsePromises.size > 0;
3359
+ },
3360
+ trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
3361
+ let _sendNotification = false;
3362
+ let _traceFormat = TraceFormat.Text;
3363
+ if (sendNotificationOrTraceOptions !== void 0) {
3364
+ if (Is.boolean(sendNotificationOrTraceOptions)) {
3365
+ _sendNotification = sendNotificationOrTraceOptions;
3366
+ } else {
3367
+ _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
3368
+ _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
3369
+ }
3370
+ }
3371
+ trace = _value;
3372
+ traceFormat = _traceFormat;
3373
+ if (trace === Trace.Off) {
3374
+ tracer = void 0;
3375
+ } else {
3376
+ tracer = _tracer;
3377
+ }
3378
+ if (_sendNotification && !isClosed() && !isDisposed()) {
3379
+ await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
3380
+ }
3381
+ },
3382
+ onError: errorEmitter.event,
3383
+ onClose: closeEmitter.event,
3384
+ onUnhandledNotification: unhandledNotificationEmitter.event,
3385
+ onDispose: disposeEmitter.event,
3386
+ end: () => {
3387
+ messageWriter.end();
3388
+ },
3389
+ dispose: () => {
3390
+ if (isDisposed()) {
3391
+ return;
3392
+ }
3393
+ state = ConnectionState.Disposed;
3394
+ disposeEmitter.fire(void 0);
3395
+ const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed");
3396
+ for (const promise of responsePromises.values()) {
3397
+ promise.reject(error);
3398
+ }
3399
+ responsePromises = /* @__PURE__ */ new Map();
3400
+ requestTokens = /* @__PURE__ */ new Map();
3401
+ knownCanceledRequests = /* @__PURE__ */ new Set();
3402
+ messageQueue = new linkedMap_1.LinkedMap();
3403
+ if (Is.func(messageWriter.dispose)) {
3404
+ messageWriter.dispose();
3405
+ }
3406
+ if (Is.func(messageReader.dispose)) {
3407
+ messageReader.dispose();
3408
+ }
3409
+ },
3410
+ listen: () => {
3411
+ throwIfClosedOrDisposed();
3412
+ throwIfListening();
3413
+ state = ConnectionState.Listening;
3414
+ messageReader.listen(callback);
3415
+ },
3416
+ inspect: () => {
3417
+ (0, ral_1.default)().console.log("inspect");
3418
+ }
3419
+ };
3420
+ connection.onNotification(LogTraceNotification.type, (params) => {
3421
+ if (trace === Trace.Off || !tracer) {
3422
+ return;
3423
+ }
3424
+ const verbose = trace === Trace.Verbose || trace === Trace.Compact;
3425
+ tracer.log(params.message, verbose ? params.verbose : void 0);
3426
+ });
3427
+ connection.onNotification(ProgressNotification.type, (params) => {
3428
+ const handler = progressHandlers.get(params.token);
3429
+ if (handler) {
3430
+ handler(params.value);
3431
+ } else {
3432
+ unhandledProgressEmitter.fire(params);
3433
+ }
3434
+ });
3435
+ return connection;
3436
+ }
3437
+ exports.createMessageConnection = createMessageConnection2;
3438
+ }
3439
+ });
3440
+
3441
+ // node_modules/vscode-jsonrpc/lib/common/api.js
3442
+ var require_api = __commonJS({
3443
+ "node_modules/vscode-jsonrpc/lib/common/api.js"(exports) {
3444
+ "use strict";
3445
+ Object.defineProperty(exports, "__esModule", { value: true });
3446
+ exports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;
3447
+ exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = void 0;
3448
+ var messages_1 = require_messages();
3449
+ Object.defineProperty(exports, "Message", { enumerable: true, get: function() {
3450
+ return messages_1.Message;
3451
+ } });
3452
+ Object.defineProperty(exports, "RequestType", { enumerable: true, get: function() {
3453
+ return messages_1.RequestType;
3454
+ } });
3455
+ Object.defineProperty(exports, "RequestType0", { enumerable: true, get: function() {
3456
+ return messages_1.RequestType0;
3457
+ } });
3458
+ Object.defineProperty(exports, "RequestType1", { enumerable: true, get: function() {
3459
+ return messages_1.RequestType1;
3460
+ } });
3461
+ Object.defineProperty(exports, "RequestType2", { enumerable: true, get: function() {
3462
+ return messages_1.RequestType2;
3463
+ } });
3464
+ Object.defineProperty(exports, "RequestType3", { enumerable: true, get: function() {
3465
+ return messages_1.RequestType3;
3466
+ } });
3467
+ Object.defineProperty(exports, "RequestType4", { enumerable: true, get: function() {
3468
+ return messages_1.RequestType4;
3469
+ } });
3470
+ Object.defineProperty(exports, "RequestType5", { enumerable: true, get: function() {
3471
+ return messages_1.RequestType5;
3472
+ } });
3473
+ Object.defineProperty(exports, "RequestType6", { enumerable: true, get: function() {
3474
+ return messages_1.RequestType6;
3475
+ } });
3476
+ Object.defineProperty(exports, "RequestType7", { enumerable: true, get: function() {
3477
+ return messages_1.RequestType7;
3478
+ } });
3479
+ Object.defineProperty(exports, "RequestType8", { enumerable: true, get: function() {
3480
+ return messages_1.RequestType8;
3481
+ } });
3482
+ Object.defineProperty(exports, "RequestType9", { enumerable: true, get: function() {
3483
+ return messages_1.RequestType9;
3484
+ } });
3485
+ Object.defineProperty(exports, "ResponseError", { enumerable: true, get: function() {
3486
+ return messages_1.ResponseError;
3487
+ } });
3488
+ Object.defineProperty(exports, "ErrorCodes", { enumerable: true, get: function() {
3489
+ return messages_1.ErrorCodes;
3490
+ } });
3491
+ Object.defineProperty(exports, "NotificationType", { enumerable: true, get: function() {
3492
+ return messages_1.NotificationType;
3493
+ } });
3494
+ Object.defineProperty(exports, "NotificationType0", { enumerable: true, get: function() {
3495
+ return messages_1.NotificationType0;
3496
+ } });
3497
+ Object.defineProperty(exports, "NotificationType1", { enumerable: true, get: function() {
3498
+ return messages_1.NotificationType1;
3499
+ } });
3500
+ Object.defineProperty(exports, "NotificationType2", { enumerable: true, get: function() {
3501
+ return messages_1.NotificationType2;
3502
+ } });
3503
+ Object.defineProperty(exports, "NotificationType3", { enumerable: true, get: function() {
3504
+ return messages_1.NotificationType3;
3505
+ } });
3506
+ Object.defineProperty(exports, "NotificationType4", { enumerable: true, get: function() {
3507
+ return messages_1.NotificationType4;
3508
+ } });
3509
+ Object.defineProperty(exports, "NotificationType5", { enumerable: true, get: function() {
3510
+ return messages_1.NotificationType5;
3511
+ } });
3512
+ Object.defineProperty(exports, "NotificationType6", { enumerable: true, get: function() {
3513
+ return messages_1.NotificationType6;
3514
+ } });
3515
+ Object.defineProperty(exports, "NotificationType7", { enumerable: true, get: function() {
3516
+ return messages_1.NotificationType7;
3517
+ } });
3518
+ Object.defineProperty(exports, "NotificationType8", { enumerable: true, get: function() {
3519
+ return messages_1.NotificationType8;
3520
+ } });
3521
+ Object.defineProperty(exports, "NotificationType9", { enumerable: true, get: function() {
3522
+ return messages_1.NotificationType9;
3523
+ } });
3524
+ Object.defineProperty(exports, "ParameterStructures", { enumerable: true, get: function() {
3525
+ return messages_1.ParameterStructures;
3526
+ } });
3527
+ var linkedMap_1 = require_linkedMap();
3528
+ Object.defineProperty(exports, "LinkedMap", { enumerable: true, get: function() {
3529
+ return linkedMap_1.LinkedMap;
3530
+ } });
3531
+ Object.defineProperty(exports, "LRUCache", { enumerable: true, get: function() {
3532
+ return linkedMap_1.LRUCache;
3533
+ } });
3534
+ Object.defineProperty(exports, "Touch", { enumerable: true, get: function() {
3535
+ return linkedMap_1.Touch;
3536
+ } });
3537
+ var disposable_1 = require_disposable();
3538
+ Object.defineProperty(exports, "Disposable", { enumerable: true, get: function() {
3539
+ return disposable_1.Disposable;
3540
+ } });
3541
+ var events_1 = require_events();
3542
+ Object.defineProperty(exports, "Event", { enumerable: true, get: function() {
3543
+ return events_1.Event;
3544
+ } });
3545
+ Object.defineProperty(exports, "Emitter", { enumerable: true, get: function() {
3546
+ return events_1.Emitter;
3547
+ } });
3548
+ var cancellation_1 = require_cancellation();
3549
+ Object.defineProperty(exports, "CancellationTokenSource", { enumerable: true, get: function() {
3550
+ return cancellation_1.CancellationTokenSource;
3551
+ } });
3552
+ Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function() {
3553
+ return cancellation_1.CancellationToken;
3554
+ } });
3555
+ var sharedArrayCancellation_1 = require_sharedArrayCancellation();
3556
+ Object.defineProperty(exports, "SharedArraySenderStrategy", { enumerable: true, get: function() {
3557
+ return sharedArrayCancellation_1.SharedArraySenderStrategy;
3558
+ } });
3559
+ Object.defineProperty(exports, "SharedArrayReceiverStrategy", { enumerable: true, get: function() {
3560
+ return sharedArrayCancellation_1.SharedArrayReceiverStrategy;
3561
+ } });
3562
+ var messageReader_1 = require_messageReader();
3563
+ Object.defineProperty(exports, "MessageReader", { enumerable: true, get: function() {
3564
+ return messageReader_1.MessageReader;
3565
+ } });
3566
+ Object.defineProperty(exports, "AbstractMessageReader", { enumerable: true, get: function() {
3567
+ return messageReader_1.AbstractMessageReader;
3568
+ } });
3569
+ Object.defineProperty(exports, "ReadableStreamMessageReader", { enumerable: true, get: function() {
3570
+ return messageReader_1.ReadableStreamMessageReader;
3571
+ } });
3572
+ var messageWriter_1 = require_messageWriter();
3573
+ Object.defineProperty(exports, "MessageWriter", { enumerable: true, get: function() {
3574
+ return messageWriter_1.MessageWriter;
3575
+ } });
3576
+ Object.defineProperty(exports, "AbstractMessageWriter", { enumerable: true, get: function() {
3577
+ return messageWriter_1.AbstractMessageWriter;
3578
+ } });
3579
+ Object.defineProperty(exports, "WriteableStreamMessageWriter", { enumerable: true, get: function() {
3580
+ return messageWriter_1.WriteableStreamMessageWriter;
3581
+ } });
3582
+ var messageBuffer_1 = require_messageBuffer();
3583
+ Object.defineProperty(exports, "AbstractMessageBuffer", { enumerable: true, get: function() {
3584
+ return messageBuffer_1.AbstractMessageBuffer;
3585
+ } });
3586
+ var connection_1 = require_connection();
3587
+ Object.defineProperty(exports, "ConnectionStrategy", { enumerable: true, get: function() {
3588
+ return connection_1.ConnectionStrategy;
3589
+ } });
3590
+ Object.defineProperty(exports, "ConnectionOptions", { enumerable: true, get: function() {
3591
+ return connection_1.ConnectionOptions;
3592
+ } });
3593
+ Object.defineProperty(exports, "NullLogger", { enumerable: true, get: function() {
3594
+ return connection_1.NullLogger;
3595
+ } });
3596
+ Object.defineProperty(exports, "createMessageConnection", { enumerable: true, get: function() {
3597
+ return connection_1.createMessageConnection;
3598
+ } });
3599
+ Object.defineProperty(exports, "ProgressToken", { enumerable: true, get: function() {
3600
+ return connection_1.ProgressToken;
3601
+ } });
3602
+ Object.defineProperty(exports, "ProgressType", { enumerable: true, get: function() {
3603
+ return connection_1.ProgressType;
3604
+ } });
3605
+ Object.defineProperty(exports, "Trace", { enumerable: true, get: function() {
3606
+ return connection_1.Trace;
3607
+ } });
3608
+ Object.defineProperty(exports, "TraceValues", { enumerable: true, get: function() {
3609
+ return connection_1.TraceValues;
3610
+ } });
3611
+ Object.defineProperty(exports, "TraceFormat", { enumerable: true, get: function() {
3612
+ return connection_1.TraceFormat;
3613
+ } });
3614
+ Object.defineProperty(exports, "SetTraceNotification", { enumerable: true, get: function() {
3615
+ return connection_1.SetTraceNotification;
3616
+ } });
3617
+ Object.defineProperty(exports, "LogTraceNotification", { enumerable: true, get: function() {
3618
+ return connection_1.LogTraceNotification;
3619
+ } });
3620
+ Object.defineProperty(exports, "ConnectionErrors", { enumerable: true, get: function() {
3621
+ return connection_1.ConnectionErrors;
3622
+ } });
3623
+ Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function() {
3624
+ return connection_1.ConnectionError;
3625
+ } });
3626
+ Object.defineProperty(exports, "CancellationReceiverStrategy", { enumerable: true, get: function() {
3627
+ return connection_1.CancellationReceiverStrategy;
3628
+ } });
3629
+ Object.defineProperty(exports, "CancellationSenderStrategy", { enumerable: true, get: function() {
3630
+ return connection_1.CancellationSenderStrategy;
3631
+ } });
3632
+ Object.defineProperty(exports, "CancellationStrategy", { enumerable: true, get: function() {
3633
+ return connection_1.CancellationStrategy;
3634
+ } });
3635
+ Object.defineProperty(exports, "MessageStrategy", { enumerable: true, get: function() {
3636
+ return connection_1.MessageStrategy;
3637
+ } });
3638
+ var ral_1 = require_ral();
3639
+ exports.RAL = ral_1.default;
3640
+ }
3641
+ });
3642
+
3643
+ // node_modules/vscode-jsonrpc/lib/node/ril.js
3644
+ var require_ril = __commonJS({
3645
+ "node_modules/vscode-jsonrpc/lib/node/ril.js"(exports) {
3646
+ "use strict";
3647
+ Object.defineProperty(exports, "__esModule", { value: true });
3648
+ var util_1 = __require("util");
3649
+ var api_1 = require_api();
3650
+ var MessageBuffer = class _MessageBuffer extends api_1.AbstractMessageBuffer {
3651
+ constructor(encoding = "utf-8") {
3652
+ super(encoding);
3653
+ }
3654
+ emptyBuffer() {
3655
+ return _MessageBuffer.emptyBuffer;
3656
+ }
3657
+ fromString(value, encoding) {
3658
+ return Buffer.from(value, encoding);
3659
+ }
3660
+ toString(value, encoding) {
3661
+ if (value instanceof Buffer) {
3662
+ return value.toString(encoding);
3663
+ } else {
3664
+ return new util_1.TextDecoder(encoding).decode(value);
3665
+ }
3666
+ }
3667
+ asNative(buffer, length) {
3668
+ if (length === void 0) {
3669
+ return buffer instanceof Buffer ? buffer : Buffer.from(buffer);
3670
+ } else {
3671
+ return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);
3672
+ }
3673
+ }
3674
+ allocNative(length) {
3675
+ return Buffer.allocUnsafe(length);
3676
+ }
3677
+ };
3678
+ MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0);
3679
+ var ReadableStreamWrapper = class {
3680
+ constructor(stream) {
3681
+ this.stream = stream;
3682
+ }
3683
+ onClose(listener) {
3684
+ this.stream.on("close", listener);
3685
+ return api_1.Disposable.create(() => this.stream.off("close", listener));
3686
+ }
3687
+ onError(listener) {
3688
+ this.stream.on("error", listener);
3689
+ return api_1.Disposable.create(() => this.stream.off("error", listener));
3690
+ }
3691
+ onEnd(listener) {
3692
+ this.stream.on("end", listener);
3693
+ return api_1.Disposable.create(() => this.stream.off("end", listener));
3694
+ }
3695
+ onData(listener) {
3696
+ this.stream.on("data", listener);
3697
+ return api_1.Disposable.create(() => this.stream.off("data", listener));
3698
+ }
3699
+ };
3700
+ var WritableStreamWrapper = class {
3701
+ constructor(stream) {
3702
+ this.stream = stream;
3703
+ }
3704
+ onClose(listener) {
3705
+ this.stream.on("close", listener);
3706
+ return api_1.Disposable.create(() => this.stream.off("close", listener));
3707
+ }
3708
+ onError(listener) {
3709
+ this.stream.on("error", listener);
3710
+ return api_1.Disposable.create(() => this.stream.off("error", listener));
3711
+ }
3712
+ onEnd(listener) {
3713
+ this.stream.on("end", listener);
3714
+ return api_1.Disposable.create(() => this.stream.off("end", listener));
3715
+ }
3716
+ write(data, encoding) {
3717
+ return new Promise((resolve3, reject) => {
3718
+ const callback = (error) => {
3719
+ if (error === void 0 || error === null) {
3720
+ resolve3();
3721
+ } else {
3722
+ reject(error);
3723
+ }
3724
+ };
3725
+ if (typeof data === "string") {
3726
+ this.stream.write(data, encoding, callback);
3727
+ } else {
3728
+ this.stream.write(data, callback);
3729
+ }
3730
+ });
3731
+ }
3732
+ end() {
3733
+ this.stream.end();
3734
+ }
3735
+ };
3736
+ var _ril = Object.freeze({
3737
+ messageBuffer: Object.freeze({
3738
+ create: (encoding) => new MessageBuffer(encoding)
3739
+ }),
3740
+ applicationJson: Object.freeze({
3741
+ encoder: Object.freeze({
3742
+ name: "application/json",
3743
+ encode: (msg, options) => {
3744
+ try {
3745
+ return Promise.resolve(Buffer.from(JSON.stringify(msg, void 0, 0), options.charset));
3746
+ } catch (err) {
3747
+ return Promise.reject(err);
3748
+ }
3749
+ }
3750
+ }),
3751
+ decoder: Object.freeze({
3752
+ name: "application/json",
3753
+ decode: (buffer, options) => {
3754
+ try {
3755
+ if (buffer instanceof Buffer) {
3756
+ return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
3757
+ } else {
3758
+ return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
3759
+ }
3760
+ } catch (err) {
3761
+ return Promise.reject(err);
3762
+ }
3763
+ }
3764
+ })
3765
+ }),
3766
+ stream: Object.freeze({
3767
+ asReadableStream: (stream) => new ReadableStreamWrapper(stream),
3768
+ asWritableStream: (stream) => new WritableStreamWrapper(stream)
3769
+ }),
3770
+ console,
3771
+ timer: Object.freeze({
3772
+ setTimeout(callback, ms, ...args) {
3773
+ const handle = setTimeout(callback, ms, ...args);
3774
+ return { dispose: () => clearTimeout(handle) };
3775
+ },
3776
+ setImmediate(callback, ...args) {
3777
+ const handle = setImmediate(callback, ...args);
3778
+ return { dispose: () => clearImmediate(handle) };
3779
+ },
3780
+ setInterval(callback, ms, ...args) {
3781
+ const handle = setInterval(callback, ms, ...args);
3782
+ return { dispose: () => clearInterval(handle) };
3783
+ }
3784
+ })
3785
+ });
3786
+ function RIL() {
3787
+ return _ril;
3788
+ }
3789
+ (function(RIL2) {
3790
+ function install() {
3791
+ api_1.RAL.install(_ril);
3792
+ }
3793
+ RIL2.install = install;
3794
+ })(RIL || (RIL = {}));
3795
+ exports.default = RIL;
3796
+ }
3797
+ });
3798
+
3799
+ // node_modules/vscode-jsonrpc/lib/node/main.js
3800
+ var require_main = __commonJS({
3801
+ "node_modules/vscode-jsonrpc/lib/node/main.js"(exports) {
3802
+ "use strict";
3803
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
3804
+ if (k2 === void 0) k2 = k;
3805
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3806
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3807
+ desc = { enumerable: true, get: function() {
3808
+ return m[k];
3809
+ } };
3810
+ }
3811
+ Object.defineProperty(o, k2, desc);
3812
+ }) : (function(o, m, k, k2) {
3813
+ if (k2 === void 0) k2 = k;
3814
+ o[k2] = m[k];
3815
+ }));
3816
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
3817
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
3818
+ };
3819
+ Object.defineProperty(exports, "__esModule", { value: true });
3820
+ exports.createMessageConnection = exports.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.PortMessageWriter = exports.PortMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = void 0;
3821
+ var ril_1 = require_ril();
3822
+ ril_1.default.install();
3823
+ var path = __require("path");
3824
+ var os = __require("os");
3825
+ var crypto_1 = __require("crypto");
3826
+ var net_1 = __require("net");
3827
+ var api_1 = require_api();
3828
+ __exportStar(require_api(), exports);
3829
+ var IPCMessageReader = class extends api_1.AbstractMessageReader {
3830
+ constructor(process2) {
3831
+ super();
3832
+ this.process = process2;
3833
+ let eventEmitter = this.process;
3834
+ eventEmitter.on("error", (error) => this.fireError(error));
3835
+ eventEmitter.on("close", () => this.fireClose());
3836
+ }
3837
+ listen(callback) {
3838
+ this.process.on("message", callback);
3839
+ return api_1.Disposable.create(() => this.process.off("message", callback));
3840
+ }
3841
+ };
3842
+ exports.IPCMessageReader = IPCMessageReader;
3843
+ var IPCMessageWriter = class extends api_1.AbstractMessageWriter {
3844
+ constructor(process2) {
3845
+ super();
3846
+ this.process = process2;
3847
+ this.errorCount = 0;
3848
+ const eventEmitter = this.process;
3849
+ eventEmitter.on("error", (error) => this.fireError(error));
3850
+ eventEmitter.on("close", () => this.fireClose);
3851
+ }
3852
+ write(msg) {
3853
+ try {
3854
+ if (typeof this.process.send === "function") {
3855
+ this.process.send(msg, void 0, void 0, (error) => {
3856
+ if (error) {
3857
+ this.errorCount++;
3858
+ this.handleError(error, msg);
3859
+ } else {
3860
+ this.errorCount = 0;
3861
+ }
3862
+ });
3863
+ }
3864
+ return Promise.resolve();
3865
+ } catch (error) {
3866
+ this.handleError(error, msg);
3867
+ return Promise.reject(error);
3868
+ }
3869
+ }
3870
+ handleError(error, msg) {
3871
+ this.errorCount++;
3872
+ this.fireError(error, msg, this.errorCount);
3873
+ }
3874
+ end() {
3875
+ }
3876
+ };
3877
+ exports.IPCMessageWriter = IPCMessageWriter;
3878
+ var PortMessageReader = class extends api_1.AbstractMessageReader {
3879
+ constructor(port) {
3880
+ super();
3881
+ this.onData = new api_1.Emitter();
3882
+ port.on("close", () => this.fireClose);
3883
+ port.on("error", (error) => this.fireError(error));
3884
+ port.on("message", (message) => {
3885
+ this.onData.fire(message);
3886
+ });
3887
+ }
3888
+ listen(callback) {
3889
+ return this.onData.event(callback);
3890
+ }
3891
+ };
3892
+ exports.PortMessageReader = PortMessageReader;
3893
+ var PortMessageWriter = class extends api_1.AbstractMessageWriter {
3894
+ constructor(port) {
3895
+ super();
3896
+ this.port = port;
3897
+ this.errorCount = 0;
3898
+ port.on("close", () => this.fireClose());
3899
+ port.on("error", (error) => this.fireError(error));
3900
+ }
3901
+ write(msg) {
3902
+ try {
3903
+ this.port.postMessage(msg);
3904
+ return Promise.resolve();
3905
+ } catch (error) {
3906
+ this.handleError(error, msg);
3907
+ return Promise.reject(error);
3908
+ }
3909
+ }
3910
+ handleError(error, msg) {
3911
+ this.errorCount++;
3912
+ this.fireError(error, msg, this.errorCount);
3913
+ }
3914
+ end() {
3915
+ }
3916
+ };
3917
+ exports.PortMessageWriter = PortMessageWriter;
3918
+ var SocketMessageReader = class extends api_1.ReadableStreamMessageReader {
3919
+ constructor(socket, encoding = "utf-8") {
3920
+ super((0, ril_1.default)().stream.asReadableStream(socket), encoding);
3921
+ }
3922
+ };
3923
+ exports.SocketMessageReader = SocketMessageReader;
3924
+ var SocketMessageWriter = class extends api_1.WriteableStreamMessageWriter {
3925
+ constructor(socket, options) {
3926
+ super((0, ril_1.default)().stream.asWritableStream(socket), options);
3927
+ this.socket = socket;
3928
+ }
3929
+ dispose() {
3930
+ super.dispose();
3931
+ this.socket.destroy();
3932
+ }
3933
+ };
3934
+ exports.SocketMessageWriter = SocketMessageWriter;
3935
+ var StreamMessageReader2 = class extends api_1.ReadableStreamMessageReader {
3936
+ constructor(readable, encoding) {
3937
+ super((0, ril_1.default)().stream.asReadableStream(readable), encoding);
3938
+ }
3939
+ };
3940
+ exports.StreamMessageReader = StreamMessageReader2;
3941
+ var StreamMessageWriter2 = class extends api_1.WriteableStreamMessageWriter {
3942
+ constructor(writable, options) {
3943
+ super((0, ril_1.default)().stream.asWritableStream(writable), options);
3944
+ }
3945
+ };
3946
+ exports.StreamMessageWriter = StreamMessageWriter2;
3947
+ var XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"];
3948
+ var safeIpcPathLengths = /* @__PURE__ */ new Map([
3949
+ ["linux", 107],
3950
+ ["darwin", 103]
3951
+ ]);
3952
+ function generateRandomPipeName() {
3953
+ const randomSuffix = (0, crypto_1.randomBytes)(21).toString("hex");
3954
+ if (process.platform === "win32") {
3955
+ return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
3956
+ }
3957
+ let result;
3958
+ if (XDG_RUNTIME_DIR) {
3959
+ result = path.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);
3960
+ } else {
3961
+ result = path.join(os.tmpdir(), `vscode-${randomSuffix}.sock`);
3962
+ }
3963
+ const limit = safeIpcPathLengths.get(process.platform);
3964
+ if (limit !== void 0 && result.length > limit) {
3965
+ (0, ril_1.default)().console.warn(`WARNING: IPC handle "${result}" is longer than ${limit} characters.`);
3966
+ }
3967
+ return result;
3968
+ }
3969
+ exports.generateRandomPipeName = generateRandomPipeName;
3970
+ function createClientPipeTransport(pipeName, encoding = "utf-8") {
3971
+ let connectResolve;
3972
+ const connected = new Promise((resolve3, _reject) => {
3973
+ connectResolve = resolve3;
3974
+ });
3975
+ return new Promise((resolve3, reject) => {
3976
+ let server = (0, net_1.createServer)((socket) => {
3977
+ server.close();
3978
+ connectResolve([
3979
+ new SocketMessageReader(socket, encoding),
3980
+ new SocketMessageWriter(socket, encoding)
3981
+ ]);
3982
+ });
3983
+ server.on("error", reject);
3984
+ server.listen(pipeName, () => {
3985
+ server.removeListener("error", reject);
3986
+ resolve3({
3987
+ onConnected: () => {
3988
+ return connected;
3989
+ }
3990
+ });
3991
+ });
3992
+ });
3993
+ }
3994
+ exports.createClientPipeTransport = createClientPipeTransport;
3995
+ function createServerPipeTransport(pipeName, encoding = "utf-8") {
3996
+ const socket = (0, net_1.createConnection)(pipeName);
3997
+ return [
3998
+ new SocketMessageReader(socket, encoding),
3999
+ new SocketMessageWriter(socket, encoding)
4000
+ ];
4001
+ }
4002
+ exports.createServerPipeTransport = createServerPipeTransport;
4003
+ function createClientSocketTransport(port, encoding = "utf-8") {
4004
+ let connectResolve;
4005
+ const connected = new Promise((resolve3, _reject) => {
4006
+ connectResolve = resolve3;
4007
+ });
4008
+ return new Promise((resolve3, reject) => {
4009
+ const server = (0, net_1.createServer)((socket) => {
4010
+ server.close();
4011
+ connectResolve([
4012
+ new SocketMessageReader(socket, encoding),
4013
+ new SocketMessageWriter(socket, encoding)
4014
+ ]);
4015
+ });
4016
+ server.on("error", reject);
4017
+ server.listen(port, "127.0.0.1", () => {
4018
+ server.removeListener("error", reject);
4019
+ resolve3({
4020
+ onConnected: () => {
4021
+ return connected;
4022
+ }
4023
+ });
4024
+ });
4025
+ });
4026
+ }
4027
+ exports.createClientSocketTransport = createClientSocketTransport;
4028
+ function createServerSocketTransport(port, encoding = "utf-8") {
4029
+ const socket = (0, net_1.createConnection)(port, "127.0.0.1");
4030
+ return [
4031
+ new SocketMessageReader(socket, encoding),
4032
+ new SocketMessageWriter(socket, encoding)
4033
+ ];
4034
+ }
4035
+ exports.createServerSocketTransport = createServerSocketTransport;
4036
+ function isReadableStream(value) {
4037
+ const candidate = value;
4038
+ return candidate.read !== void 0 && candidate.addListener !== void 0;
4039
+ }
4040
+ function isWritableStream(value) {
4041
+ const candidate = value;
4042
+ return candidate.write !== void 0 && candidate.addListener !== void 0;
4043
+ }
4044
+ function createMessageConnection2(input, output, logger2, options) {
4045
+ if (!logger2) {
4046
+ logger2 = api_1.NullLogger;
4047
+ }
4048
+ const reader = isReadableStream(input) ? new StreamMessageReader2(input) : input;
4049
+ const writer = isWritableStream(output) ? new StreamMessageWriter2(output) : output;
4050
+ if (api_1.ConnectionStrategy.is(options)) {
4051
+ options = { connectionStrategy: options };
4052
+ }
4053
+ return (0, api_1.createMessageConnection)(reader, writer, logger2, options);
4054
+ }
4055
+ exports.createMessageConnection = createMessageConnection2;
4056
+ }
4057
+ });
4058
+
4059
+ // node_modules/vscode-jsonrpc/node.js
4060
+ var require_node = __commonJS({
4061
+ "node_modules/vscode-jsonrpc/node.js"(exports, module) {
4062
+ "use strict";
4063
+ module.exports = require_main();
4064
+ }
4065
+ });
4066
+
4067
+ // node_modules/@github/copilot-sdk/dist/sdkProtocolVersion.js
4068
+ function getSdkProtocolVersion() {
4069
+ return SDK_PROTOCOL_VERSION;
4070
+ }
4071
+ var SDK_PROTOCOL_VERSION;
4072
+ var init_sdkProtocolVersion = __esm({
4073
+ "node_modules/@github/copilot-sdk/dist/sdkProtocolVersion.js"() {
4074
+ "use strict";
4075
+ SDK_PROTOCOL_VERSION = 2;
4076
+ }
4077
+ });
4078
+
4079
+ // node_modules/@github/copilot-sdk/dist/session.js
4080
+ var CopilotSession;
4081
+ var init_session = __esm({
4082
+ "node_modules/@github/copilot-sdk/dist/session.js"() {
4083
+ "use strict";
4084
+ CopilotSession = class {
4085
+ /**
4086
+ * Creates a new CopilotSession instance.
4087
+ *
4088
+ * @param sessionId - The unique identifier for this session
4089
+ * @param connection - The JSON-RPC message connection to the Copilot CLI
4090
+ * @param workspacePath - Path to the session workspace directory (when infinite sessions enabled)
4091
+ * @internal This constructor is internal. Use {@link CopilotClient.createSession} to create sessions.
4092
+ */
4093
+ constructor(sessionId, connection, _workspacePath) {
4094
+ this.sessionId = sessionId;
4095
+ this.connection = connection;
4096
+ this._workspacePath = _workspacePath;
4097
+ }
4098
+ eventHandlers = /* @__PURE__ */ new Set();
4099
+ typedEventHandlers = /* @__PURE__ */ new Map();
4100
+ toolHandlers = /* @__PURE__ */ new Map();
4101
+ permissionHandler;
4102
+ userInputHandler;
4103
+ hooks;
4104
+ /**
4105
+ * Path to the session workspace directory when infinite sessions are enabled.
4106
+ * Contains checkpoints/, plan.md, and files/ subdirectories.
4107
+ * Undefined if infinite sessions are disabled.
4108
+ */
4109
+ get workspacePath() {
4110
+ return this._workspacePath;
4111
+ }
4112
+ /**
4113
+ * Sends a message to this session and waits for the response.
4114
+ *
4115
+ * The message is processed asynchronously. Subscribe to events via {@link on}
4116
+ * to receive streaming responses and other session events.
4117
+ *
4118
+ * @param options - The message options including the prompt and optional attachments
4119
+ * @returns A promise that resolves with the message ID of the response
4120
+ * @throws Error if the session has been destroyed or the connection fails
4121
+ *
4122
+ * @example
4123
+ * ```typescript
4124
+ * const messageId = await session.send({
4125
+ * prompt: "Explain this code",
4126
+ * attachments: [{ type: "file", path: "./src/index.ts" }]
4127
+ * });
4128
+ * ```
4129
+ */
4130
+ async send(options) {
4131
+ const response = await this.connection.sendRequest("session.send", {
4132
+ sessionId: this.sessionId,
4133
+ prompt: options.prompt,
4134
+ attachments: options.attachments,
4135
+ mode: options.mode
4136
+ });
4137
+ return response.messageId;
4138
+ }
4139
+ /**
4140
+ * Sends a message to this session and waits until the session becomes idle.
4141
+ *
4142
+ * This is a convenience method that combines {@link send} with waiting for
4143
+ * the `session.idle` event. Use this when you want to block until the
4144
+ * assistant has finished processing the message.
4145
+ *
4146
+ * Events are still delivered to handlers registered via {@link on} while waiting.
4147
+ *
4148
+ * @param options - The message options including the prompt and optional attachments
4149
+ * @param timeout - Timeout in milliseconds (default: 60000). Controls how long to wait; does not abort in-flight agent work.
4150
+ * @returns A promise that resolves with the final assistant message when the session becomes idle,
4151
+ * or undefined if no assistant message was received
4152
+ * @throws Error if the timeout is reached before the session becomes idle
4153
+ * @throws Error if the session has been destroyed or the connection fails
4154
+ *
4155
+ * @example
4156
+ * ```typescript
4157
+ * // Send and wait for completion with default 60s timeout
4158
+ * const response = await session.sendAndWait({ prompt: "What is 2+2?" });
4159
+ * console.log(response?.data.content); // "4"
4160
+ * ```
4161
+ */
4162
+ async sendAndWait(options, timeout) {
4163
+ const effectiveTimeout = timeout ?? 6e4;
4164
+ let resolveIdle;
4165
+ let rejectWithError;
4166
+ const idlePromise = new Promise((resolve3, reject) => {
4167
+ resolveIdle = resolve3;
4168
+ rejectWithError = reject;
4169
+ });
4170
+ let lastAssistantMessage;
4171
+ const unsubscribe = this.on((event) => {
4172
+ if (event.type === "assistant.message") {
4173
+ lastAssistantMessage = event;
4174
+ } else if (event.type === "session.idle") {
4175
+ resolveIdle();
4176
+ } else if (event.type === "session.error") {
4177
+ const error = new Error(event.data.message);
4178
+ error.stack = event.data.stack;
4179
+ rejectWithError(error);
4180
+ }
4181
+ });
4182
+ let timeoutId;
4183
+ try {
4184
+ await this.send(options);
4185
+ const timeoutPromise = new Promise((_, reject) => {
4186
+ timeoutId = setTimeout(
4187
+ () => reject(
4188
+ new Error(
4189
+ `Timeout after ${effectiveTimeout}ms waiting for session.idle`
4190
+ )
4191
+ ),
4192
+ effectiveTimeout
4193
+ );
4194
+ });
4195
+ await Promise.race([idlePromise, timeoutPromise]);
4196
+ return lastAssistantMessage;
4197
+ } finally {
4198
+ if (timeoutId !== void 0) {
4199
+ clearTimeout(timeoutId);
4200
+ }
4201
+ unsubscribe();
4202
+ }
4203
+ }
4204
+ on(eventTypeOrHandler, handler) {
4205
+ if (typeof eventTypeOrHandler === "string" && handler) {
4206
+ const eventType = eventTypeOrHandler;
4207
+ if (!this.typedEventHandlers.has(eventType)) {
4208
+ this.typedEventHandlers.set(eventType, /* @__PURE__ */ new Set());
4209
+ }
4210
+ const storedHandler = handler;
4211
+ this.typedEventHandlers.get(eventType).add(storedHandler);
4212
+ return () => {
4213
+ const handlers = this.typedEventHandlers.get(eventType);
4214
+ if (handlers) {
4215
+ handlers.delete(storedHandler);
4216
+ }
4217
+ };
4218
+ }
4219
+ const wildcardHandler = eventTypeOrHandler;
4220
+ this.eventHandlers.add(wildcardHandler);
4221
+ return () => {
4222
+ this.eventHandlers.delete(wildcardHandler);
4223
+ };
4224
+ }
4225
+ /**
4226
+ * Dispatches an event to all registered handlers.
4227
+ *
4228
+ * @param event - The session event to dispatch
4229
+ * @internal This method is for internal use by the SDK.
4230
+ */
4231
+ _dispatchEvent(event) {
4232
+ const typedHandlers = this.typedEventHandlers.get(event.type);
4233
+ if (typedHandlers) {
4234
+ for (const handler of typedHandlers) {
4235
+ try {
4236
+ handler(event);
4237
+ } catch (_error) {
4238
+ }
4239
+ }
4240
+ }
4241
+ for (const handler of this.eventHandlers) {
4242
+ try {
4243
+ handler(event);
4244
+ } catch (_error) {
4245
+ }
4246
+ }
4247
+ }
4248
+ /**
4249
+ * Registers custom tool handlers for this session.
4250
+ *
4251
+ * Tools allow the assistant to execute custom functions. When the assistant
4252
+ * invokes a tool, the corresponding handler is called with the tool arguments.
4253
+ *
4254
+ * @param tools - An array of tool definitions with their handlers, or undefined to clear all tools
4255
+ * @internal This method is typically called internally when creating a session with tools.
4256
+ */
4257
+ registerTools(tools) {
4258
+ this.toolHandlers.clear();
4259
+ if (!tools) {
4260
+ return;
4261
+ }
4262
+ for (const tool of tools) {
4263
+ this.toolHandlers.set(tool.name, tool.handler);
4264
+ }
4265
+ }
4266
+ /**
4267
+ * Retrieves a registered tool handler by name.
4268
+ *
4269
+ * @param name - The name of the tool to retrieve
4270
+ * @returns The tool handler if found, or undefined
4271
+ * @internal This method is for internal use by the SDK.
4272
+ */
4273
+ getToolHandler(name) {
4274
+ return this.toolHandlers.get(name);
4275
+ }
4276
+ /**
4277
+ * Registers a handler for permission requests.
4278
+ *
4279
+ * When the assistant needs permission to perform certain actions (e.g., file operations),
4280
+ * this handler is called to approve or deny the request.
4281
+ *
4282
+ * @param handler - The permission handler function, or undefined to remove the handler
4283
+ * @internal This method is typically called internally when creating a session.
4284
+ */
4285
+ registerPermissionHandler(handler) {
4286
+ this.permissionHandler = handler;
4287
+ }
4288
+ /**
4289
+ * Registers a user input handler for ask_user requests.
4290
+ *
4291
+ * When the agent needs input from the user (via ask_user tool),
4292
+ * this handler is called to provide the response.
4293
+ *
4294
+ * @param handler - The user input handler function, or undefined to remove the handler
4295
+ * @internal This method is typically called internally when creating a session.
4296
+ */
4297
+ registerUserInputHandler(handler) {
4298
+ this.userInputHandler = handler;
4299
+ }
4300
+ /**
4301
+ * Registers hook handlers for session lifecycle events.
4302
+ *
4303
+ * Hooks allow custom logic to be executed at various points during
4304
+ * the session lifecycle (before/after tool use, session start/end, etc.).
4305
+ *
4306
+ * @param hooks - The hook handlers object, or undefined to remove all hooks
4307
+ * @internal This method is typically called internally when creating a session.
4308
+ */
4309
+ registerHooks(hooks) {
4310
+ this.hooks = hooks;
4311
+ }
4312
+ /**
4313
+ * Handles a permission request from the Copilot CLI.
4314
+ *
4315
+ * @param request - The permission request data from the CLI
4316
+ * @returns A promise that resolves with the permission decision
4317
+ * @internal This method is for internal use by the SDK.
4318
+ */
4319
+ async _handlePermissionRequest(request) {
4320
+ if (!this.permissionHandler) {
4321
+ return { kind: "denied-no-approval-rule-and-could-not-request-from-user" };
4322
+ }
4323
+ try {
4324
+ const result = await this.permissionHandler(request, {
4325
+ sessionId: this.sessionId
4326
+ });
4327
+ return result;
4328
+ } catch (_error) {
4329
+ return { kind: "denied-no-approval-rule-and-could-not-request-from-user" };
4330
+ }
4331
+ }
4332
+ /**
4333
+ * Handles a user input request from the Copilot CLI.
4334
+ *
4335
+ * @param request - The user input request data from the CLI
4336
+ * @returns A promise that resolves with the user's response
4337
+ * @internal This method is for internal use by the SDK.
4338
+ */
4339
+ async _handleUserInputRequest(request) {
4340
+ if (!this.userInputHandler) {
4341
+ throw new Error("User input requested but no handler registered");
4342
+ }
4343
+ try {
4344
+ const result = await this.userInputHandler(request, {
4345
+ sessionId: this.sessionId
4346
+ });
4347
+ return result;
4348
+ } catch (error) {
4349
+ throw error;
4350
+ }
4351
+ }
4352
+ /**
4353
+ * Handles a hooks invocation from the Copilot CLI.
4354
+ *
4355
+ * @param hookType - The type of hook being invoked
4356
+ * @param input - The input data for the hook
4357
+ * @returns A promise that resolves with the hook output, or undefined
4358
+ * @internal This method is for internal use by the SDK.
4359
+ */
4360
+ async _handleHooksInvoke(hookType, input) {
4361
+ if (!this.hooks) {
4362
+ return void 0;
4363
+ }
4364
+ const handlerMap = {
4365
+ preToolUse: this.hooks.onPreToolUse,
4366
+ postToolUse: this.hooks.onPostToolUse,
4367
+ userPromptSubmitted: this.hooks.onUserPromptSubmitted,
4368
+ sessionStart: this.hooks.onSessionStart,
4369
+ sessionEnd: this.hooks.onSessionEnd,
4370
+ errorOccurred: this.hooks.onErrorOccurred
4371
+ };
4372
+ const handler = handlerMap[hookType];
4373
+ if (!handler) {
4374
+ return void 0;
4375
+ }
4376
+ try {
4377
+ const result = await handler(input, { sessionId: this.sessionId });
4378
+ return result;
4379
+ } catch (_error) {
4380
+ return void 0;
4381
+ }
4382
+ }
4383
+ /**
4384
+ * Retrieves all events and messages from this session's history.
4385
+ *
4386
+ * This returns the complete conversation history including user messages,
4387
+ * assistant responses, tool executions, and other session events.
4388
+ *
4389
+ * @returns A promise that resolves with an array of all session events
4390
+ * @throws Error if the session has been destroyed or the connection fails
4391
+ *
4392
+ * @example
4393
+ * ```typescript
4394
+ * const events = await session.getMessages();
4395
+ * for (const event of events) {
4396
+ * if (event.type === "assistant.message") {
4397
+ * console.log("Assistant:", event.data.content);
4398
+ * }
4399
+ * }
4400
+ * ```
4401
+ */
4402
+ async getMessages() {
4403
+ const response = await this.connection.sendRequest("session.getMessages", {
4404
+ sessionId: this.sessionId
4405
+ });
4406
+ return response.events;
4407
+ }
4408
+ /**
4409
+ * Destroys this session and releases all associated resources.
4410
+ *
4411
+ * After calling this method, the session can no longer be used. All event
4412
+ * handlers and tool handlers are cleared. To continue the conversation,
4413
+ * use {@link CopilotClient.resumeSession} with the session ID.
4414
+ *
4415
+ * @returns A promise that resolves when the session is destroyed
4416
+ * @throws Error if the connection fails
4417
+ *
4418
+ * @example
4419
+ * ```typescript
4420
+ * // Clean up when done
4421
+ * await session.destroy();
4422
+ * ```
4423
+ */
4424
+ async destroy() {
4425
+ await this.connection.sendRequest("session.destroy", {
4426
+ sessionId: this.sessionId
4427
+ });
4428
+ this.eventHandlers.clear();
4429
+ this.typedEventHandlers.clear();
4430
+ this.toolHandlers.clear();
4431
+ this.permissionHandler = void 0;
4432
+ }
4433
+ /**
4434
+ * Aborts the currently processing message in this session.
4435
+ *
4436
+ * Use this to cancel a long-running request. The session remains valid
4437
+ * and can continue to be used for new messages.
4438
+ *
4439
+ * @returns A promise that resolves when the abort request is acknowledged
4440
+ * @throws Error if the session has been destroyed or the connection fails
4441
+ *
4442
+ * @example
4443
+ * ```typescript
4444
+ * // Start a long-running request
4445
+ * const messagePromise = session.send({ prompt: "Write a very long story..." });
4446
+ *
4447
+ * // Abort after 5 seconds
4448
+ * setTimeout(async () => {
4449
+ * await session.abort();
4450
+ * }, 5000);
4451
+ * ```
4452
+ */
4453
+ async abort() {
4454
+ await this.connection.sendRequest("session.abort", {
4455
+ sessionId: this.sessionId
4456
+ });
4457
+ }
4458
+ };
4459
+ }
4460
+ });
4461
+
4462
+ // node_modules/@github/copilot-sdk/dist/client.js
4463
+ import { spawn } from "child_process";
4464
+ import { existsSync as existsSync4 } from "fs";
4465
+ import { Socket } from "net";
4466
+ import { dirname as dirname3, join as join5 } from "path";
4467
+ import { fileURLToPath as fileURLToPath3 } from "url";
4468
+ function isZodSchema(value) {
4469
+ return value != null && typeof value === "object" && "toJSONSchema" in value && typeof value.toJSONSchema === "function";
4470
+ }
4471
+ function toJsonSchema(parameters) {
4472
+ if (!parameters) return void 0;
4473
+ if (isZodSchema(parameters)) {
4474
+ return parameters.toJSONSchema();
4475
+ }
4476
+ return parameters;
4477
+ }
4478
+ function getBundledCliPath() {
4479
+ const sdkUrl = import.meta.resolve("@github/copilot/sdk");
4480
+ const sdkPath = fileURLToPath3(sdkUrl);
4481
+ return join5(dirname3(dirname3(sdkPath)), "index.js");
4482
+ }
4483
+ var import_node, CopilotClient;
4484
+ var init_client = __esm({
4485
+ "node_modules/@github/copilot-sdk/dist/client.js"() {
4486
+ "use strict";
4487
+ import_node = __toESM(require_node(), 1);
4488
+ init_sdkProtocolVersion();
4489
+ init_session();
4490
+ CopilotClient = class {
4491
+ cliProcess = null;
4492
+ connection = null;
4493
+ socket = null;
4494
+ actualPort = null;
4495
+ actualHost = "localhost";
4496
+ state = "disconnected";
4497
+ sessions = /* @__PURE__ */ new Map();
4498
+ options;
4499
+ isExternalServer = false;
4500
+ forceStopping = false;
4501
+ modelsCache = null;
4502
+ modelsCacheLock = Promise.resolve();
4503
+ sessionLifecycleHandlers = /* @__PURE__ */ new Set();
4504
+ typedLifecycleHandlers = /* @__PURE__ */ new Map();
4505
+ /**
4506
+ * Creates a new CopilotClient instance.
4507
+ *
4508
+ * @param options - Configuration options for the client
4509
+ * @throws Error if mutually exclusive options are provided (e.g., cliUrl with useStdio or cliPath)
4510
+ *
4511
+ * @example
4512
+ * ```typescript
4513
+ * // Default options - spawns CLI server using stdio
4514
+ * const client = new CopilotClient();
4515
+ *
4516
+ * // Connect to an existing server
4517
+ * const client = new CopilotClient({ cliUrl: "localhost:3000" });
4518
+ *
4519
+ * // Custom CLI path with specific log level
4520
+ * const client = new CopilotClient({
4521
+ * cliPath: "/usr/local/bin/copilot",
4522
+ * logLevel: "debug"
4523
+ * });
4524
+ * ```
4525
+ */
4526
+ constructor(options = {}) {
4527
+ if (options.cliUrl && (options.useStdio === true || options.cliPath)) {
4528
+ throw new Error("cliUrl is mutually exclusive with useStdio and cliPath");
4529
+ }
4530
+ if (options.cliUrl && (options.githubToken || options.useLoggedInUser !== void 0)) {
4531
+ throw new Error(
4532
+ "githubToken and useLoggedInUser cannot be used with cliUrl (external server manages its own auth)"
4533
+ );
4534
+ }
4535
+ if (options.cliUrl) {
4536
+ const { host, port } = this.parseCliUrl(options.cliUrl);
4537
+ this.actualHost = host;
4538
+ this.actualPort = port;
4539
+ this.isExternalServer = true;
4540
+ }
4541
+ this.options = {
4542
+ cliPath: options.cliPath || getBundledCliPath(),
4543
+ cliArgs: options.cliArgs ?? [],
4544
+ cwd: options.cwd ?? process.cwd(),
4545
+ port: options.port || 0,
4546
+ useStdio: options.cliUrl ? false : options.useStdio ?? true,
4547
+ // Default to stdio unless cliUrl is provided
4548
+ cliUrl: options.cliUrl,
4549
+ logLevel: options.logLevel || "debug",
4550
+ autoStart: options.autoStart ?? true,
4551
+ autoRestart: options.autoRestart ?? true,
4552
+ env: options.env ?? process.env,
4553
+ githubToken: options.githubToken,
4554
+ // Default useLoggedInUser to false when githubToken is provided, otherwise true
4555
+ useLoggedInUser: options.useLoggedInUser ?? (options.githubToken ? false : true)
4556
+ };
4557
+ }
4558
+ /**
4559
+ * Parse CLI URL into host and port
4560
+ * Supports formats: "host:port", "http://host:port", "https://host:port", or just "port"
4561
+ */
4562
+ parseCliUrl(url) {
4563
+ let cleanUrl = url.replace(/^https?:\/\//, "");
4564
+ if (/^\d+$/.test(cleanUrl)) {
4565
+ return { host: "localhost", port: parseInt(cleanUrl, 10) };
4566
+ }
4567
+ const parts = cleanUrl.split(":");
4568
+ if (parts.length !== 2) {
4569
+ throw new Error(
4570
+ `Invalid cliUrl format: ${url}. Expected "host:port", "http://host:port", or "port"`
4571
+ );
4572
+ }
4573
+ const host = parts[0] || "localhost";
4574
+ const port = parseInt(parts[1], 10);
4575
+ if (isNaN(port) || port <= 0 || port > 65535) {
4576
+ throw new Error(`Invalid port in cliUrl: ${url}`);
4577
+ }
4578
+ return { host, port };
4579
+ }
4580
+ /**
4581
+ * Starts the CLI server and establishes a connection.
4582
+ *
4583
+ * If connecting to an external server (via cliUrl), only establishes the connection.
4584
+ * Otherwise, spawns the CLI server process and then connects.
4585
+ *
4586
+ * This method is called automatically when creating a session if `autoStart` is true (default).
4587
+ *
4588
+ * @returns A promise that resolves when the connection is established
4589
+ * @throws Error if the server fails to start or the connection fails
4590
+ *
4591
+ * @example
4592
+ * ```typescript
4593
+ * const client = new CopilotClient({ autoStart: false });
4594
+ * await client.start();
4595
+ * // Now ready to create sessions
4596
+ * ```
4597
+ */
4598
+ async start() {
4599
+ if (this.state === "connected") {
4600
+ return;
4601
+ }
4602
+ this.state = "connecting";
4603
+ try {
4604
+ if (!this.isExternalServer) {
4605
+ await this.startCLIServer();
4606
+ }
4607
+ await this.connectToServer();
4608
+ await this.verifyProtocolVersion();
4609
+ this.state = "connected";
4610
+ } catch (error) {
4611
+ this.state = "error";
4612
+ throw error;
4613
+ }
4614
+ }
4615
+ /**
4616
+ * Stops the CLI server and closes all active sessions.
4617
+ *
4618
+ * This method performs graceful cleanup:
4619
+ * 1. Destroys all active sessions with retry logic
4620
+ * 2. Closes the JSON-RPC connection
4621
+ * 3. Terminates the CLI server process (if spawned by this client)
4622
+ *
4623
+ * @returns A promise that resolves with an array of errors encountered during cleanup.
4624
+ * An empty array indicates all cleanup succeeded.
4625
+ *
4626
+ * @example
4627
+ * ```typescript
4628
+ * const errors = await client.stop();
4629
+ * if (errors.length > 0) {
4630
+ * console.error("Cleanup errors:", errors);
4631
+ * }
4632
+ * ```
4633
+ */
4634
+ async stop() {
4635
+ const errors = [];
4636
+ for (const session of this.sessions.values()) {
4637
+ const sessionId = session.sessionId;
4638
+ let lastError = null;
4639
+ for (let attempt = 1; attempt <= 3; attempt++) {
4640
+ try {
4641
+ await session.destroy();
4642
+ lastError = null;
4643
+ break;
4644
+ } catch (error) {
4645
+ lastError = error instanceof Error ? error : new Error(String(error));
4646
+ if (attempt < 3) {
4647
+ const delay = 100 * Math.pow(2, attempt - 1);
4648
+ await new Promise((resolve3) => setTimeout(resolve3, delay));
4649
+ }
4650
+ }
4651
+ }
4652
+ if (lastError) {
4653
+ errors.push(
4654
+ new Error(
4655
+ `Failed to destroy session ${sessionId} after 3 attempts: ${lastError.message}`
4656
+ )
4657
+ );
4658
+ }
4659
+ }
4660
+ this.sessions.clear();
4661
+ if (this.connection) {
4662
+ try {
4663
+ this.connection.dispose();
4664
+ } catch (error) {
4665
+ errors.push(
4666
+ new Error(
4667
+ `Failed to dispose connection: ${error instanceof Error ? error.message : String(error)}`
4668
+ )
4669
+ );
4670
+ }
4671
+ this.connection = null;
4672
+ }
4673
+ this.modelsCache = null;
4674
+ if (this.socket) {
4675
+ try {
4676
+ this.socket.end();
4677
+ } catch (error) {
4678
+ errors.push(
4679
+ new Error(
4680
+ `Failed to close socket: ${error instanceof Error ? error.message : String(error)}`
4681
+ )
4682
+ );
4683
+ }
4684
+ this.socket = null;
4685
+ }
4686
+ if (this.cliProcess && !this.isExternalServer) {
4687
+ try {
4688
+ this.cliProcess.kill();
4689
+ } catch (error) {
4690
+ errors.push(
4691
+ new Error(
4692
+ `Failed to kill CLI process: ${error instanceof Error ? error.message : String(error)}`
4693
+ )
4694
+ );
4695
+ }
4696
+ this.cliProcess = null;
4697
+ }
4698
+ this.state = "disconnected";
4699
+ this.actualPort = null;
4700
+ return errors;
4701
+ }
4702
+ /**
4703
+ * Forcefully stops the CLI server without graceful cleanup.
4704
+ *
4705
+ * Use this when {@link stop} fails or takes too long. This method:
4706
+ * - Clears all sessions immediately without destroying them
4707
+ * - Force closes the connection
4708
+ * - Sends SIGKILL to the CLI process (if spawned by this client)
4709
+ *
4710
+ * @returns A promise that resolves when the force stop is complete
4711
+ *
4712
+ * @example
4713
+ * ```typescript
4714
+ * // If normal stop hangs, force stop
4715
+ * const stopPromise = client.stop();
4716
+ * const timeout = new Promise((_, reject) =>
4717
+ * setTimeout(() => reject(new Error("Timeout")), 5000)
4718
+ * );
4719
+ *
4720
+ * try {
4721
+ * await Promise.race([stopPromise, timeout]);
4722
+ * } catch {
4723
+ * await client.forceStop();
4724
+ * }
4725
+ * ```
4726
+ */
4727
+ async forceStop() {
4728
+ this.forceStopping = true;
4729
+ this.sessions.clear();
4730
+ if (this.connection) {
4731
+ try {
4732
+ this.connection.dispose();
4733
+ } catch {
4734
+ }
4735
+ this.connection = null;
4736
+ }
4737
+ this.modelsCache = null;
4738
+ if (this.socket) {
4739
+ try {
4740
+ this.socket.destroy();
4741
+ } catch {
4742
+ }
4743
+ this.socket = null;
4744
+ }
4745
+ if (this.cliProcess && !this.isExternalServer) {
4746
+ try {
4747
+ this.cliProcess.kill("SIGKILL");
4748
+ } catch {
4749
+ }
4750
+ this.cliProcess = null;
4751
+ }
4752
+ this.state = "disconnected";
4753
+ this.actualPort = null;
4754
+ }
4755
+ /**
4756
+ * Creates a new conversation session with the Copilot CLI.
4757
+ *
4758
+ * Sessions maintain conversation state, handle events, and manage tool execution.
4759
+ * If the client is not connected and `autoStart` is enabled, this will automatically
4760
+ * start the connection.
4761
+ *
4762
+ * @param config - Optional configuration for the session
4763
+ * @returns A promise that resolves with the created session
4764
+ * @throws Error if the client is not connected and autoStart is disabled
4765
+ *
4766
+ * @example
4767
+ * ```typescript
4768
+ * // Basic session
4769
+ * const session = await client.createSession();
4770
+ *
4771
+ * // Session with model and tools
4772
+ * const session = await client.createSession({
4773
+ * model: "gpt-4",
4774
+ * tools: [{
4775
+ * name: "get_weather",
4776
+ * description: "Get weather for a location",
4777
+ * parameters: { type: "object", properties: { location: { type: "string" } } },
4778
+ * handler: async (args) => ({ temperature: 72 })
4779
+ * }]
4780
+ * });
4781
+ * ```
4782
+ */
4783
+ async createSession(config2 = {}) {
4784
+ if (!this.connection) {
4785
+ if (this.options.autoStart) {
4786
+ await this.start();
4787
+ } else {
4788
+ throw new Error("Client not connected. Call start() first.");
4789
+ }
4790
+ }
4791
+ const response = await this.connection.sendRequest("session.create", {
4792
+ model: config2.model,
4793
+ sessionId: config2.sessionId,
4794
+ reasoningEffort: config2.reasoningEffort,
4795
+ tools: config2.tools?.map((tool) => ({
4796
+ name: tool.name,
4797
+ description: tool.description,
4798
+ parameters: toJsonSchema(tool.parameters)
4799
+ })),
4800
+ systemMessage: config2.systemMessage,
4801
+ availableTools: config2.availableTools,
4802
+ excludedTools: config2.excludedTools,
4803
+ provider: config2.provider,
4804
+ requestPermission: !!config2.onPermissionRequest,
4805
+ requestUserInput: !!config2.onUserInputRequest,
4806
+ hooks: !!(config2.hooks && Object.values(config2.hooks).some(Boolean)),
4807
+ workingDirectory: config2.workingDirectory,
4808
+ streaming: config2.streaming,
4809
+ mcpServers: config2.mcpServers,
4810
+ customAgents: config2.customAgents,
4811
+ configDir: config2.configDir,
4812
+ skillDirectories: config2.skillDirectories,
4813
+ disabledSkills: config2.disabledSkills,
4814
+ infiniteSessions: config2.infiniteSessions
4815
+ });
4816
+ const { sessionId, workspacePath } = response;
4817
+ const session = new CopilotSession(sessionId, this.connection, workspacePath);
4818
+ session.registerTools(config2.tools);
4819
+ if (config2.onPermissionRequest) {
4820
+ session.registerPermissionHandler(config2.onPermissionRequest);
4821
+ }
4822
+ if (config2.onUserInputRequest) {
4823
+ session.registerUserInputHandler(config2.onUserInputRequest);
4824
+ }
4825
+ if (config2.hooks) {
4826
+ session.registerHooks(config2.hooks);
4827
+ }
4828
+ this.sessions.set(sessionId, session);
4829
+ return session;
4830
+ }
4831
+ /**
4832
+ * Resumes an existing conversation session by its ID.
4833
+ *
4834
+ * This allows you to continue a previous conversation, maintaining all
4835
+ * conversation history. The session must have been previously created
4836
+ * and not deleted.
4837
+ *
4838
+ * @param sessionId - The ID of the session to resume
4839
+ * @param config - Optional configuration for the resumed session
4840
+ * @returns A promise that resolves with the resumed session
4841
+ * @throws Error if the session does not exist or the client is not connected
4842
+ *
4843
+ * @example
4844
+ * ```typescript
4845
+ * // Resume a previous session
4846
+ * const session = await client.resumeSession("session-123");
4847
+ *
4848
+ * // Resume with new tools
4849
+ * const session = await client.resumeSession("session-123", {
4850
+ * tools: [myNewTool]
4851
+ * });
4852
+ * ```
4853
+ */
4854
+ async resumeSession(sessionId, config2 = {}) {
4855
+ if (!this.connection) {
4856
+ if (this.options.autoStart) {
4857
+ await this.start();
4858
+ } else {
4859
+ throw new Error("Client not connected. Call start() first.");
4860
+ }
4861
+ }
4862
+ const response = await this.connection.sendRequest("session.resume", {
4863
+ sessionId,
4864
+ model: config2.model,
4865
+ reasoningEffort: config2.reasoningEffort,
4866
+ systemMessage: config2.systemMessage,
4867
+ availableTools: config2.availableTools,
4868
+ excludedTools: config2.excludedTools,
4869
+ tools: config2.tools?.map((tool) => ({
4870
+ name: tool.name,
4871
+ description: tool.description,
4872
+ parameters: toJsonSchema(tool.parameters)
4873
+ })),
4874
+ provider: config2.provider,
4875
+ requestPermission: !!config2.onPermissionRequest,
4876
+ requestUserInput: !!config2.onUserInputRequest,
4877
+ hooks: !!(config2.hooks && Object.values(config2.hooks).some(Boolean)),
4878
+ workingDirectory: config2.workingDirectory,
4879
+ configDir: config2.configDir,
4880
+ streaming: config2.streaming,
4881
+ mcpServers: config2.mcpServers,
4882
+ customAgents: config2.customAgents,
4883
+ skillDirectories: config2.skillDirectories,
4884
+ disabledSkills: config2.disabledSkills,
4885
+ infiniteSessions: config2.infiniteSessions,
4886
+ disableResume: config2.disableResume
4887
+ });
4888
+ const { sessionId: resumedSessionId, workspacePath } = response;
4889
+ const session = new CopilotSession(resumedSessionId, this.connection, workspacePath);
4890
+ session.registerTools(config2.tools);
4891
+ if (config2.onPermissionRequest) {
4892
+ session.registerPermissionHandler(config2.onPermissionRequest);
4893
+ }
4894
+ if (config2.onUserInputRequest) {
4895
+ session.registerUserInputHandler(config2.onUserInputRequest);
4896
+ }
4897
+ if (config2.hooks) {
4898
+ session.registerHooks(config2.hooks);
4899
+ }
4900
+ this.sessions.set(resumedSessionId, session);
4901
+ return session;
4902
+ }
4903
+ /**
4904
+ * Gets the current connection state of the client.
4905
+ *
4906
+ * @returns The current connection state: "disconnected", "connecting", "connected", or "error"
4907
+ *
4908
+ * @example
4909
+ * ```typescript
4910
+ * if (client.getState() === "connected") {
4911
+ * const session = await client.createSession();
4912
+ * }
4913
+ * ```
4914
+ */
4915
+ getState() {
4916
+ return this.state;
4917
+ }
4918
+ /**
4919
+ * Sends a ping request to the server to verify connectivity.
4920
+ *
4921
+ * @param message - Optional message to include in the ping
4922
+ * @returns A promise that resolves with the ping response containing the message and timestamp
4923
+ * @throws Error if the client is not connected
4924
+ *
4925
+ * @example
4926
+ * ```typescript
4927
+ * const response = await client.ping("health check");
4928
+ * console.log(`Server responded at ${new Date(response.timestamp)}`);
4929
+ * ```
4930
+ */
4931
+ async ping(message) {
4932
+ if (!this.connection) {
4933
+ throw new Error("Client not connected");
4934
+ }
4935
+ const result = await this.connection.sendRequest("ping", { message });
4936
+ return result;
4937
+ }
4938
+ /**
4939
+ * Get CLI status including version and protocol information
4940
+ */
4941
+ async getStatus() {
4942
+ if (!this.connection) {
4943
+ throw new Error("Client not connected");
4944
+ }
4945
+ const result = await this.connection.sendRequest("status.get", {});
4946
+ return result;
4947
+ }
4948
+ /**
4949
+ * Get current authentication status
4950
+ */
4951
+ async getAuthStatus() {
4952
+ if (!this.connection) {
4953
+ throw new Error("Client not connected");
4954
+ }
4955
+ const result = await this.connection.sendRequest("auth.getStatus", {});
4956
+ return result;
4957
+ }
4958
+ /**
4959
+ * List available models with their metadata.
4960
+ *
4961
+ * Results are cached after the first successful call to avoid rate limiting.
4962
+ * The cache is cleared when the client disconnects.
4963
+ *
4964
+ * @throws Error if not authenticated
4965
+ */
4966
+ async listModels() {
4967
+ if (!this.connection) {
4968
+ throw new Error("Client not connected");
4969
+ }
4970
+ await this.modelsCacheLock;
4971
+ let resolveLock;
4972
+ this.modelsCacheLock = new Promise((resolve3) => {
4973
+ resolveLock = resolve3;
4974
+ });
4975
+ try {
4976
+ if (this.modelsCache !== null) {
4977
+ return [...this.modelsCache];
4978
+ }
4979
+ const result = await this.connection.sendRequest("models.list", {});
4980
+ const response = result;
4981
+ const models = response.models;
4982
+ this.modelsCache = models;
4983
+ return [...models];
4984
+ } finally {
4985
+ resolveLock();
4986
+ }
4987
+ }
4988
+ /**
4989
+ * Verify that the server's protocol version matches the SDK's expected version
4990
+ */
4991
+ async verifyProtocolVersion() {
4992
+ const expectedVersion = getSdkProtocolVersion();
4993
+ const pingResult = await this.ping();
4994
+ const serverVersion = pingResult.protocolVersion;
4995
+ if (serverVersion === void 0) {
4996
+ throw new Error(
4997
+ `SDK protocol version mismatch: SDK expects version ${expectedVersion}, but server does not report a protocol version. Please update your server to ensure compatibility.`
4998
+ );
4999
+ }
5000
+ if (serverVersion !== expectedVersion) {
5001
+ throw new Error(
5002
+ `SDK protocol version mismatch: SDK expects version ${expectedVersion}, but server reports version ${serverVersion}. Please update your SDK or server to ensure compatibility.`
5003
+ );
5004
+ }
5005
+ }
5006
+ /**
5007
+ * Gets the ID of the most recently updated session.
5008
+ *
5009
+ * This is useful for resuming the last conversation when the session ID
5010
+ * was not stored.
5011
+ *
5012
+ * @returns A promise that resolves with the session ID, or undefined if no sessions exist
5013
+ * @throws Error if the client is not connected
5014
+ *
5015
+ * @example
5016
+ * ```typescript
5017
+ * const lastId = await client.getLastSessionId();
5018
+ * if (lastId) {
5019
+ * const session = await client.resumeSession(lastId);
5020
+ * }
5021
+ * ```
5022
+ */
5023
+ async getLastSessionId() {
5024
+ if (!this.connection) {
5025
+ throw new Error("Client not connected");
5026
+ }
5027
+ const response = await this.connection.sendRequest("session.getLastId", {});
5028
+ return response.sessionId;
5029
+ }
5030
+ /**
5031
+ * Deletes a session and its data from disk.
5032
+ *
5033
+ * This permanently removes the session and all its conversation history.
5034
+ * The session cannot be resumed after deletion.
5035
+ *
5036
+ * @param sessionId - The ID of the session to delete
5037
+ * @returns A promise that resolves when the session is deleted
5038
+ * @throws Error if the session does not exist or deletion fails
5039
+ *
5040
+ * @example
5041
+ * ```typescript
5042
+ * await client.deleteSession("session-123");
5043
+ * ```
5044
+ */
5045
+ async deleteSession(sessionId) {
5046
+ if (!this.connection) {
5047
+ throw new Error("Client not connected");
5048
+ }
5049
+ const response = await this.connection.sendRequest("session.delete", {
5050
+ sessionId
5051
+ });
5052
+ const { success, error } = response;
5053
+ if (!success) {
5054
+ throw new Error(`Failed to delete session ${sessionId}: ${error || "Unknown error"}`);
5055
+ }
5056
+ this.sessions.delete(sessionId);
5057
+ }
5058
+ /**
5059
+ * Lists all available sessions known to the server.
5060
+ *
5061
+ * Returns metadata about each session including ID, timestamps, and summary.
5062
+ *
5063
+ * @returns A promise that resolves with an array of session metadata
5064
+ * @throws Error if the client is not connected
5065
+ *
5066
+ * @example
5067
+ * ```typescript
5068
+ * const sessions = await client.listSessions();
5069
+ * for (const session of sessions) {
5070
+ * console.log(`${session.sessionId}: ${session.summary}`);
5071
+ * }
5072
+ * ```
5073
+ */
5074
+ async listSessions() {
5075
+ if (!this.connection) {
5076
+ throw new Error("Client not connected");
5077
+ }
5078
+ const response = await this.connection.sendRequest("session.list", {});
5079
+ const { sessions } = response;
5080
+ return sessions.map((s) => ({
5081
+ sessionId: s.sessionId,
5082
+ startTime: new Date(s.startTime),
5083
+ modifiedTime: new Date(s.modifiedTime),
5084
+ summary: s.summary,
5085
+ isRemote: s.isRemote
5086
+ }));
5087
+ }
5088
+ /**
5089
+ * Gets the foreground session ID in TUI+server mode.
5090
+ *
5091
+ * This returns the ID of the session currently displayed in the TUI.
5092
+ * Only available when connecting to a server running in TUI+server mode (--ui-server).
5093
+ *
5094
+ * @returns A promise that resolves with the foreground session ID, or undefined if none
5095
+ * @throws Error if the client is not connected
5096
+ *
5097
+ * @example
5098
+ * ```typescript
5099
+ * const sessionId = await client.getForegroundSessionId();
5100
+ * if (sessionId) {
5101
+ * console.log(`TUI is displaying session: ${sessionId}`);
5102
+ * }
5103
+ * ```
5104
+ */
5105
+ async getForegroundSessionId() {
5106
+ if (!this.connection) {
5107
+ throw new Error("Client not connected");
5108
+ }
5109
+ const response = await this.connection.sendRequest("session.getForeground", {});
5110
+ return response.sessionId;
5111
+ }
5112
+ /**
5113
+ * Sets the foreground session in TUI+server mode.
5114
+ *
5115
+ * This requests the TUI to switch to displaying the specified session.
5116
+ * Only available when connecting to a server running in TUI+server mode (--ui-server).
5117
+ *
5118
+ * @param sessionId - The ID of the session to display in the TUI
5119
+ * @returns A promise that resolves when the session is switched
5120
+ * @throws Error if the client is not connected or if the operation fails
5121
+ *
5122
+ * @example
5123
+ * ```typescript
5124
+ * // Switch the TUI to display a specific session
5125
+ * await client.setForegroundSessionId("session-123");
5126
+ * ```
5127
+ */
5128
+ async setForegroundSessionId(sessionId) {
5129
+ if (!this.connection) {
5130
+ throw new Error("Client not connected");
5131
+ }
5132
+ const response = await this.connection.sendRequest("session.setForeground", { sessionId });
5133
+ const result = response;
5134
+ if (!result.success) {
5135
+ throw new Error(result.error || "Failed to set foreground session");
5136
+ }
5137
+ }
5138
+ on(eventTypeOrHandler, handler) {
5139
+ if (typeof eventTypeOrHandler === "string" && handler) {
5140
+ const eventType = eventTypeOrHandler;
5141
+ if (!this.typedLifecycleHandlers.has(eventType)) {
5142
+ this.typedLifecycleHandlers.set(eventType, /* @__PURE__ */ new Set());
5143
+ }
5144
+ const storedHandler = handler;
5145
+ this.typedLifecycleHandlers.get(eventType).add(storedHandler);
5146
+ return () => {
5147
+ const handlers = this.typedLifecycleHandlers.get(eventType);
5148
+ if (handlers) {
5149
+ handlers.delete(storedHandler);
5150
+ }
5151
+ };
5152
+ }
5153
+ const wildcardHandler = eventTypeOrHandler;
5154
+ this.sessionLifecycleHandlers.add(wildcardHandler);
5155
+ return () => {
5156
+ this.sessionLifecycleHandlers.delete(wildcardHandler);
5157
+ };
5158
+ }
5159
+ /**
5160
+ * Start the CLI server process
5161
+ */
5162
+ async startCLIServer() {
5163
+ return new Promise((resolve3, reject) => {
5164
+ const args = [
5165
+ ...this.options.cliArgs,
5166
+ "--headless",
5167
+ "--no-auto-update",
5168
+ "--log-level",
5169
+ this.options.logLevel
5170
+ ];
5171
+ if (this.options.useStdio) {
5172
+ args.push("--stdio");
5173
+ } else if (this.options.port > 0) {
5174
+ args.push("--port", this.options.port.toString());
5175
+ }
5176
+ if (this.options.githubToken) {
5177
+ args.push("--auth-token-env", "COPILOT_SDK_AUTH_TOKEN");
5178
+ }
5179
+ if (!this.options.useLoggedInUser) {
5180
+ args.push("--no-auto-login");
5181
+ }
5182
+ const envWithoutNodeDebug = { ...this.options.env };
5183
+ delete envWithoutNodeDebug.NODE_DEBUG;
5184
+ if (this.options.githubToken) {
5185
+ envWithoutNodeDebug.COPILOT_SDK_AUTH_TOKEN = this.options.githubToken;
5186
+ }
5187
+ if (!existsSync4(this.options.cliPath)) {
5188
+ throw new Error(
5189
+ `Copilot CLI not found at ${this.options.cliPath}. Ensure @github/copilot is installed.`
5190
+ );
5191
+ }
5192
+ const stdioConfig = this.options.useStdio ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"];
5193
+ const isJsFile = this.options.cliPath.endsWith(".js");
5194
+ if (isJsFile) {
5195
+ this.cliProcess = spawn(process.execPath, [this.options.cliPath, ...args], {
5196
+ stdio: stdioConfig,
5197
+ cwd: this.options.cwd,
5198
+ env: envWithoutNodeDebug
5199
+ });
5200
+ } else {
5201
+ this.cliProcess = spawn(this.options.cliPath, args, {
5202
+ stdio: stdioConfig,
5203
+ cwd: this.options.cwd,
5204
+ env: envWithoutNodeDebug
5205
+ });
5206
+ }
5207
+ let stdout = "";
5208
+ let resolved = false;
5209
+ if (this.options.useStdio) {
5210
+ resolved = true;
5211
+ resolve3();
5212
+ } else {
5213
+ this.cliProcess.stdout?.on("data", (data) => {
5214
+ stdout += data.toString();
5215
+ const match = stdout.match(/listening on port (\d+)/i);
5216
+ if (match && !resolved) {
5217
+ this.actualPort = parseInt(match[1], 10);
5218
+ resolved = true;
5219
+ resolve3();
5220
+ }
5221
+ });
5222
+ }
5223
+ this.cliProcess.stderr?.on("data", (data) => {
5224
+ const lines = data.toString().split("\n");
5225
+ for (const line of lines) {
5226
+ if (line.trim()) {
5227
+ process.stderr.write(`[CLI subprocess] ${line}
5228
+ `);
5229
+ }
5230
+ }
5231
+ });
5232
+ this.cliProcess.on("error", (error) => {
5233
+ if (!resolved) {
5234
+ resolved = true;
5235
+ reject(new Error(`Failed to start CLI server: ${error.message}`));
5236
+ }
5237
+ });
5238
+ this.cliProcess.on("exit", (code) => {
5239
+ if (!resolved) {
5240
+ resolved = true;
5241
+ reject(new Error(`CLI server exited with code ${code}`));
5242
+ } else if (this.options.autoRestart && this.state === "connected") {
5243
+ void this.reconnect();
5244
+ }
5245
+ });
5246
+ setTimeout(() => {
5247
+ if (!resolved) {
5248
+ resolved = true;
5249
+ reject(new Error("Timeout waiting for CLI server to start"));
5250
+ }
5251
+ }, 1e4);
5252
+ });
5253
+ }
5254
+ /**
5255
+ * Connect to the CLI server (via socket or stdio)
5256
+ */
5257
+ async connectToServer() {
5258
+ if (this.options.useStdio) {
5259
+ return this.connectViaStdio();
5260
+ } else {
5261
+ return this.connectViaTcp();
5262
+ }
5263
+ }
5264
+ /**
5265
+ * Connect via stdio pipes
5266
+ */
5267
+ async connectViaStdio() {
5268
+ if (!this.cliProcess) {
5269
+ throw new Error("CLI process not started");
5270
+ }
5271
+ this.cliProcess.stdin?.on("error", (err) => {
5272
+ if (!this.forceStopping) {
5273
+ throw err;
5274
+ }
5275
+ });
5276
+ this.connection = (0, import_node.createMessageConnection)(
5277
+ new import_node.StreamMessageReader(this.cliProcess.stdout),
5278
+ new import_node.StreamMessageWriter(this.cliProcess.stdin)
5279
+ );
5280
+ this.attachConnectionHandlers();
5281
+ this.connection.listen();
5282
+ }
5283
+ /**
5284
+ * Connect to the CLI server via TCP socket
5285
+ */
5286
+ async connectViaTcp() {
5287
+ if (!this.actualPort) {
5288
+ throw new Error("Server port not available");
5289
+ }
5290
+ return new Promise((resolve3, reject) => {
5291
+ this.socket = new Socket();
5292
+ this.socket.connect(this.actualPort, this.actualHost, () => {
5293
+ this.connection = (0, import_node.createMessageConnection)(
5294
+ new import_node.StreamMessageReader(this.socket),
5295
+ new import_node.StreamMessageWriter(this.socket)
5296
+ );
5297
+ this.attachConnectionHandlers();
5298
+ this.connection.listen();
5299
+ resolve3();
5300
+ });
5301
+ this.socket.on("error", (error) => {
5302
+ reject(new Error(`Failed to connect to CLI server: ${error.message}`));
5303
+ });
5304
+ });
5305
+ }
5306
+ attachConnectionHandlers() {
5307
+ if (!this.connection) {
5308
+ return;
5309
+ }
5310
+ this.connection.onNotification("session.event", (notification) => {
5311
+ this.handleSessionEventNotification(notification);
5312
+ });
5313
+ this.connection.onNotification("session.lifecycle", (notification) => {
5314
+ this.handleSessionLifecycleNotification(notification);
5315
+ });
5316
+ this.connection.onRequest(
5317
+ "tool.call",
5318
+ async (params) => await this.handleToolCallRequest(params)
5319
+ );
5320
+ this.connection.onRequest(
5321
+ "permission.request",
5322
+ async (params) => await this.handlePermissionRequest(params)
5323
+ );
5324
+ this.connection.onRequest(
5325
+ "userInput.request",
5326
+ async (params) => await this.handleUserInputRequest(params)
5327
+ );
5328
+ this.connection.onRequest(
5329
+ "hooks.invoke",
5330
+ async (params) => await this.handleHooksInvoke(params)
5331
+ );
5332
+ this.connection.onClose(() => {
5333
+ if (this.state === "connected" && this.options.autoRestart) {
5334
+ void this.reconnect();
5335
+ }
5336
+ });
5337
+ this.connection.onError((_error) => {
5338
+ });
5339
+ }
5340
+ handleSessionEventNotification(notification) {
5341
+ if (typeof notification !== "object" || !notification || !("sessionId" in notification) || typeof notification.sessionId !== "string" || !("event" in notification)) {
5342
+ return;
5343
+ }
5344
+ const session = this.sessions.get(notification.sessionId);
5345
+ if (session) {
5346
+ session._dispatchEvent(notification.event);
5347
+ }
5348
+ }
5349
+ handleSessionLifecycleNotification(notification) {
5350
+ if (typeof notification !== "object" || !notification || !("type" in notification) || typeof notification.type !== "string" || !("sessionId" in notification) || typeof notification.sessionId !== "string") {
5351
+ return;
5352
+ }
5353
+ const event = notification;
5354
+ const typedHandlers = this.typedLifecycleHandlers.get(event.type);
5355
+ if (typedHandlers) {
5356
+ for (const handler of typedHandlers) {
5357
+ try {
5358
+ handler(event);
5359
+ } catch {
5360
+ }
5361
+ }
5362
+ }
5363
+ for (const handler of this.sessionLifecycleHandlers) {
5364
+ try {
5365
+ handler(event);
5366
+ } catch {
5367
+ }
5368
+ }
5369
+ }
5370
+ async handleToolCallRequest(params) {
5371
+ if (!params || typeof params.sessionId !== "string" || typeof params.toolCallId !== "string" || typeof params.toolName !== "string") {
5372
+ throw new Error("Invalid tool call payload");
5373
+ }
5374
+ const session = this.sessions.get(params.sessionId);
5375
+ if (!session) {
5376
+ throw new Error(`Unknown session ${params.sessionId}`);
5377
+ }
5378
+ const handler = session.getToolHandler(params.toolName);
5379
+ if (!handler) {
5380
+ return { result: this.buildUnsupportedToolResult(params.toolName) };
5381
+ }
5382
+ return await this.executeToolCall(handler, params);
5383
+ }
5384
+ async executeToolCall(handler, request) {
5385
+ try {
5386
+ const invocation = {
5387
+ sessionId: request.sessionId,
5388
+ toolCallId: request.toolCallId,
5389
+ toolName: request.toolName,
5390
+ arguments: request.arguments
5391
+ };
5392
+ const result = await handler(request.arguments, invocation);
5393
+ return { result: this.normalizeToolResult(result) };
5394
+ } catch (error) {
5395
+ const message = error instanceof Error ? error.message : String(error);
5396
+ return {
5397
+ result: {
5398
+ // Don't expose detailed error information to the LLM for security reasons
5399
+ textResultForLlm: "Invoking this tool produced an error. Detailed information is not available.",
5400
+ resultType: "failure",
5401
+ error: message,
5402
+ toolTelemetry: {}
5403
+ }
5404
+ };
5405
+ }
5406
+ }
5407
+ async handlePermissionRequest(params) {
5408
+ if (!params || typeof params.sessionId !== "string" || !params.permissionRequest) {
5409
+ throw new Error("Invalid permission request payload");
5410
+ }
5411
+ const session = this.sessions.get(params.sessionId);
5412
+ if (!session) {
5413
+ throw new Error(`Session not found: ${params.sessionId}`);
5414
+ }
5415
+ try {
5416
+ const result = await session._handlePermissionRequest(params.permissionRequest);
5417
+ return { result };
5418
+ } catch (_error) {
5419
+ return {
5420
+ result: {
5421
+ kind: "denied-no-approval-rule-and-could-not-request-from-user"
5422
+ }
5423
+ };
5424
+ }
5425
+ }
5426
+ async handleUserInputRequest(params) {
5427
+ if (!params || typeof params.sessionId !== "string" || typeof params.question !== "string") {
5428
+ throw new Error("Invalid user input request payload");
5429
+ }
5430
+ const session = this.sessions.get(params.sessionId);
5431
+ if (!session) {
5432
+ throw new Error(`Session not found: ${params.sessionId}`);
5433
+ }
5434
+ const result = await session._handleUserInputRequest({
5435
+ question: params.question,
5436
+ choices: params.choices,
5437
+ allowFreeform: params.allowFreeform
5438
+ });
5439
+ return result;
5440
+ }
5441
+ async handleHooksInvoke(params) {
5442
+ if (!params || typeof params.sessionId !== "string" || typeof params.hookType !== "string") {
5443
+ throw new Error("Invalid hooks invoke payload");
5444
+ }
5445
+ const session = this.sessions.get(params.sessionId);
5446
+ if (!session) {
5447
+ throw new Error(`Session not found: ${params.sessionId}`);
5448
+ }
5449
+ const output = await session._handleHooksInvoke(params.hookType, params.input);
5450
+ return { output };
5451
+ }
5452
+ normalizeToolResult(result) {
5453
+ if (result === void 0 || result === null) {
5454
+ return {
5455
+ textResultForLlm: "Tool returned no result",
5456
+ resultType: "failure",
5457
+ error: "tool returned no result",
5458
+ toolTelemetry: {}
5459
+ };
5460
+ }
5461
+ if (this.isToolResultObject(result)) {
5462
+ return result;
5463
+ }
5464
+ const textResult = typeof result === "string" ? result : JSON.stringify(result);
5465
+ return {
5466
+ textResultForLlm: textResult,
5467
+ resultType: "success",
5468
+ toolTelemetry: {}
5469
+ };
5470
+ }
5471
+ isToolResultObject(value) {
5472
+ return typeof value === "object" && value !== null && "textResultForLlm" in value && typeof value.textResultForLlm === "string" && "resultType" in value;
5473
+ }
5474
+ buildUnsupportedToolResult(toolName) {
5475
+ return {
5476
+ textResultForLlm: `Tool '${toolName}' is not supported by this client instance.`,
5477
+ resultType: "failure",
5478
+ error: `tool '${toolName}' not supported`,
5479
+ toolTelemetry: {}
5480
+ };
5481
+ }
5482
+ /**
5483
+ * Attempt to reconnect to the server
5484
+ */
5485
+ async reconnect() {
5486
+ this.state = "disconnected";
5487
+ try {
5488
+ await this.stop();
5489
+ await this.start();
5490
+ } catch (_error) {
5491
+ }
5492
+ }
5493
+ };
5494
+ }
5495
+ });
5496
+
5497
+ // node_modules/@github/copilot-sdk/dist/types.js
5498
+ var init_types2 = __esm({
5499
+ "node_modules/@github/copilot-sdk/dist/types.js"() {
5500
+ "use strict";
5501
+ }
5502
+ });
5503
+
5504
+ // node_modules/@github/copilot-sdk/dist/index.js
5505
+ var init_dist = __esm({
5506
+ "node_modules/@github/copilot-sdk/dist/index.js"() {
5507
+ "use strict";
5508
+ init_client();
5509
+ init_session();
5510
+ init_types2();
5511
+ }
5512
+ });
5513
+
781
5514
  // src/L1-infra/ai/copilot.ts
782
- import { CopilotClient, CopilotSession } from "@github/copilot-sdk";
783
5515
  var init_copilot = __esm({
784
5516
  "src/L1-infra/ai/copilot.ts"() {
785
5517
  "use strict";
5518
+ init_dist();
786
5519
  }
787
5520
  });
788
5521