@sourcegraph/cody-web 0.7.4 → 0.7.7

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.
@@ -18,7 +18,7 @@ var __privateWrapper = (obj, member, setter2, getter) => ({
18
18
  }
19
19
  });
20
20
  var _a2, _b, _constructing, _max, _maxSize, _dispose, _disposeAfter, _fetchMethod, _size, _calculatedSize, _keyMap, _keyList, _valList, _next, _prev, _head, _tail, _free, _disposed, _sizes, _starts, _ttls, _hasDispose, _hasFetchMethod, _hasDisposeAfter, _LRUCache_instances, initializeTTLTracking_fn, _updateItemAge, _statusTTL, _setItemTTL, _isStale, initializeSizeTracking_fn, _removeItemSize, _addItemSize, _requireSize, indexes_fn, rindexes_fn, isValidIndex_fn, evict_fn, backgroundFetch_fn, isBackgroundFetch_fn, connect_fn, moveToTail_fn, _c, _d, _e, _constructing2, _f, _g, _max2, _maxSize2, _dispose2, _disposeAfter2, _fetchMethod2, _size2, _calculatedSize2, _keyMap2, _keyList2, _valList2, _next2, _prev2, _head2, _tail2, _free2, _disposed2, _sizes2, _starts2, _ttls2, _hasDispose2, _hasFetchMethod2, _hasDisposeAfter2, _LRUCache_instances2, initializeTTLTracking_fn2, _updateItemAge2, _statusTTL2, _setItemTTL2, _isStale2, initializeSizeTracking_fn2, _removeItemSize2, _addItemSize2, _requireSize2, indexes_fn2, rindexes_fn2, isValidIndex_fn2, evict_fn2, backgroundFetch_fn2, isBackgroundFetch_fn2, connect_fn2, moveToTail_fn2, _root2, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _AST_instances, fillNegs_fn, _AST_static, parseAST_fn, partsToRegExp_fn, parseGlob_fn, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
21
- import { bz as createSubscriber, bA as graphqlClient, bB as logError$2, aV as lodashExports, bC as logDebug$1, bD as isFileURI, w as wrapInActiveSpan, bE as INCLUDE_EVERYTHING_CONTEXT_FILTERS, bF as EXCLUDE_EVERYTHING_CONTEXT_FILTERS, bG as isAbortError, b8 as isError$1, bb as isDefined, bH as onAbort, bI as CHAT_OUTPUT_TOKEN_BUDGET, bk as ModelTag, b3 as CodyIDE, bJ as isEnterpriseUser, b2 as isCodyProUser, bs as CHAT_INPUT_TOKEN_BUDGET, bK as getModelInfo, bL as EXTENDED_CHAT_INPUT_TOKEN_BUDGET, bM as EXTENDED_USER_CONTEXT_TOKEN_BUDGET, g as getDefaultExportFromCjs, bN as pathFunctionsForURI, bO as uriBasename, bP as uriHasPrefix, bQ as isWindows, aL as URI, bR as Utils$1, p as ps, bS as Observable, b5 as commonjsGlobal, bT as fromVSCodeEvent, bU as ClientConfigSingleton, by as PromptString, bV as isCustomModel, bW as recordErrorToSpan, bX as dependentAbortController, bY as addCustomUserAgent, bZ as addTraceparent, b_ as fetch$2, b$ as verifyResponseCode, b7 as cryptoJsExports, c0 as openCtx, c1 as extensionForLanguage, c2 as isSourcegraphToken, c3 as _, c4 as toRangeData, c5 as DOTCOM_URL, c6 as requireBase64Js, c7 as isDotCom, c8 as NetworkError, c9 as isRateLimitError, ca as isAuthError, cb as offlineModeAuthStatus, cc as unauthenticatedStatus, cd as semver, t as telemetryRecorder, ce as defaultAuthStatus, bt as ACCOUNT_USAGE_URL, cf as SourcegraphGraphQLAPIClient, cg as networkErrorAuthStatus, ch as NoOpTelemetryRecorderProvider, ci as TimestampTelemetryProcessor_1, cj as updateGlobalTelemetryInstances, ck as TelemetryRecorderProvider, cl as telemetryRecorderProvider, cm as convertGitCloneURLToCodebaseName, cn as subscriptionDisposable, d as dedent$1, co as uriExtname, cp as SUPPORTED_URI_SCHEMAS, cq as require$$1$4, cr as dedupeWith$1, cs as getEditorInsertSpaces, ct as TimeoutError, cu as getActiveTraceAndSpanId, cv as isNetworkError$1, cw as trace, bj as isCodyProModel, b6 as CodyTaskState, be as isEqual, cx as getAugmentedNamespace, cy as main$1, cz as setUserAgent, cA as TESTING_TELEMETRY_EXPORTER, cB as dist, bm as isMacOS, bl as CustomCommandType, bx as setDisplayPathEnvInfo, T as TokenCounterUtils, C as ContextItemSource, cC as _root, cD as _baseGetTag, cE as isObjectLike_1, cF as isObject_1, bw as isErrorLike, au as displayPath, cG as DefaultChatCommands, cH as uriParseNameAndExtension, cI as uriDirname, cJ as DefaultEditCommands, an as FILE_CONTEXT_MENTION_PROVIDER, ao as SYMBOL_CONTEXT_MENTION_PROVIDER, ap as REMOTE_REPOSITORY_PROVIDER_URI, cK as promiseFactoryToObservable, cL as webMentionProvidersMetadata, cM as allMentionProvidersMetadata, cN as combineLatest$1, cO as expandToLineRange, am as displayPathBasename, av as displayLineRange, cP as truncateTextNearestLine, cQ as TokenCounter, bq as View, aQ as parseMentionQuery, cR as tracer, bd as isAbortErrorOrSocketHangUp, cS as isContextWindowLimitError, cT as truncatePromptString, cU as inputTextWithoutContextChipsFromPromptEditorState, bc as reformatBotMessageForChat, b1 as hydrateAfterPostMessage, cV as addMessageListenersForExtensionAPI, cW as createMessageAPIForExtension, cX as CODY_PASSTHROUGH_VSCODE_OPEN_COMMAND_ID, cY as editorStateFromPromptString, cZ as getEditorTabSize$1, bi as pluralize, c_ as AbortError, c$ as getEditorIndentString, b9 as RateLimitError$1, d0 as logResponseHeadersToSpan, d1 as TracedError, d2 as isNodeResponse, d3 as SpanStatusCode, aq as REMOTE_FILE_PROVIDER_URI, as as CURRENT_REPOSITORY_DIRECTORY_PROVIDER_URI, d4 as assertFileURI, ar as REMOTE_DIRECTORY_PROVIDER_URI, at as WEB_PROVIDER_URI, d5 as setOpenCtx, d6 as GIT_OPENCTX_PROVIDER_URI, d7 as ACCOUNT_UPGRADE_URL, aZ as scanForMentionTriggerInUserTextInput, ay as LARGE_FILE_WARNING_LABEL, d8 as GENERAL_HELP_LABEL, d9 as diffLines, da as psDedent, db as languageFromFilename, dc as ProgrammingLanguage, dd as truncatePromptStringStart, de as posixFilePaths, df as CODY_DOC_URL, ba as CODY_FEEDBACK_URL, dg as DISCORD_URL, dh as CODY_SUPPORT_URL, bu as getRelativeChatPeriod, di as SG_BLOG_URL, dj as ACCOUNT_LIMITS_INFO_URL, dk as setLogger, dl as CODY_OLLAMA_DOCS_URL, bv as browser$3 } from "./browser-BTzYzFoB.mjs";
21
+ import { by as Observable, bz as unsubscribe, bA as createSubscriber, bB as graphqlClient, bC as logError$2, aU as lodashExports, bD as logDebug$1, bE as isFileURI, w as wrapInActiveSpan, bF as INCLUDE_EVERYTHING_CONTEXT_FILTERS, bG as isDotCom, bH as EXCLUDE_EVERYTHING_CONTEXT_FILTERS, bI as isAbortError, b7 as isError$1, ba as isDefined, bJ as onAbort, bK as CHAT_OUTPUT_TOKEN_BUDGET, bj as ModelTag, b2 as CodyIDE, bL as isEnterpriseUser, b1 as isCodyProUser, br as CHAT_INPUT_TOKEN_BUDGET, bM as getModelInfo, bN as EXTENDED_CHAT_INPUT_TOKEN_BUDGET, bO as EXTENDED_USER_CONTEXT_TOKEN_BUDGET, g as getDefaultExportFromCjs, bP as pathFunctionsForURI, bQ as uriBasename, bR as uriHasPrefix, bS as isWindows, aK as URI, bT as Utils$1, p as ps, bU as fromVSCodeEvent, bV as ClientConfigSingleton, bx as PromptString, bW as isCustomModel, bX as recordErrorToSpan, bY as dependentAbortController, bZ as addCustomUserAgent, b_ as addTraceparent, b$ as fetch$2, c0 as verifyResponseCode, b6 as cryptoJsExports, c1 as openCtx, c2 as AsyncSerialScheduler_1, c3 as extensionForLanguage, c4 as isSourcegraphToken, c5 as _, c6 as toRangeData, c7 as DOTCOM_URL, c8 as base64Js, b4 as commonjsGlobal, c9 as NetworkError, ca as isRateLimitError, cb as isAuthError, t as telemetryRecorder, cc as semver, cd as NO_INITIAL_VALUE, ce as distinctUntilChanged$1, cf as SourcegraphGraphQLAPIClient, cg as isNetworkLikeError, ch as NoOpTelemetryRecorderProvider, ci as TimestampTelemetryProcessor_1, cj as updateGlobalTelemetryInstances, ck as TelemetryRecorderProvider, cl as telemetryRecorderProvider, cm as convertGitCloneURLToCodebaseName, cn as subscriptionDisposable, d as dedent$1, co as uriExtname, cp as SUPPORTED_URI_SCHEMAS, cq as require$$1$4, cr as dedupeWith$1, cs as getEditorInsertSpaces, ct as TimeoutError, cu as getActiveTraceAndSpanId, cv as isNetworkError, cw as trace, bi as isCodyProModel, b5 as CodyTaskState, aS as createExtensionAPI, aT as createMessageAPIForWebview, bd as isEqual, cx as getAugmentedNamespace, cy as main$1, cz as setUserAgent, cA as TESTING_TELEMETRY_EXPORTER, cB as dist, cC as waitUntilComplete, bl as isMacOS, bk as CustomCommandType, bw as setDisplayPathEnvInfo, bs as ACCOUNT_USAGE_URL, T as TokenCounterUtils, C as ContextItemSource, cD as _root, cE as _baseGetTag, cF as isObjectLike_1, cG as isObject_1, bv as isErrorLike, at as displayPath, cH as DefaultChatCommands, cI as uriParseNameAndExtension, cJ as uriDirname, cK as DefaultEditCommands, an as FILE_CONTEXT_MENTION_PROVIDER, ao as SYMBOL_CONTEXT_MENTION_PROVIDER, ap as REMOTE_REPOSITORY_PROVIDER_URI, cL as promiseFactoryToObservable, cM as webMentionProvidersMetadata, cN as allMentionProvidersMetadata, cO as combineLatest$1, cP as expandToLineRange, am as displayPathBasename, au as displayLineRange, cQ as truncateTextNearestLine, cR as TokenCounter, bp as View, aP as parseMentionQuery, cS as tracer, bc as isAbortErrorOrSocketHangUp, cT as isContextWindowLimitError, cU as truncatePromptString, cV as inputTextWithoutContextChipsFromPromptEditorState, bb as reformatBotMessageForChat, b0 as hydrateAfterPostMessage, cW as addMessageListenersForExtensionAPI, cX as createMessageAPIForExtension, cY as startWith$1, cZ as promiseToObservable$1, c_ as CODY_PASSTHROUGH_VSCODE_OPEN_COMMAND_ID, c$ as editorStateFromPromptString, d0 as getEditorTabSize$1, bh as pluralize, d1 as AbortError, d2 as psDedent, d3 as getEditorIndentString, b8 as RateLimitError$1, d4 as logResponseHeadersToSpan, d5 as TracedError, d6 as isNodeResponse, d7 as SpanStatusCode, d8 as assertFileURI, aq as REMOTE_FILE_PROVIDER_URI, ar as REMOTE_DIRECTORY_PROVIDER_URI, as as WEB_PROVIDER_URI, d9 as setOpenCtx, da as GIT_OPENCTX_PROVIDER_URI, db as ACCOUNT_UPGRADE_URL, aY as scanForMentionTriggerInUserTextInput, ax as LARGE_FILE_WARNING_LABEL, dc as GENERAL_HELP_LABEL, dd as diffLines, de as languageFromFilename, df as ProgrammingLanguage, dg as truncatePromptStringStart, dh as posixFilePaths, di as CODY_DOC_URL, b9 as CODY_FEEDBACK_URL, dj as DISCORD_URL, dk as CODY_SUPPORT_URL, bt as getRelativeChatPeriod, dl as SG_BLOG_URL, dm as ACCOUNT_LIMITS_INFO_URL, dn as setLogger, dp as CODY_OLLAMA_DOCS_URL, bu as browser$3 } from "./browser-hDxNMh5y.mjs";
22
22
  function _mergeNamespaces(n, m) {
23
23
  for (var i = 0; i < m.length; i++) {
24
24
  const e = m[i];
@@ -38,6 +38,185 @@ function _mergeNamespaces(n, m) {
38
38
  }
39
39
  return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: "Module" }));
40
40
  }
41
+ var __awaiter$2 = function(thisArg, _arguments, P, generator) {
42
+ function adopt(value) {
43
+ return value instanceof P ? value : new P(function(resolve2) {
44
+ resolve2(value);
45
+ });
46
+ }
47
+ return new (P || (P = Promise))(function(resolve2, reject) {
48
+ function fulfilled(value) {
49
+ try {
50
+ step6(generator.next(value));
51
+ } catch (e) {
52
+ reject(e);
53
+ }
54
+ }
55
+ function rejected(value) {
56
+ try {
57
+ step6(generator["throw"](value));
58
+ } catch (e) {
59
+ reject(e);
60
+ }
61
+ }
62
+ function step6(result) {
63
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
64
+ }
65
+ step6((generator = generator.apply(thisArg, _arguments || [])).next());
66
+ });
67
+ };
68
+ class AsyncSerialScheduler {
69
+ constructor(observer) {
70
+ this._baseObserver = observer;
71
+ this._pendingPromises = /* @__PURE__ */ new Set();
72
+ }
73
+ complete() {
74
+ Promise.all(this._pendingPromises).then(() => this._baseObserver.complete()).catch((error) => this._baseObserver.error(error));
75
+ }
76
+ error(error) {
77
+ this._baseObserver.error(error);
78
+ }
79
+ schedule(task) {
80
+ const prevPromisesCompletion = Promise.all(this._pendingPromises);
81
+ const values = [];
82
+ const next = (value) => values.push(value);
83
+ const promise = Promise.resolve().then(() => __awaiter$2(this, void 0, void 0, function* () {
84
+ yield prevPromisesCompletion;
85
+ yield task(next);
86
+ this._pendingPromises.delete(promise);
87
+ for (const value of values) {
88
+ this._baseObserver.next(value);
89
+ }
90
+ })).catch((error) => {
91
+ this._pendingPromises.delete(promise);
92
+ this._baseObserver.error(error);
93
+ });
94
+ this._pendingPromises.add(promise);
95
+ }
96
+ }
97
+ var __awaiter$1 = function(thisArg, _arguments, P, generator) {
98
+ function adopt(value) {
99
+ return value instanceof P ? value : new P(function(resolve2) {
100
+ resolve2(value);
101
+ });
102
+ }
103
+ return new (P || (P = Promise))(function(resolve2, reject) {
104
+ function fulfilled(value) {
105
+ try {
106
+ step6(generator.next(value));
107
+ } catch (e) {
108
+ reject(e);
109
+ }
110
+ }
111
+ function rejected(value) {
112
+ try {
113
+ step6(generator["throw"](value));
114
+ } catch (e) {
115
+ reject(e);
116
+ }
117
+ }
118
+ function step6(result) {
119
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
120
+ }
121
+ step6((generator = generator.apply(thisArg, _arguments || [])).next());
122
+ });
123
+ };
124
+ function filter$2(test2) {
125
+ return (observable) => {
126
+ return new Observable((observer) => {
127
+ const scheduler = new AsyncSerialScheduler(observer);
128
+ const subscription = observable.subscribe({
129
+ complete() {
130
+ scheduler.complete();
131
+ },
132
+ error(error) {
133
+ scheduler.error(error);
134
+ },
135
+ next(input) {
136
+ scheduler.schedule((next) => __awaiter$1(this, void 0, void 0, function* () {
137
+ if (yield test2(input)) {
138
+ next(input);
139
+ }
140
+ }));
141
+ }
142
+ });
143
+ return () => unsubscribe(subscription);
144
+ });
145
+ };
146
+ }
147
+ var __awaiter = function(thisArg, _arguments, P, generator) {
148
+ function adopt(value) {
149
+ return value instanceof P ? value : new P(function(resolve2) {
150
+ resolve2(value);
151
+ });
152
+ }
153
+ return new (P || (P = Promise))(function(resolve2, reject) {
154
+ function fulfilled(value) {
155
+ try {
156
+ step6(generator.next(value));
157
+ } catch (e) {
158
+ reject(e);
159
+ }
160
+ }
161
+ function rejected(value) {
162
+ try {
163
+ step6(generator["throw"](value));
164
+ } catch (e) {
165
+ reject(e);
166
+ }
167
+ }
168
+ function step6(result) {
169
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
170
+ }
171
+ step6((generator = generator.apply(thisArg, _arguments || [])).next());
172
+ });
173
+ };
174
+ function map$1(mapper) {
175
+ return (observable) => {
176
+ return new Observable((observer) => {
177
+ const scheduler = new AsyncSerialScheduler(observer);
178
+ const subscription = observable.subscribe({
179
+ complete() {
180
+ scheduler.complete();
181
+ },
182
+ error(error) {
183
+ scheduler.error(error);
184
+ },
185
+ next(input) {
186
+ scheduler.schedule((next) => __awaiter(this, void 0, void 0, function* () {
187
+ const mapped = yield mapper(input);
188
+ next(mapped);
189
+ }));
190
+ }
191
+ });
192
+ return () => unsubscribe(subscription);
193
+ });
194
+ };
195
+ }
196
+ class MulticastSubject extends Observable {
197
+ constructor() {
198
+ super((observer) => {
199
+ this._observers.add(observer);
200
+ return () => this._observers.delete(observer);
201
+ });
202
+ this._observers = /* @__PURE__ */ new Set();
203
+ }
204
+ next(value) {
205
+ for (const observer of this._observers) {
206
+ observer.next(value);
207
+ }
208
+ }
209
+ error(error) {
210
+ for (const observer of this._observers) {
211
+ observer.error(error);
212
+ }
213
+ }
214
+ complete() {
215
+ for (const observer of this._observers) {
216
+ observer.complete();
217
+ }
218
+ }
219
+ }
41
220
  var define_process_default$o = { env: {} };
42
221
  const version$2 = "0.5.1";
43
222
  class ResponseError extends Error {
@@ -6681,6 +6860,7 @@ class ContextFiltersProvider {
6681
6860
  __publicField2(this, "lastFetchDelay", 0);
6682
6861
  __publicField2(this, "lastResultLifetime");
6683
6862
  __publicField2(this, "fetchIntervalId");
6863
+ __publicField2(this, "authStatusProvider", null);
6684
6864
  __publicField2(this, "contextFiltersSubscriber", createSubscriber());
6685
6865
  __publicField2(this, "onContextFiltersChanged", this.contextFiltersSubscriber.subscribe);
6686
6866
  }
@@ -6688,8 +6868,9 @@ class ContextFiltersProvider {
6688
6868
  get timerStateForTest() {
6689
6869
  return { delay: this.lastFetchDelay, lifetime: this.lastResultLifetime };
6690
6870
  }
6691
- async init(getRepoNamesFromWorkspaceUri) {
6871
+ async init(getRepoNamesFromWorkspaceUri, authStatusProvider) {
6692
6872
  this.getRepoNamesFromWorkspaceUri = getRepoNamesFromWorkspaceUri;
6873
+ this.authStatusProvider = authStatusProvider;
6693
6874
  this.reset();
6694
6875
  this.startRefetchTimer(await this.fetchContextFilters());
6695
6876
  }
@@ -6733,7 +6914,7 @@ class ContextFiltersProvider {
6733
6914
  */
6734
6915
  setTestingContextFilters(contextFilters) {
6735
6916
  if (contextFilters === null) {
6736
- this.init(this.getRepoNamesFromWorkspaceUri);
6917
+ this.init(this.getRepoNamesFromWorkspaceUri, this.authStatusProvider);
6737
6918
  } else {
6738
6919
  this.setContextFilters(contextFilters);
6739
6920
  }
@@ -6813,7 +6994,13 @@ class ContextFiltersProvider {
6813
6994
  this.reset();
6814
6995
  }
6815
6996
  hasAllowEverythingFilters() {
6816
- return graphqlClient.isDotCom() || this.lastContextFiltersResponse === INCLUDE_EVERYTHING_CONTEXT_FILTERS;
6997
+ return this.isDotCom() || this.lastContextFiltersResponse === INCLUDE_EVERYTHING_CONTEXT_FILTERS;
6998
+ }
6999
+ isDotCom() {
7000
+ if (!this.authStatusProvider) {
7001
+ throw new Error("authStatusProvider is not set, ContextFiltersProvider.init must be called");
7002
+ }
7003
+ return isDotCom(this.authStatusProvider.status);
6817
7004
  }
6818
7005
  hasIgnoreEverythingFilters() {
6819
7006
  return this.lastContextFiltersResponse === EXCLUDE_EVERYTHING_CONTEXT_FILTERS;
@@ -7131,6 +7318,7 @@ const _ModelsService = class _ModelsService {
7131
7318
  __publicField2(this, "authStatus");
7132
7319
  /** Cache of users preferences and defaults across each endpoint they have used */
7133
7320
  __publicField2(this, "_preferences");
7321
+ __publicField2(this, "_selectedOrDefaultModelChanges", new MulticastSubject());
7134
7322
  }
7135
7323
  // Get all the providers currently available to the user
7136
7324
  get models() {
@@ -7203,9 +7391,13 @@ const _ModelsService = class _ModelsService {
7203
7391
  delete preferences.selected[usage];
7204
7392
  await this.flush();
7205
7393
  }
7394
+ get selectedOrDefaultModelChanges() {
7395
+ return this._selectedOrDefaultModelChanges;
7396
+ }
7206
7397
  async flush() {
7207
7398
  var _a3;
7208
7399
  await ((_a3 = this.storage) == null ? void 0 : _a3.set(_ModelsService.STORAGE_KEY, JSON.stringify(this._preferences)));
7400
+ this._selectedOrDefaultModelChanges.next();
7209
7401
  }
7210
7402
  /**
7211
7403
  * Add new models for use.
@@ -7558,7 +7750,7 @@ class ChatClient {
7558
7750
  ...params,
7559
7751
  messages: messagesToSend
7560
7752
  };
7561
- const customHeaders = isFireworks && this.getAuthStatus().isFireworksTracingEnabled ? { "X-Fireworks-Genie": "true" } : {};
7753
+ const customHeaders = isFireworks && authStatus.isFireworksTracingEnabled ? { "X-Fireworks-Genie": "true" } : {};
7562
7754
  return this.completions.stream(
7563
7755
  completionParams,
7564
7756
  {
@@ -8213,252 +8405,6 @@ class Typewriter {
8213
8405
  }
8214
8406
  }
8215
8407
  }
8216
- var __awaiter$3 = function(thisArg, _arguments, P, generator) {
8217
- function adopt(value) {
8218
- return value instanceof P ? value : new P(function(resolve2) {
8219
- resolve2(value);
8220
- });
8221
- }
8222
- return new (P || (P = Promise))(function(resolve2, reject) {
8223
- function fulfilled(value) {
8224
- try {
8225
- step6(generator.next(value));
8226
- } catch (e) {
8227
- reject(e);
8228
- }
8229
- }
8230
- function rejected(value) {
8231
- try {
8232
- step6(generator["throw"](value));
8233
- } catch (e) {
8234
- reject(e);
8235
- }
8236
- }
8237
- function step6(result) {
8238
- result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
8239
- }
8240
- step6((generator = generator.apply(thisArg, _arguments || [])).next());
8241
- });
8242
- };
8243
- let AsyncSerialScheduler$1 = class AsyncSerialScheduler2 {
8244
- constructor(observer) {
8245
- this._baseObserver = observer;
8246
- this._pendingPromises = /* @__PURE__ */ new Set();
8247
- }
8248
- complete() {
8249
- Promise.all(this._pendingPromises).then(() => this._baseObserver.complete()).catch((error) => this._baseObserver.error(error));
8250
- }
8251
- error(error) {
8252
- this._baseObserver.error(error);
8253
- }
8254
- schedule(task) {
8255
- const prevPromisesCompletion = Promise.all(this._pendingPromises);
8256
- const values = [];
8257
- const next = (value) => values.push(value);
8258
- const promise = Promise.resolve().then(() => __awaiter$3(this, void 0, void 0, function* () {
8259
- yield prevPromisesCompletion;
8260
- yield task(next);
8261
- this._pendingPromises.delete(promise);
8262
- for (const value of values) {
8263
- this._baseObserver.next(value);
8264
- }
8265
- })).catch((error) => {
8266
- this._pendingPromises.delete(promise);
8267
- this._baseObserver.error(error);
8268
- });
8269
- this._pendingPromises.add(promise);
8270
- }
8271
- };
8272
- function unsubscribe(subscription) {
8273
- if (typeof subscription === "function") {
8274
- subscription();
8275
- } else if (subscription && typeof subscription.unsubscribe === "function") {
8276
- subscription.unsubscribe();
8277
- }
8278
- }
8279
- var __awaiter$2 = function(thisArg, _arguments, P, generator) {
8280
- function adopt(value) {
8281
- return value instanceof P ? value : new P(function(resolve2) {
8282
- resolve2(value);
8283
- });
8284
- }
8285
- return new (P || (P = Promise))(function(resolve2, reject) {
8286
- function fulfilled(value) {
8287
- try {
8288
- step6(generator.next(value));
8289
- } catch (e) {
8290
- reject(e);
8291
- }
8292
- }
8293
- function rejected(value) {
8294
- try {
8295
- step6(generator["throw"](value));
8296
- } catch (e) {
8297
- reject(e);
8298
- }
8299
- }
8300
- function step6(result) {
8301
- result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
8302
- }
8303
- step6((generator = generator.apply(thisArg, _arguments || [])).next());
8304
- });
8305
- };
8306
- function filter$2(test2) {
8307
- return (observable) => {
8308
- return new Observable((observer) => {
8309
- const scheduler = new AsyncSerialScheduler$1(observer);
8310
- const subscription = observable.subscribe({
8311
- complete() {
8312
- scheduler.complete();
8313
- },
8314
- error(error) {
8315
- scheduler.error(error);
8316
- },
8317
- next(input) {
8318
- scheduler.schedule((next) => __awaiter$2(this, void 0, void 0, function* () {
8319
- if (yield test2(input)) {
8320
- next(input);
8321
- }
8322
- }));
8323
- }
8324
- });
8325
- return () => unsubscribe(subscription);
8326
- });
8327
- };
8328
- }
8329
- var __awaiter$1 = function(thisArg, _arguments, P, generator) {
8330
- function adopt(value) {
8331
- return value instanceof P ? value : new P(function(resolve2) {
8332
- resolve2(value);
8333
- });
8334
- }
8335
- return new (P || (P = Promise))(function(resolve2, reject) {
8336
- function fulfilled(value) {
8337
- try {
8338
- step6(generator.next(value));
8339
- } catch (e) {
8340
- reject(e);
8341
- }
8342
- }
8343
- function rejected(value) {
8344
- try {
8345
- step6(generator["throw"](value));
8346
- } catch (e) {
8347
- reject(e);
8348
- }
8349
- }
8350
- function step6(result) {
8351
- result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
8352
- }
8353
- step6((generator = generator.apply(thisArg, _arguments || [])).next());
8354
- });
8355
- };
8356
- function map$1(mapper) {
8357
- return (observable) => {
8358
- return new Observable((observer) => {
8359
- const scheduler = new AsyncSerialScheduler$1(observer);
8360
- const subscription = observable.subscribe({
8361
- complete() {
8362
- scheduler.complete();
8363
- },
8364
- error(error) {
8365
- scheduler.error(error);
8366
- },
8367
- next(input) {
8368
- scheduler.schedule((next) => __awaiter$1(this, void 0, void 0, function* () {
8369
- const mapped = yield mapper(input);
8370
- next(mapped);
8371
- }));
8372
- }
8373
- });
8374
- return () => unsubscribe(subscription);
8375
- });
8376
- };
8377
- }
8378
- class MulticastSubject extends Observable {
8379
- constructor() {
8380
- super((observer) => {
8381
- this._observers.add(observer);
8382
- return () => this._observers.delete(observer);
8383
- });
8384
- this._observers = /* @__PURE__ */ new Set();
8385
- }
8386
- next(value) {
8387
- for (const observer of this._observers) {
8388
- observer.next(value);
8389
- }
8390
- }
8391
- error(error) {
8392
- for (const observer of this._observers) {
8393
- observer.error(error);
8394
- }
8395
- }
8396
- complete() {
8397
- for (const observer of this._observers) {
8398
- observer.complete();
8399
- }
8400
- }
8401
- }
8402
- var _scheduler = {};
8403
- var __awaiter = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P, generator) {
8404
- function adopt(value) {
8405
- return value instanceof P ? value : new P(function(resolve2) {
8406
- resolve2(value);
8407
- });
8408
- }
8409
- return new (P || (P = Promise))(function(resolve2, reject) {
8410
- function fulfilled(value) {
8411
- try {
8412
- step6(generator.next(value));
8413
- } catch (e) {
8414
- reject(e);
8415
- }
8416
- }
8417
- function rejected(value) {
8418
- try {
8419
- step6(generator["throw"](value));
8420
- } catch (e) {
8421
- reject(e);
8422
- }
8423
- }
8424
- function step6(result) {
8425
- result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
8426
- }
8427
- step6((generator = generator.apply(thisArg, _arguments || [])).next());
8428
- });
8429
- };
8430
- Object.defineProperty(_scheduler, "__esModule", { value: true });
8431
- var AsyncSerialScheduler_1 = _scheduler.AsyncSerialScheduler = void 0;
8432
- class AsyncSerialScheduler {
8433
- constructor(observer) {
8434
- this._baseObserver = observer;
8435
- this._pendingPromises = /* @__PURE__ */ new Set();
8436
- }
8437
- complete() {
8438
- Promise.all(this._pendingPromises).then(() => this._baseObserver.complete()).catch((error) => this._baseObserver.error(error));
8439
- }
8440
- error(error) {
8441
- this._baseObserver.error(error);
8442
- }
8443
- schedule(task) {
8444
- const prevPromisesCompletion = Promise.all(this._pendingPromises);
8445
- const values = [];
8446
- const next = (value) => values.push(value);
8447
- const promise = Promise.resolve().then(() => __awaiter(this, void 0, void 0, function* () {
8448
- yield prevPromisesCompletion;
8449
- yield task(next);
8450
- this._pendingPromises.delete(promise);
8451
- for (const value of values) {
8452
- this._baseObserver.next(value);
8453
- }
8454
- })).catch((error) => {
8455
- this._pendingPromises.delete(promise);
8456
- this._baseObserver.error(error);
8457
- });
8458
- this._pendingPromises.add(promise);
8459
- }
8460
- }
8461
- AsyncSerialScheduler_1 = _scheduler.AsyncSerialScheduler = AsyncSerialScheduler;
8462
8408
  var define_process_default$j = { env: {} };
8463
8409
  var FeatureFlag = /* @__PURE__ */ ((FeatureFlag2) => {
8464
8410
  FeatureFlag2["TestFlagDoNotUse"] = "test-flag-do-not-use";
@@ -8474,12 +8420,17 @@ var FeatureFlag = /* @__PURE__ */ ((FeatureFlag2) => {
8474
8420
  FeatureFlag2["CodyAutocompleteFIMModelExperimentVariant3"] = "cody-autocomplete-fim-model-experiment-variant-3-v2";
8475
8421
  FeatureFlag2["CodyAutocompleteFIMModelExperimentVariant4"] = "cody-autocomplete-fim-model-experiment-variant-4-v2";
8476
8422
  FeatureFlag2["CodyAutocompleteClaude3"] = "cody-autocomplete-claude-3";
8477
- FeatureFlag2["CodyAutocompleteContextBfgMixed"] = "cody-autocomplete-context-bfg-mixed";
8478
8423
  FeatureFlag2["CodyAutocompleteUserLatency"] = "cody-autocomplete-user-latency";
8479
8424
  FeatureFlag2["CodyAutocompletePreloadingExperimentBaseFeatureFlag"] = "cody-autocomplete-preloading-experiment-flag";
8480
8425
  FeatureFlag2["CodyAutocompletePreloadingExperimentVariant1"] = "cody-autocomplete-preloading-experiment-variant-1";
8481
8426
  FeatureFlag2["CodyAutocompletePreloadingExperimentVariant2"] = "cody-autocomplete-preloading-experiment-variant-2";
8482
8427
  FeatureFlag2["CodyAutocompletePreloadingExperimentVariant3"] = "cody-autocomplete-preloading-experiment-variant-3";
8428
+ FeatureFlag2["CodyAutocompleteContextExperimentBaseFeatureFlag"] = "cody-autocomplete-context-experiment-flag";
8429
+ FeatureFlag2["CodyAutocompleteContextExperimentVariant1"] = "cody-autocomplete-context-experiment-variant-1";
8430
+ FeatureFlag2["CodyAutocompleteContextExperimentVariant2"] = "cody-autocomplete-context-experiment-variant-2";
8431
+ FeatureFlag2["CodyAutocompleteContextExperimentVariant3"] = "cody-autocomplete-context-experiment-variant-3";
8432
+ FeatureFlag2["CodyAutocompleteContextExperimentVariant4"] = "cody-autocomplete-context-experiment-variant-4";
8433
+ FeatureFlag2["CodyAutocompleteContextExperimentControl"] = "cody-autocomplete-context-experiment-control";
8483
8434
  FeatureFlag2["CodyAutocompleteContextExtendLanguagePool"] = "cody-autocomplete-context-extend-language-pool";
8484
8435
  FeatureFlag2["UseSscForCodySubscription"] = "use-ssc-for-cody-subscription";
8485
8436
  FeatureFlag2["CodyProTrialEnded"] = "cody-pro-trial-ended";
@@ -17859,8 +17810,8 @@ const capabilities = {
17859
17810
  };
17860
17811
  const dependencies = {
17861
17812
  "@anthropic-ai/sdk": "^0.20.8",
17862
- "@openctx/provider-linear-issues": "^0.0.6",
17863
- "@openctx/vscode-lib": "^0.0.21",
17813
+ "@openctx/provider-linear-issues": "^0.0.7",
17814
+ "@openctx/vscode-lib": "^0.0.22",
17864
17815
  "@opentelemetry/api": "^1.7.0",
17865
17816
  "@opentelemetry/core": "^1.18.1",
17866
17817
  "@opentelemetry/exporter-trace-otlp-http": "^0.45.1",
@@ -19715,10 +19666,6 @@ const emptyFileWatcher = {
19715
19666
  let clientInfo;
19716
19667
  function setClientInfo(newClientInfo) {
19717
19668
  clientInfo = newClientInfo;
19718
- setClientNameVersion(
19719
- clientInfo.legacyNameForServerIdentification ?? clientInfo.name,
19720
- clientInfo.version
19721
- );
19722
19669
  if (newClientInfo.extensionConfiguration) {
19723
19670
  setExtensionConfiguration(newClientInfo.extensionConfiguration);
19724
19671
  }
@@ -22819,7 +22766,7 @@ function requireBuffer() {
22819
22766
  if (hasRequiredBuffer) return buffer;
22820
22767
  hasRequiredBuffer = 1;
22821
22768
  (function(exports2) {
22822
- const base64 = requireBase64Js();
22769
+ const base64 = base64Js;
22823
22770
  const ieee7542 = requireIeee754();
22824
22771
  const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
22825
22772
  exports2.Buffer = Buffer2;
@@ -33545,52 +33492,47 @@ function getOSArch() {
33545
33492
  arch: arch2
33546
33493
  };
33547
33494
  }
33548
- var AccountMenuOptions = /* @__PURE__ */ ((AccountMenuOptions2) => {
33549
- AccountMenuOptions2["SignOut"] = "Sign Out";
33550
- AccountMenuOptions2["Manage"] = "Manage Account";
33551
- AccountMenuOptions2["Switch"] = "Switch Account...";
33552
- return AccountMenuOptions2;
33553
- })(AccountMenuOptions || {});
33554
- async function openAccountMenu(authStatus) {
33555
- if (!authStatus.authenticated || !authStatus.endpoint) {
33556
- return;
33495
+ class AuthProviderSimplified {
33496
+ async openExternalAuthUrl(method, tokenReceiverUrl) {
33497
+ if (!await openExternalAuthUrl(method, tokenReceiverUrl)) {
33498
+ return false;
33499
+ }
33500
+ authProvider.instance.setAuthPendingToEndpoint(DOTCOM_URL.toString());
33501
+ return true;
33557
33502
  }
33558
- const isOffline = authStatus.isOfflineMode;
33559
- const isDotComInstance = isDotCom(authStatus.endpoint) && !isOffline;
33560
- const displayName2 = authStatus.displayName || authStatus.username;
33561
- const email = authStatus.primaryEmail || "No Email";
33562
- const username = authStatus.username || authStatus.displayName;
33563
- const planDetail = `Plan: ${authStatus.userCanUpgrade ? "Cody Free" : "Cody Pro"}`;
33564
- const enterpriseDetail = `Enterprise Instance:
33565
- ${authStatus.endpoint}`;
33566
- const offlineDetail = "Use Cody offline with Ollama";
33567
- const options = isDotComInstance ? [
33568
- "Manage Account"
33569
- /* Manage */
33570
- ] : [];
33571
- options.push(
33572
- "Switch Account...",
33573
- "Sign Out"
33574
- /* SignOut */
33575
- );
33576
- const messageOptions = {
33577
- modal: true,
33578
- detail: isOffline ? offlineDetail : isDotComInstance ? planDetail : enterpriseDetail
33579
- };
33580
- const online = isDotComInstance ? `Signed in as ${displayName2} (${email})` : `Signed in as @${username}`;
33581
- const offline = "Offline Mode";
33582
- const message = isOffline ? offline : online;
33583
- const option = await window$1.showInformationMessage(message, messageOptions, ...options);
33584
- switch (option !== void 0) {
33585
- case (option == null ? void 0 : option.startsWith("Sign Out")):
33586
- return "Sign Out";
33587
- case (option == null ? void 0 : option.startsWith("Manage")):
33588
- return "Manage Account";
33589
- case (option == null ? void 0 : option.startsWith("Switch")):
33590
- return "Switch Account...";
33503
+ }
33504
+ function getAuthReferralCode() {
33505
+ return {
33506
+ "vscode-insiders": "CODY_INSIDERS",
33507
+ vscodium: "CODY_VSCODIUM",
33508
+ cursor: "CODY_CURSOR"
33509
+ }[env.uriScheme] || "CODY";
33510
+ }
33511
+ function openExternalAuthUrl(provider, tokenReceiverUrl) {
33512
+ const referralCode = getAuthReferralCode();
33513
+ const tokenReceiver = tokenReceiverUrl ? `&tokenReceiverUrl=${encodeURIComponent(tokenReceiverUrl)}` : "";
33514
+ const newTokenUrl = `/user/settings/tokens/new/callback?requestFrom=${referralCode}${tokenReceiver}`;
33515
+ const site = new URL(newTokenUrl, DOTCOM_URL);
33516
+ const genericLoginUrl = `${site}sign-in?returnTo=${newTokenUrl}`;
33517
+ const gitHubLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=github&pc=sams&redirect=${newTokenUrl}`;
33518
+ const gitLabLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=gitlab&pc=sams&redirect=${newTokenUrl}`;
33519
+ const googleLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=google&pc=sams&redirect=${newTokenUrl}`;
33520
+ let uriSpec;
33521
+ switch (provider) {
33522
+ case "github":
33523
+ uriSpec = gitHubLoginUrl;
33524
+ break;
33525
+ case "gitlab":
33526
+ uriSpec = gitLabLoginUrl;
33527
+ break;
33528
+ case "google":
33529
+ uriSpec = googleLoginUrl;
33530
+ break;
33591
33531
  default:
33592
- return void 0;
33532
+ uriSpec = genericLoginUrl;
33533
+ break;
33593
33534
  }
33535
+ return env.openExternal(uriSpec);
33594
33536
  }
33595
33537
  let runningAuthProgressIndicator = null;
33596
33538
  function startAuthProgressIndicator() {
@@ -33614,38 +33556,285 @@ function closeAuthProgressIndicator() {
33614
33556
  runningAuthProgressIndicator == null ? void 0 : runningAuthProgressIndicator();
33615
33557
  runningAuthProgressIndicator = null;
33616
33558
  }
33559
+ async function showSignInMenu(type2, uri2) {
33560
+ const authStatus = authProvider.instance.status;
33561
+ const mode = authStatus.authenticated ? "switch" : "signin";
33562
+ logDebug("AuthProvider:signinMenu", mode);
33563
+ telemetryRecorder.recordEvent("cody.auth.login", "clicked");
33564
+ const item = await showAuthMenu(mode);
33565
+ if (!item) {
33566
+ return;
33567
+ }
33568
+ const menuID = item == null ? void 0 : item.id;
33569
+ telemetryRecorder.recordEvent("cody.auth.signin.menu", "clicked", {
33570
+ privateMetadata: { menuID }
33571
+ });
33572
+ switch (menuID) {
33573
+ case "enterprise": {
33574
+ const instanceUrl = await showInstanceURLInputBox(item.uri);
33575
+ if (!instanceUrl) {
33576
+ return;
33577
+ }
33578
+ authProvider.instance.setAuthPendingToEndpoint(instanceUrl);
33579
+ redirectToEndpointLogin(instanceUrl);
33580
+ break;
33581
+ }
33582
+ case "dotcom":
33583
+ redirectToEndpointLogin(DOTCOM_URL.href);
33584
+ break;
33585
+ case "token": {
33586
+ const instanceUrl = await showInstanceURLInputBox(item.uri);
33587
+ if (!instanceUrl) {
33588
+ return;
33589
+ }
33590
+ await signinMenuForInstanceUrl(instanceUrl);
33591
+ break;
33592
+ }
33593
+ default: {
33594
+ const selectedEndpoint = item.uri;
33595
+ const token = await secretStorage.get(selectedEndpoint);
33596
+ let authStatus2 = await authProvider.instance.auth({
33597
+ endpoint: selectedEndpoint,
33598
+ token: token || null
33599
+ });
33600
+ if (!(authStatus2 == null ? void 0 : authStatus2.authenticated)) {
33601
+ const newToken = await showAccessTokenInputBox(item.uri);
33602
+ if (!newToken) {
33603
+ return;
33604
+ }
33605
+ authStatus2 = await authProvider.instance.auth({
33606
+ endpoint: selectedEndpoint,
33607
+ token: newToken || null
33608
+ });
33609
+ }
33610
+ await showAuthResultMessage(selectedEndpoint, authStatus2);
33611
+ logDebug("AuthProvider:signinMenu", mode, selectedEndpoint);
33612
+ }
33613
+ }
33614
+ }
33615
+ function getItemLabel$1(uri2, current) {
33616
+ const icon2 = current ? "$(check) " : "";
33617
+ if (isDotCom(uri2)) {
33618
+ return `${icon2}Sourcegraph.com`;
33619
+ }
33620
+ return `${icon2}${uri2}`;
33621
+ }
33622
+ async function showAuthMenu(type2) {
33623
+ const endpointHistory = localStorage.getEndpointHistory() ?? [];
33624
+ const historySize = endpointHistory == null ? void 0 : endpointHistory.length;
33625
+ const history = historySize > 0 ? endpointHistory == null ? void 0 : endpointHistory.map((uri2, i) => ({
33626
+ id: uri2,
33627
+ label: getItemLabel$1(uri2, type2 === "switch" && i === historySize - 1),
33628
+ description: "",
33629
+ uri: uri2
33630
+ })).reverse() : [];
33631
+ const separator = [{ label: type2 === "signin" ? "previously used" : "current", kind: -1 }];
33632
+ const optionItems = [...LoginMenuOptionItems, ...separator, ...history];
33633
+ const option = await window$1.showQuickPick(
33634
+ optionItems,
33635
+ AuthMenuOptions[type2]
33636
+ );
33637
+ return option;
33638
+ }
33639
+ async function showInstanceURLInputBox(title) {
33640
+ const result = await window$1.showInputBox({
33641
+ title,
33642
+ prompt: "Enter the URL of the Sourcegraph instance. For example, https://sourcegraph.example.com.",
33643
+ placeHolder: "https://sourcegraph.example.com",
33644
+ value: "https://",
33645
+ password: false,
33646
+ ignoreFocusOut: true,
33647
+ // valide input to ensure the user is not entering a token as URL
33648
+ validateInput: (value) => {
33649
+ if (!value) {
33650
+ return null;
33651
+ }
33652
+ if (isSourcegraphToken(value)) {
33653
+ return "Please enter a valid URL";
33654
+ }
33655
+ if (value.length > 4 && !value.startsWith("http")) {
33656
+ return "URL must start with http or https";
33657
+ }
33658
+ if (!/([.]|^https?:\/\/)/.test(value)) {
33659
+ return "Please enter a valid URL";
33660
+ }
33661
+ return null;
33662
+ }
33663
+ });
33664
+ if (typeof result === "string") {
33665
+ return result.trim();
33666
+ }
33667
+ return result;
33668
+ }
33669
+ async function showAccessTokenInputBox(endpoint) {
33670
+ const result = await window$1.showInputBox({
33671
+ title: endpoint,
33672
+ prompt: 'Paste your access token. To create an access token, go to "Settings" and then "Access tokens" on the Sourcegraph instance.',
33673
+ placeHolder: "Access Token",
33674
+ password: true,
33675
+ ignoreFocusOut: true
33676
+ });
33677
+ if (typeof result === "string") {
33678
+ return result.trim();
33679
+ }
33680
+ return result;
33681
+ }
33682
+ const AuthMenuOptions = {
33683
+ signin: {
33684
+ title: "Other Sign-in Options",
33685
+ placeholder: "Choose a sign-in option"
33686
+ },
33687
+ switch: {
33688
+ title: "Switch Account",
33689
+ placeHolder: "Choose an account"
33690
+ }
33691
+ };
33692
+ const LoginMenuOptionItems = [
33693
+ {
33694
+ id: "enterprise",
33695
+ label: "Sign In to Sourcegraph Enterprise Instance",
33696
+ description: "v5.1 and above",
33697
+ totalSteps: 1,
33698
+ picked: true
33699
+ },
33700
+ {
33701
+ id: "token",
33702
+ label: "Sign In to Sourcegraph Enterprise Instance with Access Token",
33703
+ description: "v5.0 and above",
33704
+ totalSteps: 2
33705
+ },
33706
+ {
33707
+ id: "token",
33708
+ label: "Sign In with URL and Access Token",
33709
+ totalSteps: 2
33710
+ }
33711
+ ];
33712
+ async function signinMenuForInstanceUrl(instanceUrl) {
33713
+ const accessToken = await showAccessTokenInputBox(instanceUrl);
33714
+ if (!accessToken) {
33715
+ return;
33716
+ }
33717
+ const authState = await authProvider.instance.auth({
33718
+ endpoint: instanceUrl,
33719
+ token: accessToken
33720
+ });
33721
+ telemetryRecorder.recordEvent("cody.auth.signin.token", "clicked", {
33722
+ metadata: {
33723
+ success: authState.authenticated ? 1 : 0
33724
+ }
33725
+ });
33726
+ await showAuthResultMessage(instanceUrl, authState);
33727
+ }
33728
+ function redirectToEndpointLogin(uri2) {
33729
+ const endpoint = formatURL(uri2);
33730
+ if (!endpoint) {
33731
+ return;
33732
+ }
33733
+ if (env.uiKind === UIKind.Web) {
33734
+ const newTokenNoCallbackUrl = new URL("/user/settings/tokens/new", endpoint);
33735
+ void env.openExternal(Uri.parse(newTokenNoCallbackUrl.href));
33736
+ void signinMenuForInstanceUrl(endpoint);
33737
+ return;
33738
+ }
33739
+ const newTokenCallbackUrl = new URL("/user/settings/tokens/new/callback", endpoint);
33740
+ newTokenCallbackUrl.searchParams.append("requestFrom", getAuthReferralCode());
33741
+ authProvider.instance.setAuthPendingToEndpoint(endpoint);
33742
+ void env.openExternal(Uri.parse(newTokenCallbackUrl.href));
33743
+ }
33744
+ async function showAuthResultMessage(endpoint, authStatus) {
33745
+ if (authStatus == null ? void 0 : authStatus.authenticated) {
33746
+ const authority = Uri.parse(endpoint).authority;
33747
+ await window$1.showInformationMessage(`Signed in to ${authority || endpoint}`);
33748
+ } else {
33749
+ await showAuthFailureMessage(endpoint);
33750
+ }
33751
+ }
33752
+ async function showAuthFailureMessage(endpoint) {
33753
+ const authority = Uri.parse(endpoint).authority;
33754
+ await window$1.showErrorMessage(
33755
+ `Authentication failed. Please ensure Cody is enabled for ${authority} and verify your email address if required.`
33756
+ );
33757
+ }
33758
+ async function tokenCallbackHandler(uri2, customHeaders) {
33759
+ closeAuthProgressIndicator();
33760
+ const params = new URLSearchParams(uri2.query);
33761
+ const token = params.get("code");
33762
+ const endpoint = authProvider.instance.status.endpoint;
33763
+ if (!token || !endpoint) {
33764
+ return;
33765
+ }
33766
+ const authState = await authProvider.instance.auth({ endpoint, token, customHeaders });
33767
+ telemetryRecorder.recordEvent("cody.auth.fromCallback.web", "succeeded", {
33768
+ metadata: {
33769
+ success: (authState == null ? void 0 : authState.authenticated) ? 1 : 0
33770
+ }
33771
+ });
33772
+ if (authState == null ? void 0 : authState.authenticated) {
33773
+ await window$1.showInformationMessage(`Signed in to ${endpoint}`);
33774
+ } else {
33775
+ await showAuthFailureMessage(endpoint);
33776
+ }
33777
+ }
33778
+ function formatURL(uri2) {
33779
+ try {
33780
+ if (!uri2) {
33781
+ return null;
33782
+ }
33783
+ if (isSourcegraphToken(uri2)) {
33784
+ throw new Error("Access Token is not a valid URL");
33785
+ }
33786
+ if (!uri2.startsWith("http")) {
33787
+ uri2 = `https://${uri2}`;
33788
+ }
33789
+ const endpointUri = new URL(uri2);
33790
+ return endpointUri.href;
33791
+ } catch (error) {
33792
+ console.error("Invalid URL: ", error);
33793
+ return null;
33794
+ }
33795
+ }
33796
+ async function showSignOutMenu() {
33797
+ telemetryRecorder.recordEvent("cody.auth.logout", "clicked");
33798
+ const { endpoint } = authProvider.instance.status;
33799
+ if (endpoint) {
33800
+ await signOut(endpoint);
33801
+ logDebug("AuthProvider:signoutMenu", endpoint);
33802
+ }
33803
+ }
33804
+ async function signOut(endpoint) {
33805
+ await secretStorage.deleteToken(endpoint);
33806
+ await localStorage.deleteEndpoint();
33807
+ await authProvider.instance.auth({ endpoint, token: null });
33808
+ await commands$1.executeCommand("setContext", "cody.activated", false);
33809
+ }
33617
33810
  function newAuthStatus(options) {
33618
33811
  var _a3;
33619
- const {
33620
- isOfflineMode,
33621
- endpoint,
33622
- siteHasCodyEnabled,
33623
- username,
33624
- authenticated,
33625
- isDotCom: isDotCom2,
33626
- siteVersion,
33627
- userOrganizations
33628
- } = options;
33629
- if (isOfflineMode) {
33630
- return { ...offlineModeAuthStatus, endpoint, username };
33812
+ if (!options.authenticated) {
33813
+ return { authenticated: false, endpoint: options.endpoint, showInvalidAccessTokenError: true };
33631
33814
  }
33632
- if (!authenticated) {
33633
- return { ...unauthenticatedStatus, endpoint };
33815
+ const { isOfflineMode, username, endpoint, siteVersion, userOrganizations } = options;
33816
+ if (isOfflineMode) {
33817
+ return {
33818
+ authenticated: true,
33819
+ endpoint,
33820
+ username,
33821
+ codyApiVersion: 0,
33822
+ siteVersion: "offline",
33823
+ isOfflineMode: true
33824
+ };
33634
33825
  }
33635
- const primaryEmail = typeof options.primaryEmail === "string" ? options.primaryEmail : ((_a3 = options.primaryEmail) == null ? void 0 : _a3.email) || "";
33636
- const requiresVerifiedEmail = isDotCom2;
33637
- const hasVerifiedEmail = requiresVerifiedEmail && options.hasVerifiedEmail;
33638
- const isAllowed = !requiresVerifiedEmail || hasVerifiedEmail;
33826
+ const isDotCom_ = isDotCom(endpoint);
33827
+ const primaryEmail = typeof options.primaryEmail === "string" ? options.primaryEmail : (_a3 = options.primaryEmail) == null ? void 0 : _a3.email;
33828
+ const requiresVerifiedEmail = isDotCom_;
33829
+ const hasVerifiedEmail = requiresVerifiedEmail && options.authenticated && options.hasVerifiedEmail;
33639
33830
  return {
33640
33831
  ...options,
33641
- showInvalidAccessTokenError: false,
33642
33832
  endpoint,
33643
33833
  primaryEmail,
33644
33834
  requiresVerifiedEmail,
33645
33835
  hasVerifiedEmail,
33646
- isLoggedIn: siteHasCodyEnabled && authenticated && isAllowed,
33647
- codyApiVersion: inferCodyApiVersion(siteVersion, isDotCom2),
33648
- isFireworksTracingEnabled: isDotCom2 && !!(userOrganizations == null ? void 0 : userOrganizations.nodes.find((org) => org.name === "sourcegraph"))
33836
+ codyApiVersion: inferCodyApiVersion(siteVersion, isDotCom_),
33837
+ isFireworksTracingEnabled: isDotCom_ && !!(userOrganizations == null ? void 0 : userOrganizations.nodes.find((org) => org.name === "sourcegraph"))
33649
33838
  };
33650
33839
  }
33651
33840
  const countGeneratedCode = (text) => {
@@ -33729,7 +33918,7 @@ function getEnterpriseOutputLimit(model2) {
33729
33918
  async function syncModels(authStatus) {
33730
33919
  var _a3, _b2;
33731
33920
  modelsService.instance.setAuthStatus(authStatus);
33732
- if (authStatus.isOfflineMode) {
33921
+ if (authStatus.authenticated && authStatus.isOfflineMode) {
33733
33922
  modelsService.instance.setModels([]);
33734
33923
  return;
33735
33924
  }
@@ -33742,12 +33931,15 @@ async function syncModels(authStatus) {
33742
33931
  logDebug("ModelsService", "new models API enabled");
33743
33932
  const serverSideModels = await fetchServerSideModels(authStatus.endpoint || "");
33744
33933
  if (serverSideModels) {
33745
- modelsService.instance.setServerSentModels(serverSideModels);
33934
+ modelsService.instance.setServerSentModels({
33935
+ ...serverSideModels,
33936
+ models: maybeAdjustContextWindows(serverSideModels.models)
33937
+ });
33746
33938
  registerModelsFromVSCodeConfiguration();
33747
33939
  return;
33748
33940
  }
33749
33941
  }
33750
- if (authStatus.isDotCom) {
33942
+ if (isDotCom(authStatus)) {
33751
33943
  modelsService.instance.setModels(getDotComDefaultModels());
33752
33944
  registerModelsFromVSCodeConfiguration();
33753
33945
  return;
@@ -33799,6 +33991,13 @@ async function fetchServerSideModels(endpoint) {
33799
33991
  const client = new RestClient(endpoint, userAccessToken, customHeaders);
33800
33992
  return await client.getAvailableModels();
33801
33993
  }
33994
+ const maybeAdjustContextWindows = (models) => models.map((model2) => {
33995
+ let maxInputTokens = model2.contextWindow.maxInputTokens;
33996
+ if (/^mi(x|s)tral/.test(model2.modelName)) {
33997
+ maxInputTokens = Math.round(model2.contextWindow.maxInputTokens * 0.85);
33998
+ }
33999
+ return { ...model2, contextWindow: { ...model2.contextWindow, maxInputTokens } };
34000
+ });
33802
34001
  function logFirstEnrollmentEvent(key, isEnabled) {
33803
34002
  const isEnrolled = localStorage.getEnrollmentHistory(key);
33804
34003
  const eventName = getFeatureFlagEventName(key);
@@ -33843,159 +34042,18 @@ const maybeStartInteractiveTutorial = async () => {
33843
34042
  }
33844
34043
  return commands$1.executeCommand("cody.tutorial.start");
33845
34044
  };
33846
- function getItemLabel$1(uri2, current) {
33847
- const icon2 = current ? "$(check) " : "";
33848
- if (isDotCom(uri2)) {
33849
- return `${icon2}Sourcegraph.com`;
33850
- }
33851
- return `${icon2}${uri2}`;
33852
- }
33853
- const AuthMenu = async (type2, historyItems) => {
33854
- const historySize = historyItems == null ? void 0 : historyItems.length;
33855
- const history = historySize > 0 ? historyItems == null ? void 0 : historyItems.map((uri2, i) => ({
33856
- id: uri2,
33857
- label: getItemLabel$1(uri2, type2 === "switch" && i === historySize - 1),
33858
- description: "",
33859
- uri: uri2
33860
- })).reverse() : [];
33861
- const separator = [{ label: type2 === "signin" ? "previously used" : "current", kind: -1 }];
33862
- const optionItems = [...LoginMenuOptionItems, ...separator, ...history];
33863
- const option = await window$1.showQuickPick(
33864
- optionItems,
33865
- AuthMenuOptions[type2]
33866
- );
33867
- return option;
33868
- };
33869
- async function showInstanceURLInputBox(title) {
33870
- const result = await window$1.showInputBox({
33871
- title,
33872
- prompt: "Enter the URL of the Sourcegraph instance. For example, https://sourcegraph.example.com.",
33873
- placeHolder: "https://sourcegraph.example.com",
33874
- value: "https://",
33875
- password: false,
33876
- ignoreFocusOut: true,
33877
- // valide input to ensure the user is not entering a token as URL
33878
- validateInput: (value) => {
33879
- if (!value) {
33880
- return null;
33881
- }
33882
- if (isSourcegraphToken(value)) {
33883
- return "Please enter a valid URL";
33884
- }
33885
- if (value.length > 4 && !value.startsWith("http")) {
33886
- return "URL must start with http or https";
33887
- }
33888
- if (!/([.]|^https?:\/\/)/.test(value)) {
33889
- return "Please enter a valid URL";
33890
- }
33891
- return null;
33892
- }
33893
- });
33894
- if (typeof result === "string") {
33895
- return result.trim();
33896
- }
33897
- return result;
33898
- }
33899
- async function showAccessTokenInputBox(endpoint) {
33900
- const result = await window$1.showInputBox({
33901
- title: endpoint,
33902
- prompt: 'Paste your access token. To create an access token, go to "Settings" and then "Access tokens" on the Sourcegraph instance.',
33903
- placeHolder: "Access Token",
33904
- password: true,
33905
- ignoreFocusOut: true
33906
- });
33907
- if (typeof result === "string") {
33908
- return result.trim();
33909
- }
33910
- return result;
33911
- }
33912
- const AuthMenuOptions = {
33913
- signin: {
33914
- title: "Other Sign-in Options",
33915
- placeholder: "Choose a sign-in option"
33916
- },
33917
- switch: {
33918
- title: "Switch Account",
33919
- placeHolder: "Choose an account"
33920
- }
33921
- };
33922
- const LoginMenuOptionItems = [
33923
- {
33924
- id: "enterprise",
33925
- label: "Sign In to Sourcegraph Enterprise Instance",
33926
- description: "v5.1 and above",
33927
- totalSteps: 1,
33928
- picked: true
33929
- },
33930
- {
33931
- id: "token",
33932
- label: "Sign In to Sourcegraph Enterprise Instance with Access Token",
33933
- description: "v5.0 and above",
33934
- totalSteps: 2
33935
- },
33936
- {
33937
- id: "token",
33938
- label: "Sign In with URL and Access Token",
33939
- totalSteps: 2
33940
- }
33941
- ];
33942
- class AuthProviderSimplified {
33943
- async openExternalAuthUrl(method, tokenReceiverUrl) {
33944
- if (!await openExternalAuthUrl(method, tokenReceiverUrl)) {
33945
- return false;
33946
- }
33947
- authProvider.instance.authProviderSimplifiedWillAttemptAuth();
33948
- return true;
33949
- }
33950
- }
33951
- function getAuthReferralCode() {
33952
- return {
33953
- "vscode-insiders": "CODY_INSIDERS",
33954
- vscodium: "CODY_VSCODIUM",
33955
- cursor: "CODY_CURSOR"
33956
- }[env.uriScheme] || "CODY";
33957
- }
33958
- function openExternalAuthUrl(provider, tokenReceiverUrl) {
33959
- const referralCode = getAuthReferralCode();
33960
- const tokenReceiver = tokenReceiverUrl ? `&tokenReceiverUrl=${encodeURIComponent(tokenReceiverUrl)}` : "";
33961
- const newTokenUrl = `/user/settings/tokens/new/callback?requestFrom=${referralCode}${tokenReceiver}`;
33962
- const site = new URL(newTokenUrl, DOTCOM_URL);
33963
- const genericLoginUrl = `${site}sign-in?returnTo=${newTokenUrl}`;
33964
- const gitHubLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=github&pc=sams&redirect=${newTokenUrl}`;
33965
- const gitLabLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=gitlab&pc=sams&redirect=${newTokenUrl}`;
33966
- const googleLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=google&pc=sams&redirect=${newTokenUrl}`;
33967
- let uriSpec;
33968
- switch (provider) {
33969
- case "github":
33970
- uriSpec = gitHubLoginUrl;
33971
- break;
33972
- case "gitlab":
33973
- uriSpec = gitLabLoginUrl;
33974
- break;
33975
- case "google":
33976
- uriSpec = googleLoginUrl;
33977
- break;
33978
- default:
33979
- uriSpec = genericLoginUrl;
33980
- break;
33981
- }
33982
- return env.openExternal(uriSpec);
33983
- }
33984
34045
  const HAS_AUTHENTICATED_BEFORE_KEY = "has-authenticated-before";
33985
34046
  class AuthProvider {
33986
34047
  constructor(config) {
33987
- __publicField2(this, "endpointHistory", []);
33988
34048
  __publicField2(this, "client", null);
33989
- __publicField2(this, "status", defaultAuthStatus);
34049
+ __publicField2(this, "_status", null);
33990
34050
  __publicField2(this, "didChangeEvent", new AgentEventEmitter());
33991
34051
  __publicField2(this, "disposables", [this.didChangeEvent]);
33992
34052
  __publicField2(this, "changes", fromVSCodeEvent(
33993
34053
  this.didChangeEvent.event,
33994
- this.getAuthStatus.bind(this)
33995
- ));
34054
+ () => this._status ?? NO_INITIAL_VALUE
34055
+ ).pipe(distinctUntilChanged$1()));
33996
34056
  this.config = config;
33997
- this.status.endpoint = "init";
33998
- this.loadEndpointHistory();
33999
34057
  }
34000
34058
  dispose() {
34001
34059
  for (const d2 of this.disposables) {
@@ -34018,114 +34076,6 @@ class AuthProvider {
34018
34076
  isExtensionStartup: true
34019
34077
  }).catch((error) => logError$2("AuthProvider:init:failed", lastEndpoint, { verbose: error }));
34020
34078
  }
34021
- // Display quickpick to select endpoint to sign in to
34022
- async signinMenu(type2, uri2) {
34023
- const mode = this.status.isLoggedIn ? "switch" : "signin";
34024
- logDebug("AuthProvider:signinMenu", mode);
34025
- telemetryRecorder.recordEvent("cody.auth.login", "clicked");
34026
- const item = await AuthMenu(mode, this.endpointHistory);
34027
- if (!item) {
34028
- return;
34029
- }
34030
- const menuID = type2 || (item == null ? void 0 : item.id);
34031
- telemetryRecorder.recordEvent("cody.auth.signin.menu", "clicked", {
34032
- privateMetadata: { menuID }
34033
- });
34034
- switch (menuID) {
34035
- case "enterprise": {
34036
- const instanceUrl = await showInstanceURLInputBox(item.uri);
34037
- if (!instanceUrl) {
34038
- return;
34039
- }
34040
- this.status.endpoint = instanceUrl;
34041
- this.redirectToEndpointLogin(instanceUrl);
34042
- break;
34043
- }
34044
- case "dotcom":
34045
- this.redirectToEndpointLogin(DOTCOM_URL.href);
34046
- break;
34047
- case "token": {
34048
- const instanceUrl = await showInstanceURLInputBox(uri2 || item.uri);
34049
- if (!instanceUrl) {
34050
- return;
34051
- }
34052
- await this.signinMenuForInstanceUrl(instanceUrl);
34053
- break;
34054
- }
34055
- default: {
34056
- const selectedEndpoint = item.uri;
34057
- const token = await secretStorage.get(selectedEndpoint);
34058
- let authStatus = await this.auth({
34059
- endpoint: selectedEndpoint,
34060
- token: token || null
34061
- });
34062
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
34063
- const newToken = await showAccessTokenInputBox(item.uri);
34064
- if (!newToken) {
34065
- return;
34066
- }
34067
- authStatus = await this.auth({
34068
- endpoint: selectedEndpoint,
34069
- token: newToken || null
34070
- });
34071
- }
34072
- await showAuthResultMessage(selectedEndpoint, authStatus);
34073
- logDebug("AuthProvider:signinMenu", mode, selectedEndpoint);
34074
- }
34075
- }
34076
- }
34077
- async signinMenuForInstanceUrl(instanceUrl) {
34078
- const accessToken = await showAccessTokenInputBox(instanceUrl);
34079
- if (!accessToken) {
34080
- return;
34081
- }
34082
- const authState = await this.auth({
34083
- endpoint: instanceUrl,
34084
- token: accessToken
34085
- });
34086
- telemetryRecorder.recordEvent("cody.auth.signin.token", "clicked", {
34087
- metadata: {
34088
- success: authState.isLoggedIn ? 1 : 0
34089
- }
34090
- });
34091
- await showAuthResultMessage(instanceUrl, authState);
34092
- }
34093
- async signoutMenu() {
34094
- telemetryRecorder.recordEvent("cody.auth.logout", "clicked");
34095
- const { endpoint } = this.getAuthStatus();
34096
- if (endpoint) {
34097
- await this.signout(endpoint);
34098
- logDebug("AuthProvider:signoutMenu", endpoint);
34099
- }
34100
- }
34101
- async accountMenu() {
34102
- const selected = await openAccountMenu(this.status);
34103
- if (selected === void 0) {
34104
- return;
34105
- }
34106
- switch (selected) {
34107
- case AccountMenuOptions.Manage: {
34108
- const uri2 = Uri.parse(ACCOUNT_USAGE_URL.toString()).with({
34109
- query: `cody_client_user=${encodeURIComponent(this.status.username)}`
34110
- });
34111
- void env.openExternal(uri2);
34112
- break;
34113
- }
34114
- case AccountMenuOptions.Switch:
34115
- await this.signinMenu();
34116
- break;
34117
- case AccountMenuOptions.SignOut:
34118
- await this.signoutMenu();
34119
- break;
34120
- }
34121
- }
34122
- // Log user out of the selected endpoint (remove token from secret)
34123
- async signout(endpoint) {
34124
- await secretStorage.deleteToken(endpoint);
34125
- await localStorage.deleteEndpoint();
34126
- await this.auth({ endpoint: "", token: null });
34127
- await commands$1.executeCommand("setContext", "cody.activated", false);
34128
- }
34129
34079
  // Create Auth Status
34130
34080
  async makeAuthStatus(config, isOfflineMode) {
34131
34081
  var _a3;
@@ -34134,15 +34084,22 @@ class AuthProvider {
34134
34084
  const isCodyWeb = workspace.getConfiguration().get("cody.advanced.agent.ide") === CodyIDE.Web;
34135
34085
  if (isOfflineMode) {
34136
34086
  const lastUser = localStorage.getLastStoredUser();
34137
- return { ...offlineModeAuthStatus, ...lastUser };
34087
+ return {
34088
+ endpoint: (lastUser == null ? void 0 : lastUser.endpoint) ?? "https://offline.sourcegraph.com",
34089
+ username: (lastUser == null ? void 0 : lastUser.username) ?? "offline-user",
34090
+ authenticated: true,
34091
+ isOfflineMode: true,
34092
+ codyApiVersion: 0,
34093
+ siteVersion: ""
34094
+ };
34138
34095
  }
34139
34096
  if (isCodyWeb) {
34140
34097
  if (!endpoint) {
34141
- return { ...defaultAuthStatus, endpoint };
34098
+ return { authenticated: false, endpoint };
34142
34099
  }
34143
34100
  } else {
34144
34101
  if (!token || !endpoint) {
34145
- return { ...defaultAuthStatus, endpoint };
34102
+ return { authenticated: false, endpoint };
34146
34103
  }
34147
34104
  }
34148
34105
  if (this.config !== config || !this.client) {
@@ -34155,24 +34112,27 @@ class AuthProvider {
34155
34112
  this.client.getCurrentUserInfo()
34156
34113
  ]);
34157
34114
  logDebug("CodyLLMConfiguration", JSON.stringify(codyLLMConfiguration));
34158
- if (isError$1(userInfo) && isNetworkError(userInfo)) {
34159
- return { ...networkErrorAuthStatus, endpoint };
34115
+ if (isError$1(userInfo) && isNetworkLikeError(userInfo)) {
34116
+ return { authenticated: false, showNetworkError: true, endpoint };
34160
34117
  }
34161
34118
  if (!userInfo || isError$1(userInfo)) {
34162
- return { ...unauthenticatedStatus, endpoint };
34119
+ return { authenticated: false, endpoint, showInvalidAccessTokenError: true };
34120
+ }
34121
+ if (!siteHasCodyEnabled) {
34122
+ window$1.showErrorMessage(
34123
+ `Cody is not enabled on this Sourcegraph instance (${endpoint}). Ask a site administrator to enable it.`
34124
+ );
34125
+ return { authenticated: false, endpoint };
34163
34126
  }
34164
34127
  const configOverwrites = isError$1(codyLLMConfiguration) ? void 0 : codyLLMConfiguration;
34165
- const isDotCom2 = this.client.isDotCom();
34166
- if (!isDotCom2) {
34128
+ if (!isDotCom(endpoint)) {
34167
34129
  return newAuthStatus({
34168
34130
  ...userInfo,
34169
34131
  endpoint,
34170
- isDotCom: isDotCom2,
34171
34132
  siteVersion,
34172
34133
  configOverwrites,
34173
34134
  authenticated: true,
34174
34135
  hasVerifiedEmail: false,
34175
- siteHasCodyEnabled,
34176
34136
  userCanUpgrade: false
34177
34137
  });
34178
34138
  }
@@ -34181,8 +34141,6 @@ class AuthProvider {
34181
34141
  return newAuthStatus({
34182
34142
  ...userInfo,
34183
34143
  endpoint,
34184
- isDotCom: isDotCom2,
34185
- siteHasCodyEnabled,
34186
34144
  siteVersion,
34187
34145
  configOverwrites,
34188
34146
  authenticated: !!userInfo.id,
@@ -34190,8 +34148,25 @@ class AuthProvider {
34190
34148
  primaryEmail: ((_a3 = userInfo.primaryEmail) == null ? void 0 : _a3.email) ?? ""
34191
34149
  });
34192
34150
  }
34193
- getAuthStatus() {
34194
- return this.status;
34151
+ get status() {
34152
+ if (!this._status) {
34153
+ throw new Error("AuthStatus is not initialized");
34154
+ }
34155
+ return this._status;
34156
+ }
34157
+ /** Like {@link AuthProvider.status} but throws if not authed. */
34158
+ get statusAuthed() {
34159
+ if (!this._status) {
34160
+ throw new Error("AuthStatus is not initialized");
34161
+ }
34162
+ if (!this._status.authenticated) {
34163
+ throw new Error("Not authenticated");
34164
+ }
34165
+ return this._status;
34166
+ }
34167
+ /** Like {@link AuthProvider.status} but returns null instead of throwing if not ready. */
34168
+ get statusOrNotReadyYet() {
34169
+ return this._status;
34195
34170
  }
34196
34171
  // It processes the authentication steps and stores the login info before sharing the auth status with chatview
34197
34172
  async auth({
@@ -34201,8 +34176,12 @@ class AuthProvider {
34201
34176
  isExtensionStartup = false,
34202
34177
  isOfflineMode = false
34203
34178
  }) {
34179
+ const formattedEndpoint = formatURL(endpoint);
34180
+ if (!formattedEndpoint) {
34181
+ throw new Error(`invalid endpoint URL: ${JSON.stringify(endpoint)}`);
34182
+ }
34204
34183
  const config = {
34205
- serverEndpoint: formatURL(endpoint) ?? "",
34184
+ serverEndpoint: formattedEndpoint,
34206
34185
  accessToken: token,
34207
34186
  customHeaders: customHeaders || this.config.customHeaders
34208
34187
  };
@@ -34211,17 +34190,24 @@ class AuthProvider {
34211
34190
  if (!isOfflineMode) {
34212
34191
  await this.storeAuthInfo(config.serverEndpoint, config.accessToken);
34213
34192
  }
34214
- await commands$1.executeCommand("setContext", "cody.activated", authStatus.isLoggedIn);
34193
+ await commands$1.executeCommand(
34194
+ "setContext",
34195
+ "cody.activated",
34196
+ authStatus.authenticated
34197
+ );
34215
34198
  await this.setAuthStatus(authStatus);
34216
- if (isExtensionStartup && authStatus.isLoggedIn) {
34199
+ if (isExtensionStartup && authStatus.authenticated) {
34217
34200
  await this.setHasAuthenticatedBefore();
34218
- } else if (authStatus.isLoggedIn) {
34201
+ } else if (authStatus.authenticated) {
34219
34202
  this.handleFirstEverAuthentication();
34220
34203
  }
34221
34204
  return authStatus;
34222
34205
  } catch (error) {
34223
34206
  logDebug("AuthProvider:auth", "failed", error);
34224
- return await this.reloadAuthStatus().catch(() => unauthenticatedStatus);
34207
+ return await this.reloadAuthStatus().catch(() => ({
34208
+ authenticated: false,
34209
+ endpoint: config.serverEndpoint
34210
+ }));
34225
34211
  }
34226
34212
  }
34227
34213
  // Set auth status in case of reload
@@ -34236,13 +34222,10 @@ class AuthProvider {
34236
34222
  }
34237
34223
  // Set auth status and share it with chatview
34238
34224
  async setAuthStatus(authStatus) {
34239
- if (this.status === authStatus) {
34240
- return;
34241
- }
34242
- this.status = authStatus;
34243
- if (authStatus.endpoint === "init") {
34225
+ if (this._status === authStatus) {
34244
34226
  return;
34245
34227
  }
34228
+ this._status = authStatus;
34246
34229
  await this.updateAuthStatus(authStatus);
34247
34230
  }
34248
34231
  async updateAuthStatus(authStatus) {
@@ -34253,61 +34236,18 @@ class AuthProvider {
34253
34236
  } catch (error) {
34254
34237
  logDebug("AuthProvider", "updateAuthStatus error", error);
34255
34238
  } finally {
34256
- this.didChangeEvent.fire(this.getAuthStatus());
34239
+ this.didChangeEvent.fire(this.status);
34257
34240
  let eventValue;
34258
- if (authStatus.showNetworkError || authStatus.showInvalidAccessTokenError) {
34259
- eventValue = "failed";
34260
- } else if (authStatus.isLoggedIn) {
34241
+ if (authStatus.authenticated) {
34261
34242
  eventValue = "connected";
34243
+ } else if (authStatus.showNetworkError || authStatus.showInvalidAccessTokenError) {
34244
+ eventValue = "failed";
34262
34245
  } else {
34263
34246
  eventValue = "disconnected";
34264
34247
  }
34265
34248
  telemetryRecorder.recordEvent("cody.auth", eventValue);
34266
34249
  }
34267
34250
  }
34268
- // Register URI Handler (vscode://sourcegraph.cody-ai) for resolving token
34269
- // sending back from sourcegraph.com
34270
- async tokenCallbackHandler(uri2, customHeaders) {
34271
- closeAuthProgressIndicator();
34272
- const params = new URLSearchParams(uri2.query);
34273
- const token = params.get("code");
34274
- const endpoint = this.status.endpoint;
34275
- if (!token || !endpoint) {
34276
- return;
34277
- }
34278
- const authState = await this.auth({ endpoint, token, customHeaders });
34279
- telemetryRecorder.recordEvent("cody.auth.fromCallback.web", "succeeded", {
34280
- metadata: {
34281
- success: (authState == null ? void 0 : authState.isLoggedIn) ? 1 : 0
34282
- }
34283
- });
34284
- if (authState == null ? void 0 : authState.isLoggedIn) {
34285
- await window$1.showInformationMessage(`Signed in to ${endpoint}`);
34286
- } else {
34287
- await showAuthFailureMessage(endpoint);
34288
- }
34289
- }
34290
- /** Open callback URL in browser to get token from instance. */
34291
- redirectToEndpointLogin(uri2) {
34292
- const endpoint = formatURL(uri2);
34293
- if (!endpoint) {
34294
- return;
34295
- }
34296
- if (env.uiKind === UIKind.Web) {
34297
- const newTokenNoCallbackUrl = new URL("/user/settings/tokens/new", endpoint);
34298
- void env.openExternal(Uri.parse(newTokenNoCallbackUrl.href));
34299
- void this.signinMenuForInstanceUrl(endpoint);
34300
- return;
34301
- }
34302
- const newTokenCallbackUrl = new URL("/user/settings/tokens/new/callback", endpoint);
34303
- newTokenCallbackUrl.searchParams.append("requestFrom", getAuthReferralCode());
34304
- this.status.endpoint = endpoint;
34305
- void env.openExternal(Uri.parse(newTokenCallbackUrl.href));
34306
- }
34307
- // Refresh current endpoint history with the one from local storage
34308
- loadEndpointHistory() {
34309
- this.endpointHistory = localStorage.getEndpointHistory() || [];
34310
- }
34311
34251
  // Store endpoint in local storage, token in secret storage, and update endpoint history.
34312
34252
  async storeAuthInfo(endpoint, token) {
34313
34253
  if (!endpoint) {
@@ -34317,13 +34257,10 @@ class AuthProvider {
34317
34257
  if (token) {
34318
34258
  await secretStorage.storeToken(endpoint, token);
34319
34259
  }
34320
- this.loadEndpointHistory();
34321
34260
  }
34322
- // Notifies the AuthProvider that the simplified onboarding experiment is
34323
- // kicking off an authorization flow. That flow ends when (if) this
34324
- // AuthProvider gets a call to tokenCallbackHandler.
34325
- authProviderSimplifiedWillAttemptAuth() {
34326
- this.status.endpoint = DOTCOM_URL.toString();
34261
+ setAuthPendingToEndpoint(endpoint) {
34262
+ this._status = { authenticated: false, endpoint };
34263
+ this.didChangeEvent.fire(this._status);
34327
34264
  }
34328
34265
  // Logs a telemetry event if the user has never authenticated to Sourcegraph.
34329
34266
  handleFirstEverAuthentication() {
@@ -34339,42 +34276,6 @@ class AuthProvider {
34339
34276
  }
34340
34277
  }
34341
34278
  const authProvider = singletonNotYetSet();
34342
- function isNetworkError(error) {
34343
- const message = error.message;
34344
- return message.includes("ENOTFOUND") || message.includes("ECONNREFUSED") || message.includes("ECONNRESET") || message.includes("EHOSTUNREACH") || message.includes("ETIMEDOUT");
34345
- }
34346
- function formatURL(uri2) {
34347
- try {
34348
- if (!uri2) {
34349
- return null;
34350
- }
34351
- if (isSourcegraphToken(uri2)) {
34352
- throw new Error("Access Token is not a valid URL");
34353
- }
34354
- if (!uri2.startsWith("http")) {
34355
- uri2 = `https://${uri2}`;
34356
- }
34357
- const endpointUri = new URL(uri2);
34358
- return endpointUri.href;
34359
- } catch (error) {
34360
- console.error("Invalid URL: ", error);
34361
- return null;
34362
- }
34363
- }
34364
- async function showAuthResultMessage(endpoint, authStatus) {
34365
- if (authStatus == null ? void 0 : authStatus.isLoggedIn) {
34366
- const authority = Uri.parse(endpoint).authority;
34367
- await window$1.showInformationMessage(`Signed in to ${authority || endpoint}`);
34368
- } else {
34369
- await showAuthFailureMessage(endpoint);
34370
- }
34371
- }
34372
- async function showAuthFailureMessage(endpoint) {
34373
- const authority = Uri.parse(endpoint).authority;
34374
- await window$1.showErrorMessage(
34375
- `Authentication failed. Please ensure Cody is enabled for ${authority} and verify your email address if required.`
34376
- );
34377
- }
34378
34279
  const { platform, arch } = getOSArch();
34379
34280
  const getExtensionDetails = (config) => ({
34380
34281
  ide: config.agentIDE ?? CodyIDE.VSCode,
@@ -35097,7 +34998,7 @@ class RepoNameResolver {
35097
34998
  throw new Error("RepoNameResolver not initialized");
35098
34999
  }
35099
35000
  const uniqueRemoteUrls = Array.from(new Set(remoteUrls));
35100
- if (authProvider.instance.getAuthStatus().isDotCom) {
35001
+ if (isDotCom(authProvider.instance.status)) {
35101
35002
  return uniqueRemoteUrls.map(convertGitCloneURLToCodebaseName).filter(isDefined);
35102
35003
  }
35103
35004
  const repoNames = await Promise.all(
@@ -38454,18 +38355,30 @@ const languages = {
38454
38355
  ...cQueries,
38455
38356
  ...cppQueries
38456
38357
  };
38358
+ let cached;
38359
+ function isRunningInsideAgent() {
38360
+ if (cached === void 0) {
38361
+ cached = workspace.getConfiguration().get("cody.advanced.agent.running", false);
38362
+ }
38363
+ return cached;
38364
+ }
38457
38365
  class CompletionProviderConfig {
38458
38366
  constructor() {
38459
38367
  __publicField2(this, "_config");
38460
38368
  __publicField2(this, "flagsToResolve", [
38461
- FeatureFlag.CodyAutocompleteContextBfgMixed,
38462
38369
  FeatureFlag.CodyAutocompleteUserLatency,
38463
38370
  FeatureFlag.CodyAutocompleteTracing,
38464
38371
  FeatureFlag.CodyAutocompleteContextExtendLanguagePool,
38465
38372
  FeatureFlag.CodyAutocompletePreloadingExperimentBaseFeatureFlag,
38466
38373
  FeatureFlag.CodyAutocompletePreloadingExperimentVariant1,
38467
38374
  FeatureFlag.CodyAutocompletePreloadingExperimentVariant2,
38468
- FeatureFlag.CodyAutocompletePreloadingExperimentVariant3
38375
+ FeatureFlag.CodyAutocompletePreloadingExperimentVariant3,
38376
+ FeatureFlag.CodyAutocompleteContextExperimentBaseFeatureFlag,
38377
+ FeatureFlag.CodyAutocompleteContextExperimentVariant1,
38378
+ FeatureFlag.CodyAutocompleteContextExperimentVariant2,
38379
+ FeatureFlag.CodyAutocompleteContextExperimentVariant3,
38380
+ FeatureFlag.CodyAutocompleteContextExperimentVariant4,
38381
+ FeatureFlag.CodyAutocompleteContextExperimentControl
38469
38382
  ]);
38470
38383
  }
38471
38384
  get config() {
@@ -38506,9 +38419,49 @@ class CompletionProviderConfig {
38506
38419
  return "jaccard-similarity";
38507
38420
  case "new-jaccard-similarity":
38508
38421
  return "new-jaccard-similarity";
38422
+ case "recent-edits":
38423
+ return "recent-edits";
38424
+ case "recent-edits-1m":
38425
+ return "recent-edits-1m";
38426
+ case "recent-edits-5m":
38427
+ return "recent-edits-5m";
38428
+ case "recent-edits-mixed":
38429
+ return "recent-edits-mixed";
38509
38430
  default:
38510
- return this.getPrefetchedFlag(FeatureFlag.CodyAutocompleteContextBfgMixed) ? "bfg-mixed" : "jaccard-similarity";
38431
+ return this.experimentBasedContextStrategy();
38432
+ }
38433
+ }
38434
+ experimentBasedContextStrategy() {
38435
+ const defaultContextStrategy = "jaccard-similarity";
38436
+ const isContextExperimentFlagEnabled = this.getPrefetchedFlag(
38437
+ FeatureFlag.CodyAutocompleteContextExperimentBaseFeatureFlag
38438
+ );
38439
+ if (isRunningInsideAgent() || !isContextExperimentFlagEnabled) {
38440
+ return defaultContextStrategy;
38441
+ }
38442
+ const [variant1, variant2, variant3, variant4, control2] = [
38443
+ this.getPrefetchedFlag(FeatureFlag.CodyAutocompleteContextExperimentVariant1),
38444
+ this.getPrefetchedFlag(FeatureFlag.CodyAutocompleteContextExperimentVariant2),
38445
+ this.getPrefetchedFlag(FeatureFlag.CodyAutocompleteContextExperimentVariant3),
38446
+ this.getPrefetchedFlag(FeatureFlag.CodyAutocompleteContextExperimentVariant4),
38447
+ this.getPrefetchedFlag(FeatureFlag.CodyAutocompleteContextExperimentControl)
38448
+ ];
38449
+ if (variant1) {
38450
+ return "recent-edits-1m";
38451
+ }
38452
+ if (variant2) {
38453
+ return "recent-edits-5m";
38454
+ }
38455
+ if (variant3) {
38456
+ return "recent-edits-mixed";
38457
+ }
38458
+ if (variant4) {
38459
+ return "none";
38511
38460
  }
38461
+ if (control2) {
38462
+ return defaultContextStrategy;
38463
+ }
38464
+ return defaultContextStrategy;
38512
38465
  }
38513
38466
  getPreloadingExperimentGroup() {
38514
38467
  if (this.getPrefetchedFlag(FeatureFlag.CodyAutocompletePreloadingExperimentBaseFeatureFlag)) {
@@ -42858,7 +42811,7 @@ function logError(error) {
42858
42811
  }
42859
42812
  captureException(error);
42860
42813
  const message = error.message;
42861
- const traceId = isNetworkError$1(error) ? error.traceId : void 0;
42814
+ const traceId = isNetworkError(error) ? error.traceId : void 0;
42862
42815
  if (!errorCounts.has(message)) {
42863
42816
  errorCounts.set(message, 0);
42864
42817
  logCompletionErrorEvent({ message, traceId, count: 1 });
@@ -43289,13 +43242,6 @@ function getEditDefaultProvidedRange(document2, selection) {
43289
43242
  }
43290
43243
  return;
43291
43244
  }
43292
- let cached;
43293
- function isRunningInsideAgent() {
43294
- if (cached === void 0) {
43295
- cached = workspace.getConfiguration().get("cody.advanced.agent.running", false);
43296
- }
43297
- return cached;
43298
- }
43299
43245
  class ContentProvider {
43300
43246
  constructor() {
43301
43247
  // This stores the content of the document for each task ID
@@ -43976,7 +43922,6 @@ class AgentWebviewPanel {
43976
43922
  __publicField2(this, "panelID", v4());
43977
43923
  __publicField2(this, "chatID");
43978
43924
  // also known as `sessionID` in some parts of the Cody codebase
43979
- __publicField2(this, "models");
43980
43925
  __publicField2(this, "remoteRepos");
43981
43926
  __publicField2(this, "isInitialized", false);
43982
43927
  __publicField2(this, "isMessageInProgress");
@@ -43988,6 +43933,7 @@ class AgentWebviewPanel {
43988
43933
  __publicField2(this, "postMessage", new AgentEventEmitter());
43989
43934
  __publicField2(this, "onDidPostMessage", this.postMessage.event);
43990
43935
  __publicField2(this, "attributionResults", /* @__PURE__ */ new Map());
43936
+ __publicField2(this, "_extensionAPI");
43991
43937
  this.panel = defaultWebviewPanel({
43992
43938
  viewType,
43993
43939
  title,
@@ -44048,6 +43994,23 @@ class AgentWebviewPanel {
44048
43994
  get onDidChangeViewState() {
44049
43995
  return this.panel.onDidChangeViewState;
44050
43996
  }
43997
+ /**
43998
+ * Call an extension host API exposed to the "webview". See {@link WebviewToExtensionAPI}.
43999
+ */
44000
+ get extensionAPI() {
44001
+ if (!this._extensionAPI) {
44002
+ this._extensionAPI = createExtensionAPI(
44003
+ createMessageAPIForWebview({
44004
+ postMessage: (message) => this.receiveMessage.fire(message),
44005
+ onMessage: (callback) => {
44006
+ const disposable = this.onDidPostMessage(callback);
44007
+ return () => disposable.dispose();
44008
+ }
44009
+ })
44010
+ );
44011
+ }
44012
+ return this._extensionAPI;
44013
+ }
44051
44014
  reveal() {
44052
44015
  this.panel.reveal();
44053
44016
  }
@@ -44853,6 +44816,8 @@ class AgentTextEditor {
44853
44816
  );
44854
44817
  return selection;
44855
44818
  }
44819
+ set selection(newSelection) {
44820
+ }
44856
44821
  get selections() {
44857
44822
  return [this.selection];
44858
44823
  }
@@ -46702,17 +46667,60 @@ var define_process_default$7 = { env: {} };
46702
46667
  }).call(this);
46703
46668
  LocalStorage_2 = LocalStorage2;
46704
46669
  }).call(commonjsGlobal);
46670
+ async function migrateChatHistoryCODY3538(storage) {
46671
+ const hasMigrated = storage.get(MIGRATED_CHAT_HISTORY_KEY_CODY_3538);
46672
+ if (hasMigrated) {
46673
+ return;
46674
+ }
46675
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
46676
+ const history = storage.get(KEY_LOCAL_HISTORY, null);
46677
+ for (const accountHistory of Object.values(history ?? {})) {
46678
+ for (const [chatId, chat2] of Object.entries(accountHistory.chat)) {
46679
+ if (uuidRegex.test(chatId) || uuidRegex.test(chat2.lastInteractionTimestamp)) {
46680
+ let lastInteraction;
46681
+ const timestamp = Date.parse(chat2.lastInteractionTimestamp);
46682
+ if (Number.isNaN(timestamp)) {
46683
+ lastInteraction = /* @__PURE__ */ new Date();
46684
+ } else {
46685
+ lastInteraction = new Date(timestamp);
46686
+ }
46687
+ const newId = lastInteraction.toUTCString();
46688
+ chat2.id = newId;
46689
+ chat2.lastInteractionTimestamp = newId;
46690
+ delete accountHistory.chat[chatId];
46691
+ accountHistory.chat[newId] = chat2;
46692
+ }
46693
+ }
46694
+ }
46695
+ await storage.update(KEY_LOCAL_HISTORY, history);
46696
+ await storage.update(MIGRATED_CHAT_HISTORY_KEY_CODY_3538, true);
46697
+ }
46698
+ const MIGRATED_CHAT_HISTORY_KEY_CODY_3538 = "migrated-chat-history-cody-3538";
46699
+ const KEY_LOCAL_HISTORY = "cody-local-chatHistory-v2";
46700
+ async function migrate(storage) {
46701
+ await migrateChatHistoryCODY3538(storage);
46702
+ }
46705
46703
  class AgentGlobalState {
46706
- constructor(ide, dir) {
46704
+ constructor(ide, manager, dir) {
46707
46705
  __publicField2(this, "db");
46706
+ this.manager = manager;
46708
46707
  if (dir) {
46709
46708
  this.db = new LocalStorageDB(ide, dir);
46710
46709
  } else {
46711
46710
  this.db = new InMemoryDB();
46712
46711
  }
46713
- this.set("notification.setupDismissed", "true");
46714
- this.set("completion.inline.hasAcceptedFirstCompletion", true);
46715
- this.set("extension.hasActivatedPreviously", "true");
46712
+ if (manager === "client") {
46713
+ this.set("notification.setupDismissed", "true");
46714
+ this.set("completion.inline.hasAcceptedFirstCompletion", true);
46715
+ this.set("extension.hasActivatedPreviously", "true");
46716
+ }
46717
+ }
46718
+ static async initialize(ide, dir) {
46719
+ const globalState = new AgentGlobalState(ide, dir ? "server" : "client", dir);
46720
+ if (globalState.db instanceof LocalStorageDB) {
46721
+ await migrate(globalState);
46722
+ }
46723
+ return globalState;
46716
46724
  }
46717
46725
  set(key, value) {
46718
46726
  this.db.set(key, value);
@@ -46723,9 +46731,15 @@ class AgentGlobalState {
46723
46731
  }
46724
46732
  }
46725
46733
  keys() {
46734
+ if (this.manager === "server") {
46735
+ return this.db.keys();
46736
+ }
46726
46737
  return [localStorage.LAST_USED_ENDPOINT, localStorage.ANONYMOUS_USER_ID_KEY, ...this.db.keys()];
46727
46738
  }
46728
46739
  get(key, defaultValue) {
46740
+ if (this.manager === "server") {
46741
+ return this.db.get(key) ?? defaultValue;
46742
+ }
46729
46743
  switch (key) {
46730
46744
  case localStorage.LAST_USED_ENDPOINT:
46731
46745
  return extensionConfiguration == null ? void 0 : extensionConfiguration.serverEndpoint;
@@ -46799,6 +46813,10 @@ class MessageHandler {
46799
46813
  __publicField2(this, "requestHandlers", /* @__PURE__ */ new Map());
46800
46814
  __publicField2(this, "notificationHandlers", /* @__PURE__ */ new Map());
46801
46815
  __publicField2(this, "disposables", []);
46816
+ /*<M extends keyof WebviewToExtensionAPI>(
46817
+ method: M,
46818
+ ...args: Parameters<WebviewToExtensionAPI[M]>
46819
+ ): ReturnType<WebviewToExtensionAPI[M]> {}*/
46802
46820
  __publicField2(this, "alive", true);
46803
46821
  this.conn = conn2;
46804
46822
  this.disposables.push(
@@ -47061,7 +47079,7 @@ class Agent extends MessageHandler {
47061
47079
  "*",
47062
47080
  new IndentationBasedFoldingRangeProvider()
47063
47081
  );
47064
- this.globalState = this.newGlobalState(clientInfo2);
47082
+ this.globalState = await this.newGlobalState(clientInfo2);
47065
47083
  if (clientInfo2.capabilities && ((_a3 = clientInfo2.capabilities) == null ? void 0 : _a3.webview) === void 0) {
47066
47084
  clientInfo2.capabilities.webview = "agentic";
47067
47085
  }
@@ -47143,8 +47161,7 @@ class Agent extends MessageHandler {
47143
47161
  return {
47144
47162
  name: "cody-agent",
47145
47163
  authenticated: authStatus == null ? void 0 : authStatus.authenticated,
47146
- codyEnabled: authStatus == null ? void 0 : authStatus.siteHasCodyEnabled,
47147
- codyVersion: authStatus == null ? void 0 : authStatus.siteVersion,
47164
+ codyVersion: (authStatus == null ? void 0 : authStatus.authenticated) ? authStatus.siteVersion : void 0,
47148
47165
  authStatus
47149
47166
  };
47150
47167
  } catch (error) {
@@ -47801,6 +47818,9 @@ class Agent extends MessageHandler {
47801
47818
  });
47802
47819
  this.registerAuthenticatedRequest("chat/restore", async ({ modelID, messages, chatID }) => {
47803
47820
  const authStatus = await commands$1.executeCommand("cody.auth.status");
47821
+ if (!authStatus.authenticated) {
47822
+ throw new Error("Not authenticated");
47823
+ }
47804
47824
  modelID ?? (modelID = modelsService.instance.getDefaultChatModel() ?? "");
47805
47825
  const chatMessages = (messages == null ? void 0 : messages.map(PromptString.unsafe_deserializeChatMessage)) ?? [];
47806
47826
  const chatModel = new ChatModel(modelID, chatID, chatMessages);
@@ -47819,6 +47839,9 @@ class Agent extends MessageHandler {
47819
47839
  this.registerAuthenticatedRequest("chat/export", async (input) => {
47820
47840
  const { fullHistory = false } = input ?? {};
47821
47841
  const authStatus = await commands$1.executeCommand("cody.auth.status");
47842
+ if (!authStatus.authenticated) {
47843
+ throw new Error("Not authenticated");
47844
+ }
47822
47845
  const localHistory = chatHistory.getLocalHistory(authStatus);
47823
47846
  if (localHistory != null) {
47824
47847
  return Object.entries(localHistory == null ? void 0 : localHistory.chat).filter(
@@ -47844,6 +47867,9 @@ class Agent extends MessageHandler {
47844
47867
  id: params2.chatId
47845
47868
  });
47846
47869
  const authStatus = await commands$1.executeCommand("cody.auth.status");
47870
+ if (!authStatus.authenticated) {
47871
+ throw new Error("Not authenticated");
47872
+ }
47847
47873
  const localHistory = await chatHistory.getLocalHistory(authStatus);
47848
47874
  if (localHistory != null) {
47849
47875
  return Object.entries(localHistory == null ? void 0 : localHistory.chat).map(([chatID, chatTranscript]) => ({
@@ -47860,6 +47886,11 @@ class Agent extends MessageHandler {
47860
47886
  });
47861
47887
  return { remoteRepos: panel2.remoteRepos };
47862
47888
  });
47889
+ this.registerAuthenticatedRequest("chat/setModel", async ({ id, model: model2 }) => {
47890
+ const panel2 = this.webPanels.getPanelOrError(id);
47891
+ await waitUntilComplete(panel2.extensionAPI.setChatModel(model2));
47892
+ return null;
47893
+ });
47863
47894
  const submitOrEditHandler = async ({ id, message }, token) => {
47864
47895
  if (message.command !== "submit" && message.command !== "edit") {
47865
47896
  throw new Error('Invalid message, must have a command of "submit"');
@@ -47985,18 +48016,18 @@ class Agent extends MessageHandler {
47985
48016
  pendingPromise.finally(() => this.pendingPromises.delete(pendingPromise));
47986
48017
  }
47987
48018
  }
47988
- newGlobalState(clientInfo2) {
48019
+ async newGlobalState(clientInfo2) {
47989
48020
  var _a3;
47990
48021
  switch ((_a3 = clientInfo2.capabilities) == null ? void 0 : _a3.globalState) {
47991
48022
  case "server-managed":
47992
- return new AgentGlobalState(
48023
+ return AgentGlobalState.initialize(
47993
48024
  clientInfo2.name,
47994
48025
  clientInfo2.globalStateDir ?? codyPaths().data
47995
48026
  );
47996
48027
  case "client-managed":
47997
48028
  throw new Error("client-managed global state is not supported");
47998
48029
  default:
47999
- return new AgentGlobalState(clientInfo2.name);
48030
+ return AgentGlobalState.initialize(clientInfo2.name);
48000
48031
  }
48001
48032
  }
48002
48033
  createFixupControlApplicator(files) {
@@ -48029,6 +48060,10 @@ class Agent extends MessageHandler {
48029
48060
  var _a3;
48030
48061
  return ((_a3 = this.clientInfo) == null ? void 0 : _a3.name.toLowerCase()) || "uninitialized-agent";
48031
48062
  }
48063
+ get httpClientNameForLegacyReasons() {
48064
+ var _a3;
48065
+ return ((_a3 = this.clientInfo) == null ? void 0 : _a3.legacyNameForServerIdentification) ?? void 0;
48066
+ }
48032
48067
  get clientVersion() {
48033
48068
  var _a3;
48034
48069
  return ((_a3 = this.clientInfo) == null ? void 0 : _a3.version) || "0.0.0";
@@ -48175,8 +48210,6 @@ class Agent extends MessageHandler {
48175
48210
  panel2.isMessageInProgress = message.isMessageInProgress;
48176
48211
  panel2.messageInProgressChange.fire(message);
48177
48212
  }
48178
- } else if (message.type === "chatModels") {
48179
- panel2.models = message.models;
48180
48213
  } else if (message.type === "context/remote-repos") {
48181
48214
  panel2.remoteRepos = message.repos;
48182
48215
  } else if (message.type === "errors") {
@@ -49431,7 +49464,7 @@ class CommandsProvider {
49431
49464
  * Used for retreiving context for the command field in custom command
49432
49465
  */
49433
49466
  async runShell(shell2) {
49434
- const { getContextFileFromShell } = await import("./shell-CvNNoU2J.mjs");
49467
+ const { getContextFileFromShell } = await import("./shell-CWTEC0Ll.mjs");
49435
49468
  return getContextFileFromShell(shell2);
49436
49469
  }
49437
49470
  /**
@@ -49442,7 +49475,7 @@ class CommandsProvider {
49442
49475
  if (!isFileURI(uri2)) {
49443
49476
  throw new Error("history only supported on local file paths");
49444
49477
  }
49445
- const { getContextFileFromGitLog } = await import("./git-log-CKjP84c8.mjs");
49478
+ const { getContextFileFromGitLog } = await import("./git-log-PGCFF8k9.mjs");
49446
49479
  return getContextFileFromGitLog(uri2, options);
49447
49480
  }
49448
49481
  dispose() {
@@ -49526,6 +49559,66 @@ class ExtensionApi {
49526
49559
  this.extensionMode = extensionMode;
49527
49560
  }
49528
49561
  }
49562
+ async function showAccountMenu() {
49563
+ const authStatus = authProvider.instance.statusAuthed;
49564
+ const selected = await openAccountMenuFirstStep(authStatus);
49565
+ if (selected === void 0) {
49566
+ return;
49567
+ }
49568
+ switch (selected) {
49569
+ case "Manage Account": {
49570
+ const uri2 = Uri.parse(ACCOUNT_USAGE_URL.toString()).with({
49571
+ query: `cody_client_user=${encodeURIComponent(authStatus.username)}`
49572
+ });
49573
+ void env.openExternal(uri2);
49574
+ break;
49575
+ }
49576
+ case "Switch Account...":
49577
+ await showSignInMenu();
49578
+ break;
49579
+ case "Sign Out":
49580
+ await showSignOutMenu();
49581
+ break;
49582
+ }
49583
+ }
49584
+ async function openAccountMenuFirstStep(authStatus) {
49585
+ const isOffline = !!authStatus.isOfflineMode;
49586
+ const isDotComInstance = isDotCom(authStatus.endpoint) && !isOffline;
49587
+ const displayName2 = authStatus.displayName || authStatus.username;
49588
+ const email = authStatus.primaryEmail || "No Email";
49589
+ const username = authStatus.username || authStatus.displayName;
49590
+ const planDetail = `Plan: ${authStatus.userCanUpgrade ? "Cody Free" : "Cody Pro"}`;
49591
+ const enterpriseDetail = `Enterprise Instance:
49592
+ ${authStatus.endpoint}`;
49593
+ const offlineDetail = "Use Cody offline with Ollama";
49594
+ const options = isDotComInstance ? [
49595
+ "Manage Account"
49596
+ /* Manage */
49597
+ ] : [];
49598
+ options.push(
49599
+ "Switch Account...",
49600
+ "Sign Out"
49601
+ /* SignOut */
49602
+ );
49603
+ const messageOptions = {
49604
+ modal: true,
49605
+ detail: isOffline ? offlineDetail : isDotComInstance ? planDetail : enterpriseDetail
49606
+ };
49607
+ const online = isDotComInstance ? `Signed in as ${displayName2} (${email})` : `Signed in as @${username}`;
49608
+ const offline = "Offline Mode";
49609
+ const message = isOffline ? offline : online;
49610
+ const option = await window$1.showInformationMessage(message, messageOptions, ...options);
49611
+ switch (option !== void 0) {
49612
+ case (option == null ? void 0 : option.startsWith("Sign Out")):
49613
+ return "Sign Out";
49614
+ case (option == null ? void 0 : option.startsWith("Manage")):
49615
+ return "Manage Account";
49616
+ case (option == null ? void 0 : option.startsWith("Switch")):
49617
+ return "Switch Account...";
49618
+ default:
49619
+ return void 0;
49620
+ }
49621
+ }
49529
49622
  const executeSmartApply = async (args2) => {
49530
49623
  return commands$1.executeCommand("cody.command.smart-apply", args2);
49531
49624
  };
@@ -49602,13 +49695,16 @@ async function handleCodeFromInsertAtCursor(text) {
49602
49695
  throw new Error("No editor or selection found to insert text");
49603
49696
  }
49604
49697
  const edit2 = new AgentWorkspaceEdit();
49605
- edit2.insert(activeEditor.document.uri, selectionRange.start, `${text}
49606
- `);
49698
+ if (selectionRange.isEmpty) {
49699
+ edit2.insert(activeEditor.document.uri, selectionRange.start, text.trimEnd());
49700
+ } else {
49701
+ edit2.replace(activeEditor.document.uri, selectionRange, text.trimEnd());
49702
+ }
49607
49703
  setLastStoredCode(text, "insertButton");
49608
49704
  await workspace.applyEdit(edit2);
49609
49705
  }
49610
49706
  function getSmartApplyModel(authStatus) {
49611
- if (!authStatus.isDotCom) {
49707
+ if (!isDotCom(authStatus)) {
49612
49708
  return;
49613
49709
  }
49614
49710
  return "anthropic/claude-3-5-sonnet-20240620";
@@ -52866,7 +52962,16 @@ async function getRepositoryMentions(query2, providerId) {
52866
52962
  }
52867
52963
  const repositories = dataOrError.search.results.repositories;
52868
52964
  const fzf = new Fzf(repositories, REPO_FZF_OPTIONS);
52869
- return fzf.find(cleanRegex(query2)).map((repository2) => createRepositoryMention(repository2.item, providerId));
52965
+ const localRepos = await (workspaceReposMonitor == null ? void 0 : workspaceReposMonitor.getRepoMetadata()) || [];
52966
+ return fzf.find(cleanRegex(query2)).map(
52967
+ (repository2) => createRepositoryMention(
52968
+ {
52969
+ ...repository2.item,
52970
+ current: !!localRepos.find(({ repoName }) => repoName === repository2.item.name)
52971
+ },
52972
+ providerId
52973
+ )
52974
+ );
52870
52975
  }
52871
52976
  function createRepositoryMention(repo, providerId) {
52872
52977
  return {
@@ -52876,7 +52981,7 @@ function createRepositoryMention(repo, providerId) {
52876
52981
  // By default, we show <title> <uri> in the mentions' menu.
52877
52982
  // As repo.url and repo.name are almost same, we do not want to show the uri.
52878
52983
  // So that is why we are setting the description to " " string.
52879
- description: " ",
52984
+ description: repo.current ? "Current" : " ",
52880
52985
  data: {
52881
52986
  repoId: repo.id,
52882
52987
  repoName: repo.name,
@@ -52938,21 +53043,25 @@ function getMentionMenuData(query2, chatModel) {
52938
53043
  }
52939
53044
  async function getChatContextItemsForMention(options, _2) {
52940
53045
  const MAX_RESULTS = 20;
52941
- const { mentionQuery, telemetryRecorder: telemetryRecorder2, remoteRepositoriesNames, rangeFilter = true } = options;
53046
+ const { mentionQuery, telemetryRecorder: telemetryRecorder2, rangeFilter = true } = options;
52942
53047
  switch (mentionQuery.provider) {
52943
53048
  case null:
52944
53049
  telemetryRecorder2 == null ? void 0 : telemetryRecorder2.empty();
52945
53050
  return getOpenTabsContextFile();
52946
53051
  case SYMBOL_CONTEXT_MENTION_PROVIDER.id:
52947
53052
  telemetryRecorder2 == null ? void 0 : telemetryRecorder2.withProvider(mentionQuery.provider);
52948
- return getSymbolContextFiles(mentionQuery.text, MAX_RESULTS, remoteRepositoriesNames);
53053
+ return getSymbolContextFiles(
53054
+ mentionQuery.text,
53055
+ MAX_RESULTS,
53056
+ mentionQuery.contextRemoteRepositoriesNames
53057
+ );
52949
53058
  case FILE_CONTEXT_MENTION_PROVIDER.id: {
52950
53059
  telemetryRecorder2 == null ? void 0 : telemetryRecorder2.withProvider(mentionQuery.provider);
52951
53060
  const files = mentionQuery.text ? await getFileContextFiles({
52952
53061
  query: mentionQuery.text,
52953
53062
  range: mentionQuery.range,
52954
53063
  maxResults: MAX_RESULTS,
52955
- repositoriesNames: remoteRepositoriesNames
53064
+ repositoriesNames: mentionQuery.contextRemoteRepositoriesNames
52956
53065
  }) : await getOpenTabsContextFile();
52957
53066
  if (mentionQuery.range && files.length > 0 && rangeFilter) {
52958
53067
  const item = await getContextFileFromUri(
@@ -52969,7 +53078,7 @@ async function getChatContextItemsForMention(options, _2) {
52969
53078
  return [];
52970
53079
  }
52971
53080
  const items = await openCtx.controller.mentions(
52972
- { query: mentionQuery.text },
53081
+ { query: mentionQuery.text, ...await getActiveEditorContextForOpenCtxMentions() },
52973
53082
  // get mention items for the selected provider only.
52974
53083
  { providerUri: mentionQuery.provider }
52975
53084
  );
@@ -52979,6 +53088,13 @@ async function getChatContextItemsForMention(options, _2) {
52979
53088
  }
52980
53089
  }
52981
53090
  }
53091
+ async function getActiveEditorContextForOpenCtxMentions() {
53092
+ var _a3, _b2, _c2;
53093
+ const uri2 = (_b2 = (_a3 = window$1.activeTextEditor) == null ? void 0 : _a3.document.uri) == null ? void 0 : _b2.toString();
53094
+ const activeWorkspaceURI = uri2 && (workspaceReposMonitor == null ? void 0 : workspaceReposMonitor.getFolderURIs().find((folderURI) => uri2 == null ? void 0 : uri2.startsWith(folderURI.toString())));
53095
+ const codebase = activeWorkspaceURI && ((_c2 = (await fetchRepoMetadataForFolder(activeWorkspaceURI))[0]) == null ? void 0 : _c2.repoName);
53096
+ return { uri: uri2, codebase };
53097
+ }
52982
53098
  function contextItemMentionFromOpenCtxItem(item) {
52983
53099
  var _a3;
52984
53100
  const isIgnored = (_a3 = item.data) == null ? void 0 : _a3.isIgnored;
@@ -53059,7 +53175,7 @@ function startClientStateBroadcaster({
53059
53175
  return Disposable.from(...disposables);
53060
53176
  }
53061
53177
  async function getCorpusContextItemsForEditorState(useRemote) {
53062
- var _a3;
53178
+ var _a3, _b2, _c2;
53063
53179
  const items = [];
53064
53180
  if (useRemote && workspaceReposMonitor) {
53065
53181
  const repoMetadata = await workspaceReposMonitor.getRepoMetadata();
@@ -53103,7 +53219,27 @@ async function getCorpusContextItemsForEditorState(useRemote) {
53103
53219
  });
53104
53220
  }
53105
53221
  }
53106
- return items;
53222
+ const providers = (_c2 = await ((_b2 = openCtx.controller) == null ? void 0 : _b2.meta({}))) == null ? void 0 : _c2.filter((meta) => {
53223
+ var _a4;
53224
+ return (_a4 = meta.mentions) == null ? void 0 : _a4.autoInclude;
53225
+ });
53226
+ if (!providers) {
53227
+ return items;
53228
+ }
53229
+ const activeEditorContext = await getActiveEditorContextForOpenCtxMentions();
53230
+ const openctxMentions = (await Promise.all(
53231
+ providers.map(async (provider) => {
53232
+ var _a4, _b3;
53233
+ const mentions = await ((_b3 = (_a4 = openCtx) == null ? void 0 : _a4.controller) == null ? void 0 : _b3.mentions(activeEditorContext, provider)) || [];
53234
+ return mentions.map((mention) => ({
53235
+ ...mention,
53236
+ provider: "openctx",
53237
+ type: "openctx",
53238
+ uri: URI.parse(mention.uri)
53239
+ }));
53240
+ })
53241
+ )).flat();
53242
+ return [...items, ...openctxMentions];
53107
53243
  }
53108
53244
  function idempotentPostMessage(rawPostMessage) {
53109
53245
  let lastMessage;
@@ -53363,7 +53499,7 @@ async function retrieveContextGracefully(promise, strategy) {
53363
53499
  logError$1("ChatController", `resolveContext > ${strategy}' (aborted)`);
53364
53500
  throw error;
53365
53501
  }
53366
- logError$1("ChatController", `resolveContext > ${strategy}' (error)`, error);
53502
+ logError$1("ChatController", `resolveContext > ${strategy} (error)`, error);
53367
53503
  return [];
53368
53504
  } finally {
53369
53505
  logDebug("ChatController", `resolveContext > ${strategy} (end)`);
@@ -54055,7 +54191,7 @@ class AuthDependentRetrievers {
54055
54191
  return workspace.getConfiguration().get("cody.advanced.agent.ide") === CodyIDE.Web;
54056
54192
  }
54057
54193
  isConsumer() {
54058
- return authProvider.instance.getAuthStatus().isDotCom;
54194
+ return isDotCom(authProvider.instance.status);
54059
54195
  }
54060
54196
  allowRemoteContext() {
54061
54197
  return this.isCodyWeb() || !this.isConsumer();
@@ -54080,7 +54216,8 @@ class ChatController {
54080
54216
  startTokenReceiver,
54081
54217
  contextAPIClient,
54082
54218
  contextRetriever,
54083
- extensionClient
54219
+ extensionClient,
54220
+ configWatcher
54084
54221
  }) {
54085
54222
  __publicField2(this, "chatModel");
54086
54223
  __publicField2(this, "chatClient");
@@ -54091,6 +54228,7 @@ class ChatController {
54091
54228
  __publicField2(this, "guardrails");
54092
54229
  __publicField2(this, "startTokenReceiver");
54093
54230
  __publicField2(this, "contextAPIClient");
54231
+ __publicField2(this, "configWatcher");
54094
54232
  __publicField2(this, "disposables", []);
54095
54233
  __publicField2(this, "initDoer", new InitDoer());
54096
54234
  __publicField2(this, "submitOrEditOperation");
@@ -54107,6 +54245,7 @@ class ChatController {
54107
54245
  this.editor = editor;
54108
54246
  this.extensionClient = extensionClient;
54109
54247
  this.contextRetriever = contextRetriever;
54248
+ this.configWatcher = configWatcher;
54110
54249
  this.chatModel = new ChatModel(getDefaultModelID());
54111
54250
  this.guardrails = guardrails;
54112
54251
  this.startTokenReceiver = startTokenReceiver;
@@ -54178,13 +54317,6 @@ class ChatController {
54178
54317
  case "abort":
54179
54318
  this.handleAbort();
54180
54319
  break;
54181
- case "chatModel":
54182
- await modelsService.instance.setSelectedModel(ModelUsage.Chat, message.model);
54183
- this.handleSetChatModel(message.model);
54184
- break;
54185
- case "get-chat-models":
54186
- this.postChatModels();
54187
- break;
54188
54320
  case "getUserContext": {
54189
54321
  const result = await getChatContextItemsForMention({
54190
54322
  mentionQuery: parseMentionQuery(message.query, null)
@@ -54205,7 +54337,7 @@ class ChatController {
54205
54337
  await handleSmartApply(
54206
54338
  message.id,
54207
54339
  message.code,
54208
- authProvider.instance.getAuthStatus(),
54340
+ authProvider.instance.status,
54209
54341
  message.instruction,
54210
54342
  message.fileName
54211
54343
  );
@@ -54290,7 +54422,7 @@ class ChatController {
54290
54422
  break;
54291
54423
  case "auth": {
54292
54424
  if (message.authKind === "callback" && message.endpoint) {
54293
- authProvider.instance.redirectToEndpointLogin(message.endpoint);
54425
+ redirectToEndpointLogin(message.endpoint);
54294
54426
  break;
54295
54427
  }
54296
54428
  if (message.authKind === "offline") {
@@ -54313,11 +54445,11 @@ class ChatController {
54313
54445
  "succeeded",
54314
54446
  {
54315
54447
  metadata: {
54316
- success: (authStatus == null ? void 0 : authStatus.isLoggedIn) ? 1 : 0
54448
+ success: (authStatus == null ? void 0 : authStatus.authenticated) ? 1 : 0
54317
54449
  }
54318
54450
  }
54319
54451
  );
54320
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
54452
+ if (!(authStatus == null ? void 0 : authStatus.authenticated)) {
54321
54453
  void window$1.showErrorMessage(
54322
54454
  "Authentication failed. Please check your token and try again."
54323
54455
  );
@@ -54343,7 +54475,7 @@ class ChatController {
54343
54475
  break;
54344
54476
  }
54345
54477
  if (message.authKind === "signout") {
54346
- await authProvider.instance.signoutMenu();
54478
+ await showSignOutMenu();
54347
54479
  this.setWebviewView(View.Login);
54348
54480
  break;
54349
54481
  }
@@ -54360,7 +54492,7 @@ class ChatController {
54360
54492
  endpoint: DOTCOM_URL.href,
54361
54493
  token
54362
54494
  });
54363
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
54495
+ if (!(authStatus == null ? void 0 : authStatus.authenticated)) {
54364
54496
  void window$1.showErrorMessage(
54365
54497
  "Authentication failed. Please check your token and try again."
54366
54498
  );
@@ -54372,10 +54504,10 @@ class ChatController {
54372
54504
  }
54373
54505
  case "troubleshoot/reloadAuth": {
54374
54506
  await authProvider.instance.reloadAuthStatus();
54375
- const nextAuth = authProvider.instance.getAuthStatus();
54507
+ const nextAuth = authProvider.instance.status;
54376
54508
  telemetryRecorder.recordEvent("cody.troubleshoot", "reloadAuth", {
54377
54509
  metadata: {
54378
- success: nextAuth.isLoggedIn ? 1 : 0
54510
+ success: nextAuth.authenticated ? 1 : 0
54379
54511
  }
54380
54512
  });
54381
54513
  break;
@@ -54409,8 +54541,8 @@ class ChatController {
54409
54541
  // =======================================================================
54410
54542
  setAuthStatus(status) {
54411
54543
  void this.sendConfig();
54412
- if (status.isLoggedIn) {
54413
- this.handleSetChatModel(getDefaultModelID());
54544
+ if (status.authenticated) {
54545
+ this.chatModel.updateModel(getDefaultModelID());
54414
54546
  }
54415
54547
  }
54416
54548
  // When the webview sends the 'ready' message, respond by posting the view config
@@ -54419,7 +54551,7 @@ class ChatController {
54419
54551
  }
54420
54552
  async sendConfig() {
54421
54553
  var _a3;
54422
- const authStatus = authProvider.instance.getAuthStatus();
54554
+ const authStatus = authProvider.instance.status;
54423
54555
  const configForWebview = await this.getConfigForWebview();
54424
54556
  const workspaceFolderUris = ((_a3 = workspace.workspaceFolders) == null ? void 0 : _a3.map((folder2) => folder2.uri.toString())) ?? [];
54425
54557
  const clientConfig = await ClientConfigSingleton.getInstance().getConfig();
@@ -54436,7 +54568,8 @@ class ChatController {
54436
54568
  chat: (clientConfig == null ? void 0 : clientConfig.chatEnabled) ?? true,
54437
54569
  attribution: (clientConfig == null ? void 0 : clientConfig.attributionEnabled) ?? false,
54438
54570
  serverSentModels: (clientConfig == null ? void 0 : clientConfig.modelsAPIEnabled) ?? false
54439
- }
54571
+ },
54572
+ isDotComUser: isDotCom(authStatus)
54440
54573
  });
54441
54574
  logDebug("ChatController", "updateViewConfig", {
54442
54575
  verbose: configForWebview
@@ -54450,7 +54583,7 @@ class ChatController {
54450
54583
  isMessageInProgress: false,
54451
54584
  chatID: this.chatModel.sessionID
54452
54585
  }));
54453
- this.handleSetChatModel(this.chatModel.modelID);
54586
+ this.chatModel.updateModel(this.chatModel.modelID);
54454
54587
  await this.saveSession();
54455
54588
  this.initDoer.signalInitialized();
54456
54589
  await this.sendConfig();
@@ -54461,7 +54594,7 @@ class ChatController {
54461
54594
  async handleUserMessageSubmission(requestID, inputText, submitType, mentions, editorState, legacyAddEnhancedContext, signal2, source, command) {
54462
54595
  return tracer.startActiveSpan("chat.submit", async (span2) => {
54463
54596
  span2.setAttribute("sampled", true);
54464
- const authStatus = authProvider.instance.getAuthStatus();
54597
+ const authStatus = authProvider.instance.statusAuthed;
54465
54598
  const sharedProperties = {
54466
54599
  requestID,
54467
54600
  chatModel: this.chatModel.modelID,
@@ -54526,6 +54659,7 @@ class ChatController {
54526
54659
  prompter2,
54527
54660
  signal2,
54528
54661
  requestID,
54662
+ authStatus.codyApiVersion,
54529
54663
  contextAlternatives
54530
54664
  );
54531
54665
  void this.sendChatExecutedTelemetry(
@@ -54554,7 +54688,7 @@ class ChatController {
54554
54688
  });
54555
54689
  }
54556
54690
  async sendChatExecutedTelemetry(span2, firstTokenSpan, inputText, sharedProperties, context2) {
54557
- const authStatus = authProvider.instance.getAuthStatus();
54691
+ const authStatus = authProvider.instance.status;
54558
54692
  const contextSummary = {};
54559
54693
  for (const { source } of context2.used) {
54560
54694
  if (!source) {
@@ -54578,7 +54712,7 @@ class ChatController {
54578
54712
  ...contextSummary,
54579
54713
  // Flag indicating this is a transcript event to go through ML data pipeline. Only for DotCom users
54580
54714
  // See https://github.com/sourcegraph/sourcegraph/pull/59524
54581
- recordsPrivateMetadataTranscript: authStatus.isDotCom ? 1 : 0
54715
+ recordsPrivateMetadataTranscript: isDotCom(authStatus) ? 1 : 0
54582
54716
  },
54583
54717
  privateMetadata: {
54584
54718
  properties: properties2,
@@ -54586,7 +54720,7 @@ class ChatController {
54586
54720
  // 🚨 SECURITY: chat transcripts are to be included only for DotCom users AND for V2 telemetry
54587
54721
  // V2 telemetry exports privateMetadata only for DotCom users
54588
54722
  // the condition below is an additional safeguard measure
54589
- promptText: authStatus.isDotCom && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET)
54723
+ promptText: isDotCom(authStatus) && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET)
54590
54724
  }
54591
54725
  });
54592
54726
  }
@@ -54612,7 +54746,7 @@ class ChatController {
54612
54746
  ]);
54613
54747
  const resolvedExplicitMentionsPromise = resolveContextItems(
54614
54748
  this.editor,
54615
- [structuredMentions.symbols, structuredMentions.files].flat(),
54749
+ [structuredMentions.symbols, structuredMentions.files, structuredMentions.openCtx].flat(),
54616
54750
  text,
54617
54751
  signal2
54618
54752
  );
@@ -54710,10 +54844,6 @@ class ChatController {
54710
54844
  this.postViewTranscript();
54711
54845
  telemetryRecorder.recordEvent("cody.sidebar.abortButton", "clicked");
54712
54846
  }
54713
- handleSetChatModel(modelID) {
54714
- this.chatModel.updateModel(modelID);
54715
- this.postChatModels();
54716
- }
54717
54847
  async handleGetUserEditorContext(uri2) {
54718
54848
  var _a3;
54719
54849
  const selection = (_a3 = window$1.activeTextEditor) == null ? void 0 : _a3.selection;
@@ -54813,17 +54943,6 @@ class ChatController {
54813
54943
  void this.postMessage({ type: "errors", errors: error.message });
54814
54944
  captureException(error);
54815
54945
  }
54816
- postChatModels() {
54817
- const authStatus = authProvider.instance.getAuthStatus();
54818
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
54819
- return;
54820
- }
54821
- const models = modelsService.instance.getModels(ModelUsage.Chat);
54822
- void this.postMessage({
54823
- type: "chatModels",
54824
- models
54825
- });
54826
- }
54827
54946
  /**
54828
54947
  * Low-level utility to post a message to the webview, pending initialization.
54829
54948
  *
@@ -54843,20 +54962,16 @@ class ChatController {
54843
54962
  /**
54844
54963
  * Constructs the prompt and updates the UI with the context used in the prompt.
54845
54964
  */
54846
- async buildPrompt(prompter2, abortSignal, requestID, contextAlternatives) {
54965
+ async buildPrompt(prompter2, abortSignal, requestID, codyApiVersion, contextAlternatives) {
54847
54966
  var _a3;
54848
- const { prompt, context: context2 } = await prompter2.makePrompt(
54849
- this.chatModel,
54850
- authProvider.instance.getAuthStatus().codyApiVersion
54851
- );
54967
+ const { prompt, context: context2 } = await prompter2.makePrompt(this.chatModel, codyApiVersion);
54852
54968
  abortSignal.throwIfAborted();
54853
54969
  this.chatModel.setLastMessageContext([...context2.used, ...context2.ignored], contextAlternatives);
54854
54970
  (_a3 = this.contextAPIClient) == null ? void 0 : _a3.recordContext(requestID, context2.used, context2.ignored);
54855
54971
  return { prompt, context: context2 };
54856
54972
  }
54857
54973
  async buildPrivateContextSummary(context2) {
54858
- const isDotCom2 = authProvider.instance.getAuthStatus().isDotCom;
54859
- if (!isDotCom2) {
54974
+ if (!isDotCom(authProvider.instance.status)) {
54860
54975
  return {};
54861
54976
  }
54862
54977
  if (!workspaceReposMonitor) {
@@ -54991,7 +55106,7 @@ class ChatController {
54991
55106
  this.chatModel.addBotMessage({ text: messageText });
54992
55107
  void this.saveSession();
54993
55108
  this.postViewTranscript();
54994
- const authStatus = authProvider.instance.getAuthStatus();
55109
+ const authStatus = authProvider.instance.status;
54995
55110
  const generatedCode = countGeneratedCode(messageText.toString());
54996
55111
  const responseEventAction = generatedCode.charCount > 0 ? "hasCode" : "noCode";
54997
55112
  telemetryRecorder.recordEvent("cody.chatResponse", responseEventAction, {
@@ -55002,13 +55117,13 @@ class ChatController {
55002
55117
  ...generatedCode,
55003
55118
  // Flag indicating this is a transcript event to go through ML data pipeline. Only for dotcom users
55004
55119
  // See https://github.com/sourcegraph/sourcegraph/pull/59524
55005
- recordsPrivateMetadataTranscript: authStatus.isDotCom ? 1 : 0
55120
+ recordsPrivateMetadataTranscript: isDotCom(authStatus) ? 1 : 0
55006
55121
  },
55007
55122
  privateMetadata: {
55008
55123
  // 🚨 SECURITY: chat transcripts are to be included only for DotCom users AND for V2 telemetry
55009
55124
  // V2 telemetry exports privateMetadata only for DotCom users
55010
55125
  // the condition below is an aditional safegaurd measure
55011
- responseText: authStatus.isDotCom && truncatePromptString(messageText, CHAT_OUTPUT_TOKEN_BUDGET),
55126
+ responseText: isDotCom(authStatus) && truncatePromptString(messageText, CHAT_OUTPUT_TOKEN_BUDGET),
55012
55127
  chatModel: this.chatModel.modelID
55013
55128
  }
55014
55129
  });
@@ -55027,7 +55142,7 @@ class ChatController {
55027
55142
  // current in-progress completion. If the chat does not exist, then this
55028
55143
  // is a no-op.
55029
55144
  async restoreSession(sessionID) {
55030
- const oldTranscript = chatHistory.getChat(authProvider.instance.getAuthStatus(), sessionID);
55145
+ const oldTranscript = chatHistory.getChat(authProvider.instance.statusAuthed, sessionID);
55031
55146
  if (!oldTranscript) {
55032
55147
  return;
55033
55148
  }
@@ -55037,15 +55152,18 @@ class ChatController {
55037
55152
  this.postViewTranscript();
55038
55153
  }
55039
55154
  async saveSession() {
55040
- const allHistory = await chatHistory.saveChat(
55041
- authProvider.instance.getAuthStatus(),
55042
- this.chatModel.toSerializedChatTranscript()
55043
- );
55044
- if (allHistory) {
55045
- void this.postMessage({
55046
- type: "history",
55047
- localHistory: allHistory
55048
- });
55155
+ const authStatus = authProvider.instance.status;
55156
+ if (authStatus.authenticated) {
55157
+ const allHistory = await chatHistory.saveChat(
55158
+ authStatus,
55159
+ this.chatModel.toSerializedChatTranscript()
55160
+ );
55161
+ if (allHistory) {
55162
+ void this.postMessage({
55163
+ type: "history",
55164
+ localHistory: allHistory
55165
+ });
55166
+ }
55049
55167
  }
55050
55168
  }
55051
55169
  async clearAndRestartSession() {
@@ -55066,7 +55184,7 @@ class ChatController {
55066
55184
  return this.webviewPanelOrView;
55067
55185
  }
55068
55186
  const viewType = CodyChatEditorViewType;
55069
- const panelTitle = ((_a3 = chatHistory.getChat(authProvider.instance.getAuthStatus(), this.chatModel.sessionID)) == null ? void 0 : _a3.chatTitle) || getChatPanelTitle(lastQuestion);
55187
+ const panelTitle = ((_a3 = chatHistory.getChat(authProvider.instance.statusAuthed, this.chatModel.sessionID)) == null ? void 0 : _a3.chatTitle) || getChatPanelTitle(lastQuestion);
55070
55188
  const viewColumn = activePanelViewColumn || ViewColumn.Beside;
55071
55189
  const webviewPath = Uri.joinPath(this.extensionUri, "dist", "webviews");
55072
55190
  const panel2 = window$1.createWebviewPanel(
@@ -55140,7 +55258,19 @@ class ChatController {
55140
55258
  evaluatedFeatureFlag: (flag2) => featureFlagProvider.instance.evaluatedFeatureFlag(flag2),
55141
55259
  prompts: (query2) => promiseFactoryToObservable(
55142
55260
  (signal2) => mergedPromptsAndLegacyCommands(query2, signal2)
55143
- )
55261
+ ),
55262
+ models: () => combineLatest$1([
55263
+ this.configWatcher.changes,
55264
+ modelsService.instance.selectedOrDefaultModelChanges.pipe(
55265
+ startWith$1(void 0)
55266
+ )
55267
+ ]).pipe(map$1(() => modelsService.instance.getModels(ModelUsage.Chat))),
55268
+ setChatModel: (model2) => {
55269
+ this.chatModel.updateModel(model2);
55270
+ return promiseToObservable$1(
55271
+ modelsService.instance.setSelectedModel(ModelUsage.Chat, model2)
55272
+ );
55273
+ }
55144
55274
  }
55145
55275
  )
55146
55276
  );
@@ -55180,7 +55310,7 @@ class ChatController {
55180
55310
  let gitMetadata = "";
55181
55311
  if (workspaceReposMonitor) {
55182
55312
  const { isPublic: isWorkspacePublic, repoMetadata } = await workspaceReposMonitor.getRepoMetadataIfPublic();
55183
- if (authStatus.isDotCom && legacyAddEnhancedContext && isWorkspacePublic) {
55313
+ if (isDotCom(authStatus) && legacyAddEnhancedContext && isWorkspacePublic) {
55184
55314
  gitMetadata = JSON.stringify(repoMetadata);
55185
55315
  }
55186
55316
  }
@@ -55188,7 +55318,7 @@ class ChatController {
55188
55318
  metadata: {
55189
55319
  // Flag indicating this is a transcript event to go through ML data pipeline. Only for DotCom users
55190
55320
  // See https://github.com/sourcegraph/sourcegraph/pull/59524
55191
- recordsPrivateMetadataTranscript: authStatus.endpoint && authStatus.isDotCom ? 1 : 0,
55321
+ recordsPrivateMetadataTranscript: authStatus.endpoint && isDotCom(authStatus) ? 1 : 0,
55192
55322
  addEnhancedContext: legacyAddEnhancedContext ? 1 : 0,
55193
55323
  // All mentions
55194
55324
  mentionsTotal: mentions.length,
@@ -55226,7 +55356,7 @@ class ChatController {
55226
55356
  // 🚨 SECURITY: chat transcripts are to be included only for DotCom users AND for V2 telemetry
55227
55357
  // V2 telemetry exports privateMetadata only for DotCom users
55228
55358
  // the condition below is an additional safeguard measure
55229
- promptText: authStatus.isDotCom && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET),
55359
+ promptText: isDotCom(authStatus) && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET),
55230
55360
  gitMetadata
55231
55361
  }
55232
55362
  });
@@ -55303,7 +55433,7 @@ function combineContext(explicitMentions, openCtxContext, priorityContext, retri
55303
55433
  }
55304
55434
  const CodyChatEditorViewType = "cody.editorPanel";
55305
55435
  class ChatsController {
55306
- constructor(options, chatClient, enterpriseContext, localEmbeddings, symf, contextRetriever, guardrails, contextAPIClient, extensionClient) {
55436
+ constructor(options, chatClient, enterpriseContext, localEmbeddings, symf, contextRetriever, guardrails, contextAPIClient, extensionClient, configWatcher) {
55307
55437
  // Chat view in the panel (typically in the sidebar)
55308
55438
  __publicField2(this, "panel");
55309
55439
  // Chat views in editor panels
@@ -55321,6 +55451,7 @@ class ChatsController {
55321
55451
  this.guardrails = guardrails;
55322
55452
  this.contextAPIClient = contextAPIClient;
55323
55453
  this.extensionClient = extensionClient;
55454
+ this.configWatcher = configWatcher;
55324
55455
  logDebug("ChatsController:constructor", "init");
55325
55456
  this.panel = this.createChatController();
55326
55457
  this.disposables.push(
@@ -55330,17 +55461,12 @@ class ChatsController {
55330
55461
  );
55331
55462
  }
55332
55463
  async setAuthStatus(authStatus) {
55333
- const hasLoggedOut = !authStatus.isLoggedIn;
55464
+ const hasLoggedOut = !authStatus.authenticated;
55334
55465
  const hasSwitchedAccount = this.currentAuthAccount && this.currentAuthAccount.endpoint !== authStatus.endpoint;
55335
55466
  if (hasLoggedOut || hasSwitchedAccount) {
55336
55467
  this.disposeAllChats();
55337
55468
  }
55338
- const endpoint = authStatus.endpoint ?? "";
55339
- this.currentAuthAccount = {
55340
- endpoint,
55341
- primaryEmail: authStatus.primaryEmail,
55342
- username: authStatus.username
55343
- };
55469
+ this.currentAuthAccount = authStatus.authenticated ? { ...authStatus } : void 0;
55344
55470
  this.panel.setAuthStatus(authStatus);
55345
55471
  }
55346
55472
  async restoreToPanel(panel2, chatID) {
@@ -55560,8 +55686,8 @@ class ChatsController {
55560
55686
  */
55561
55687
  async exportHistory() {
55562
55688
  telemetryRecorder.recordEvent("cody.exportChatHistoryButton", "clicked");
55563
- const authStatus = authProvider.instance.getAuthStatus();
55564
- if (authStatus.isLoggedIn) {
55689
+ const authStatus = authProvider.instance.status;
55690
+ if (authStatus.authenticated) {
55565
55691
  try {
55566
55692
  const historyJson = chatHistory.getLocalHistory(authStatus);
55567
55693
  const exportPath = await window$1.showSaveDialog({
@@ -55585,7 +55711,7 @@ class ChatsController {
55585
55711
  async clearHistory(chatID) {
55586
55712
  const ClearWithoutConfirmID = "clear-all-no-confirm";
55587
55713
  const isClearAll = !chatID || chatID === ClearWithoutConfirmID;
55588
- const authStatus = authProvider.instance.getAuthStatus();
55714
+ const authStatus = authProvider.instance.statusAuthed;
55589
55715
  if (isClearAll) {
55590
55716
  if (chatID !== ClearWithoutConfirmID) {
55591
55717
  const userConfirmation = await window$1.showWarningMessage(
@@ -55673,7 +55799,8 @@ class ChatsController {
55673
55799
  startTokenReceiver: this.options.startTokenReceiver,
55674
55800
  contextAPIClient: this.contextAPIClient,
55675
55801
  contextRetriever: this.contextRetriever,
55676
- extensionClient: this.extensionClient
55802
+ extensionClient: this.extensionClient,
55803
+ configWatcher: this.configWatcher
55677
55804
  });
55678
55805
  }
55679
55806
  disposeChat(chatID, includePanel) {
@@ -56133,7 +56260,7 @@ class GhostHintDecorator {
56133
56260
  trailing: true
56134
56261
  }
56135
56262
  );
56136
- const initialAuth = authProvider.instance.getAuthStatus();
56263
+ const initialAuth = authProvider.instance.status;
56137
56264
  this.updateEnablement(initialAuth);
56138
56265
  this.permanentDisposables.push(
56139
56266
  subscriptionDisposable(
@@ -56143,7 +56270,7 @@ class GhostHintDecorator {
56143
56270
  this.permanentDisposables.push(
56144
56271
  workspace.onDidChangeConfiguration((e) => {
56145
56272
  if (e.affectsConfiguration("cody")) {
56146
- this.updateEnablement(authProvider.instance.getAuthStatus());
56273
+ this.updateEnablement(authProvider.instance.status);
56147
56274
  }
56148
56275
  }),
56149
56276
  workspace.onDidChangeTextDocument((event) => {
@@ -56276,7 +56403,7 @@ class GhostHintDecorator {
56276
56403
  }
56277
56404
  async updateEnablement(authStatus) {
56278
56405
  const featureEnablement = await getGhostHintEnablement();
56279
- if (!authStatus.isLoggedIn || !(featureEnablement.Document || featureEnablement.EditOrChat || featureEnablement.Generate)) {
56406
+ if (!authStatus.authenticated || !(featureEnablement.Document || featureEnablement.EditOrChat || featureEnablement.Generate)) {
56280
56407
  this.disposeActive();
56281
56408
  return;
56282
56409
  }
@@ -56365,8 +56492,9 @@ async function getContextFilesFromGitDiff(gitRepo) {
56365
56492
  continue;
56366
56493
  }
56367
56494
  const uri2 = (_a3 = diffFiles.find((p) => {
56368
- const diffPath = diff2.split("\n")[0];
56369
- return diffPath.split("").reverse().join("").startsWith(displayPath(p.uri).split("").reverse().join(""));
56495
+ var _a4;
56496
+ const diffPath = (_a4 = diff2.split("\n")) == null ? void 0 : _a4[0];
56497
+ return diffPath ? diffPath.split("").reverse().join("").startsWith(displayPath(p.uri).split("").reverse().join("")) : p.uri;
56370
56498
  })) == null ? void 0 : _a3.uri;
56371
56499
  if (!uri2 || !await doesFileExist(uri2)) {
56372
56500
  continue;
@@ -56500,7 +56628,7 @@ class CodySourceControl {
56500
56628
  async generate(scm) {
56501
56629
  var _a3, _b2;
56502
56630
  telemetryRecorder.recordEvent("cody.command.generate-commit", "executed");
56503
- const currentWorkspaceUri = (_b2 = (_a3 = workspace.workspaceFolders) == null ? void 0 : _a3[0]) == null ? void 0 : _b2.uri;
56631
+ const currentWorkspaceUri = (scm == null ? void 0 : scm.rootUri) ?? ((_b2 = (_a3 = workspace.workspaceFolders) == null ? void 0 : _a3[0]) == null ? void 0 : _b2.uri);
56504
56632
  if (!this.gitAPI || !currentWorkspaceUri) {
56505
56633
  window$1.showInformationMessage("Git is not available in the current workspace.");
56506
56634
  return;
@@ -56790,6 +56918,75 @@ function fuseResults(retrievedSets, rankingIdentities) {
56790
56918
  }
56791
56919
  return fusedResults;
56792
56920
  }
56921
+ class DefaultCompletionsContextRanker {
56922
+ rankAndFuseContext(results) {
56923
+ if (this.containsRecentEditsBasedContext(results)) {
56924
+ return this.getRecentEditsBasedContextFusion(results);
56925
+ }
56926
+ return this.getRRFBasedContextFusion(results);
56927
+ }
56928
+ containsRecentEditsBasedContext(results) {
56929
+ return results.some((result) => result.identifier.includes("recent-edits"));
56930
+ }
56931
+ getRecentEditsBasedContextFusion(results) {
56932
+ const priorityBasedContextSnippets = this.splitPriorityBasedContextFusion(results, [
56933
+ "recent-edits"
56934
+ ]);
56935
+ const priorityContextSnippets = this.getLinearContextFusion(
56936
+ priorityBasedContextSnippets.priorityContext
56937
+ );
56938
+ const nonPriorityContextSnippets = this.getRRFBasedContextFusion(
56939
+ priorityBasedContextSnippets.nonPriorityContext
56940
+ );
56941
+ return /* @__PURE__ */ new Set([...priorityContextSnippets, ...nonPriorityContextSnippets]);
56942
+ }
56943
+ /**
56944
+ * Performs a split based on priority based retrievers and orders the the priority based retrievers based on the order of the retrieverPriority array.
56945
+ *
56946
+ * @param results - An array of RetrievedContextResults to be split.
56947
+ * @param retrieverPriority - An ordered array of strings representing priority retrievers. Rest of the retrievers are ranked using RRF.
56948
+ * @returns A seperate set of priority based and non-priority based context snippets.
56949
+ */
56950
+ splitPriorityBasedContextFusion(results, retrieverPriority) {
56951
+ const priorityBasedRetrievedContext = results.filter(
56952
+ (result) => retrieverPriority.includes(result.identifier)
56953
+ );
56954
+ const nonPriorityBasedRetrievedContext = results.filter(
56955
+ (result) => !retrieverPriority.includes(result.identifier)
56956
+ );
56957
+ const priorityMap = new Map(retrieverPriority.map((priority, index2) => [priority, index2]));
56958
+ const orderedPriorityBasedRetrievedContext = priorityBasedRetrievedContext.sort(
56959
+ (a, b) => priorityMap.get(a.identifier) - priorityMap.get(b.identifier)
56960
+ );
56961
+ return {
56962
+ priorityContext: orderedPriorityBasedRetrievedContext,
56963
+ nonPriorityContext: nonPriorityBasedRetrievedContext
56964
+ };
56965
+ }
56966
+ getRRFBasedContextFusion(results) {
56967
+ const fusedResults = fuseResults(
56968
+ results.map((r2) => r2.snippets),
56969
+ (result) => {
56970
+ if (typeof result.startLine === "undefined" || typeof result.endLine === "undefined") {
56971
+ return [result.uri.toString()];
56972
+ }
56973
+ const lineIds = [];
56974
+ for (let i = result.startLine; i <= result.endLine; i++) {
56975
+ lineIds.push(`${result.uri.toString()}:${i}`);
56976
+ }
56977
+ return lineIds;
56978
+ }
56979
+ );
56980
+ return fusedResults;
56981
+ }
56982
+ getLinearContextFusion(results) {
56983
+ const linearResults = [];
56984
+ for (const result of results) {
56985
+ linearResults.push(...Array.from(result.snippets));
56986
+ }
56987
+ return new Set(linearResults);
56988
+ }
56989
+ }
56793
56990
  class ContextMixer {
56794
56991
  constructor(strategyFactory) {
56795
56992
  this.strategyFactory = strategyFactory;
@@ -56832,19 +57029,8 @@ class ContextMixer {
56832
57029
  };
56833
57030
  })
56834
57031
  );
56835
- const fusedResults = fuseResults(
56836
- results.map((r2) => r2.snippets),
56837
- (result) => {
56838
- if (typeof result.startLine === "undefined" || typeof result.endLine === "undefined") {
56839
- return [result.uri.toString()];
56840
- }
56841
- const lineIds = [];
56842
- for (let i = result.startLine; i <= result.endLine; i++) {
56843
- lineIds.push(`${result.uri.toString()}:${i}`);
56844
- }
56845
- return lineIds;
56846
- }
56847
- );
57032
+ const contextRanker = new DefaultCompletionsContextRanker();
57033
+ const fusedResults = contextRanker.rankAndFuseContext(results);
56848
57034
  let totalChars = options.docContext.prefix.length + options.docContext.suffix.length;
56849
57035
  const mixedContext = [];
56850
57036
  const retrieverStats = {};
@@ -56919,7 +57105,11 @@ const htmlFamily = /* @__PURE__ */ new Set([
56919
57105
  // This omits vue and svelte as these languages usually do not
56920
57106
  // import CSS modules but define them in the same file instead.
56921
57107
  ]);
56922
- function shouldBeUsedAsContext(enableExtendedLanguagePool, baseLanguageId, languageId) {
57108
+ function shouldBeUsedAsContext({
57109
+ enableExtendedLanguagePool,
57110
+ baseLanguageId,
57111
+ languageId
57112
+ }) {
56923
57113
  if (baseLanguageId === languageId) {
56924
57114
  return true;
56925
57115
  }
@@ -56992,13 +57182,14 @@ class VSCodeDocumentHistory {
56992
57182
  if (ignoreSet.has(item.document.uri)) {
56993
57183
  continue;
56994
57184
  }
56995
- if (shouldBeUsedAsContext(
56996
- completionProviderConfig.getPrefetchedFlag(
57185
+ const params = {
57186
+ enableExtendedLanguagePool: completionProviderConfig.getPrefetchedFlag(
56997
57187
  FeatureFlag.CodyAutocompleteContextExtendLanguagePool
56998
57188
  ),
56999
57189
  baseLanguageId,
57000
- item.document.languageId
57001
- )) {
57190
+ languageId: item.document.languageId
57191
+ };
57192
+ if (shouldBeUsedAsContext(params)) {
57002
57193
  continue;
57003
57194
  }
57004
57195
  ret2.push(item);
@@ -156269,13 +156460,14 @@ class JaccardSimilarityRetriever extends CachedRetriever {
156269
156460
  if (!["file", "vscode-userdata"].includes(document2.uri.scheme)) {
156270
156461
  return;
156271
156462
  }
156272
- if (!shouldBeUsedAsContext(
156273
- completionProviderConfig.getPrefetchedFlag(
156463
+ const params = {
156464
+ enableExtendedLanguagePool: completionProviderConfig.getPrefetchedFlag(
156274
156465
  FeatureFlag.CodyAutocompleteContextExtendLanguagePool
156275
156466
  ),
156276
- curLang,
156277
- document2.languageId
156278
- )) {
156467
+ baseLanguageId: curLang,
156468
+ languageId: document2.languageId
156469
+ };
156470
+ if (!shouldBeUsedAsContext(params)) {
156279
156471
  return;
156280
156472
  }
156281
156473
  const endLine = Math.min(document2.lineCount, 1e4);
@@ -157277,6 +157469,165 @@ class LspLightRetriever {
157277
157469
  invalidateDocumentCache(event.document);
157278
157470
  }
157279
157471
  }
157472
+ class RecentEditsRetriever {
157473
+ constructor(maxAgeMs, workspace$1 = workspace) {
157474
+ // We use a map from the document URI to the set of tracked completions inside that document to
157475
+ // improve performance of the `onDidChangeTextDocument` event handler.
157476
+ __publicField2(this, "trackedDocuments", /* @__PURE__ */ new Map());
157477
+ __publicField2(this, "identifier", "recent-edits");
157478
+ __publicField2(this, "disposables", []);
157479
+ this.maxAgeMs = maxAgeMs;
157480
+ this.workspace = workspace$1;
157481
+ this.disposables.push(workspace$1.onDidChangeTextDocument(this.onDidChangeTextDocument.bind(this)));
157482
+ this.disposables.push(workspace$1.onDidRenameFiles(this.onDidRenameFiles.bind(this)));
157483
+ this.disposables.push(workspace$1.onDidDeleteFiles(this.onDidDeleteFiles.bind(this)));
157484
+ }
157485
+ async retrieve(options) {
157486
+ const rawDiffs = await this.getDiffAcrossDocuments();
157487
+ const diffs = this.filterCandidateDiffs(rawDiffs, options.document);
157488
+ diffs.sort((a, b) => b.latestChangeTimestamp - a.latestChangeTimestamp);
157489
+ const autocompleteContextSnippets = [];
157490
+ for (const diff2 of diffs) {
157491
+ const content = this.getCommentedPromptForCompletions(
157492
+ diff2.languageId,
157493
+ diff2.uri,
157494
+ diff2.diff
157495
+ ).toString();
157496
+ const autocompleteSnippet = {
157497
+ uri: diff2.uri,
157498
+ content
157499
+ };
157500
+ autocompleteContextSnippets.push(autocompleteSnippet);
157501
+ }
157502
+ return autocompleteContextSnippets;
157503
+ }
157504
+ async getDiffAcrossDocuments() {
157505
+ const diffs = [];
157506
+ const diffPromises = Array.from(this.trackedDocuments.entries()).map(
157507
+ async ([uri2, trackedDocument]) => {
157508
+ const diff2 = await this.getDiff(Uri.parse(uri2));
157509
+ if (diff2) {
157510
+ return {
157511
+ diff: diff2,
157512
+ uri: trackedDocument.uri,
157513
+ languageId: trackedDocument.languageId,
157514
+ latestChangeTimestamp: Math.max(
157515
+ ...trackedDocument.changes.map((c) => c.timestamp)
157516
+ )
157517
+ };
157518
+ }
157519
+ return null;
157520
+ }
157521
+ );
157522
+ const results = await Promise.all(diffPromises);
157523
+ diffs.push(...results.filter((result) => result !== null));
157524
+ return diffs;
157525
+ }
157526
+ getCommentedPromptForCompletions(languageId, filename, diff2) {
157527
+ const filePath = PromptString.fromDisplayPath(filename);
157528
+ const languageConfig = getLanguageConfig(languageId);
157529
+ const commentStart = languageConfig ? languageConfig.commentStart : ps`// `;
157530
+ const prompt = psDedent`${commentStart} Here is git diff of the recent change made to the file ${filePath} which is used to provide context for the completion:\n${diff2}`;
157531
+ return prompt;
157532
+ }
157533
+ filterCandidateDiffs(allDiffs, document2) {
157534
+ const filterCandidateDiffs = [];
157535
+ for (const diff2 of allDiffs) {
157536
+ const currentDocumentLanguageId = document2.languageId;
157537
+ const params = {
157538
+ enableExtendedLanguagePool: false,
157539
+ baseLanguageId: currentDocumentLanguageId,
157540
+ languageId: diff2.languageId
157541
+ };
157542
+ if (shouldBeUsedAsContext(params)) {
157543
+ filterCandidateDiffs.push(diff2);
157544
+ }
157545
+ }
157546
+ return filterCandidateDiffs;
157547
+ }
157548
+ isSupportedForLanguageId() {
157549
+ return true;
157550
+ }
157551
+ async getDiff(uri2) {
157552
+ if (await contextFiltersProvider.instance.isUriIgnored(uri2)) {
157553
+ return null;
157554
+ }
157555
+ const trackedDocument = this.trackedDocuments.get(uri2.toString());
157556
+ if (!trackedDocument) {
157557
+ return null;
157558
+ }
157559
+ const oldContent = trackedDocument.content;
157560
+ const newContent = applyChanges(
157561
+ oldContent,
157562
+ trackedDocument.changes.map((c) => c.change)
157563
+ );
157564
+ return PromptString.fromGitDiff(uri2, oldContent, newContent);
157565
+ }
157566
+ onDidChangeTextDocument(event) {
157567
+ let trackedDocument = this.trackedDocuments.get(event.document.uri.toString());
157568
+ if (!trackedDocument) {
157569
+ trackedDocument = this.trackDocument(event.document);
157570
+ }
157571
+ const now2 = Date.now();
157572
+ for (const change of event.contentChanges) {
157573
+ trackedDocument.changes.push({
157574
+ timestamp: now2,
157575
+ change
157576
+ });
157577
+ }
157578
+ this.reconcileOutdatedChanges();
157579
+ }
157580
+ onDidRenameFiles(event) {
157581
+ for (const file of event.files) {
157582
+ const trackedDocument = this.trackedDocuments.get(file.oldUri.toString());
157583
+ if (trackedDocument) {
157584
+ this.trackedDocuments.set(file.newUri.toString(), trackedDocument);
157585
+ this.trackedDocuments.delete(file.oldUri.toString());
157586
+ }
157587
+ }
157588
+ }
157589
+ onDidDeleteFiles(event) {
157590
+ for (const uri2 of event.files) {
157591
+ this.trackedDocuments.delete(uri2.toString());
157592
+ }
157593
+ }
157594
+ dispose() {
157595
+ this.trackedDocuments.clear();
157596
+ for (const disposable of this.disposables) {
157597
+ disposable.dispose();
157598
+ }
157599
+ }
157600
+ trackDocument(document2) {
157601
+ const trackedDocument = {
157602
+ content: document2.getText(),
157603
+ languageId: document2.languageId,
157604
+ uri: document2.uri,
157605
+ changes: []
157606
+ };
157607
+ this.trackedDocuments.set(document2.uri.toString(), trackedDocument);
157608
+ return trackedDocument;
157609
+ }
157610
+ reconcileOutdatedChanges() {
157611
+ const now2 = Date.now();
157612
+ for (const [, trackedDocument] of this.trackedDocuments) {
157613
+ const firstNonOutdatedChangeIndex = trackedDocument.changes.findIndex(
157614
+ (c) => now2 - c.timestamp < this.maxAgeMs
157615
+ );
157616
+ const outdatedChanges = trackedDocument.changes.slice(0, firstNonOutdatedChangeIndex);
157617
+ trackedDocument.content = applyChanges(
157618
+ trackedDocument.content,
157619
+ outdatedChanges.map((c) => c.change)
157620
+ );
157621
+ trackedDocument.changes = trackedDocument.changes.slice(firstNonOutdatedChangeIndex);
157622
+ }
157623
+ }
157624
+ }
157625
+ function applyChanges(content, changes) {
157626
+ for (const change of changes) {
157627
+ content = content.slice(0, change.rangeOffset) + change.text + content.slice(change.rangeOffset + change.rangeLength);
157628
+ }
157629
+ return content;
157630
+ }
157280
157631
  class DefaultContextStrategyFactory {
157281
157632
  constructor(contextStrategy, createBfgRetriever) {
157282
157633
  __publicField2(this, "disposables", []);
@@ -157286,6 +157637,24 @@ class DefaultContextStrategyFactory {
157286
157637
  switch (contextStrategy) {
157287
157638
  case "none":
157288
157639
  break;
157640
+ case "recent-edits":
157641
+ this.localRetriever = new RecentEditsRetriever(60 * 1e3);
157642
+ this.disposables.push(this.localRetriever);
157643
+ break;
157644
+ case "recent-edits-1m":
157645
+ this.localRetriever = new RecentEditsRetriever(60 * 1e3);
157646
+ this.disposables.push(this.localRetriever);
157647
+ break;
157648
+ case "recent-edits-5m":
157649
+ this.localRetriever = new RecentEditsRetriever(60 * 5 * 1e3);
157650
+ this.disposables.push(this.localRetriever);
157651
+ break;
157652
+ case "recent-edits-mixed":
157653
+ this.localRetriever = new RecentEditsRetriever(60 * 1e3);
157654
+ this.graphRetriever = new JaccardSimilarityRetriever();
157655
+ this.disposables.push(this.localRetriever);
157656
+ this.disposables.push(this.graphRetriever);
157657
+ break;
157289
157658
  case "tsc-mixed":
157290
157659
  this.localRetriever = new JaccardSimilarityRetriever();
157291
157660
  this.disposables.push(this.localRetriever);
@@ -157316,7 +157685,7 @@ class DefaultContextStrategyFactory {
157316
157685
  }
157317
157686
  }
157318
157687
  getStrategy(document2) {
157319
- var _a3, _b2, _c2;
157688
+ var _a3, _b2, _c2, _d2;
157320
157689
  const retrievers = [];
157321
157690
  switch (this.contextStrategy) {
157322
157691
  case "none": {
@@ -157348,10 +157717,22 @@ class DefaultContextStrategyFactory {
157348
157717
  retrievers.push(this.localRetriever);
157349
157718
  }
157350
157719
  break;
157351
- case "jaccard-similarity": {
157720
+ case "jaccard-similarity":
157721
+ case "recent-edits":
157722
+ case "recent-edits-1m":
157723
+ case "recent-edits-5m": {
157724
+ if (this.localRetriever) {
157725
+ retrievers.push(this.localRetriever);
157726
+ }
157727
+ break;
157728
+ }
157729
+ case "recent-edits-mixed": {
157352
157730
  if (this.localRetriever) {
157353
157731
  retrievers.push(this.localRetriever);
157354
157732
  }
157733
+ if ((_d2 = this.graphRetriever) == null ? void 0 : _d2.isSupportedForLanguageId(document2.languageId)) {
157734
+ retrievers.push(this.graphRetriever);
157735
+ }
157355
157736
  break;
157356
157737
  }
157357
157738
  }
@@ -160290,7 +160671,7 @@ function createFastPathClient(requestParams, abortController, params) {
160290
160671
  logResponseHeadersToSpan(span2, response);
160291
160672
  const traceId = (_f2 = getActiveTraceAndSpanId()) == null ? void 0 : _f2.traceId;
160292
160673
  if (response.status === 429) {
160293
- const upgradeIsAvailable = authStatus.userCanUpgrade;
160674
+ const upgradeIsAvailable = !!authStatus.userCanUpgrade;
160294
160675
  throw recordErrorToSpan(
160295
160676
  span2,
160296
160677
  await createRateLimitErrorFromResponse(response, upgradeIsAvailable)
@@ -160491,7 +160872,7 @@ class FireworksProvider extends Provider {
160491
160872
  );
160492
160873
  const isNode = typeof define_process_default !== "undefined";
160493
160874
  this.fastPathAccessToken = config.accessToken && // Require the upstream to be dotcom
160494
- (this.authStatus.isDotCom || this.isLocalInstance) && define_process_default.env.CODY_DISABLE_FASTPATH !== "true" && // Used for testing
160875
+ (isDotCom(this.authStatus) || this.isLocalInstance) && define_process_default.env.CODY_DISABLE_FASTPATH !== "true" && // Used for testing
160495
160876
  // The fast path client only supports Node.js style response streams
160496
160877
  isNode ? dotcomTokenToGatewayToken(config.accessToken) : void 0;
160497
160878
  }
@@ -160574,7 +160955,7 @@ function createProviderConfig$3({
160574
160955
  model: model2,
160575
160956
  ...otherOptions
160576
160957
  }) {
160577
- const clientModel = getClientModel(model2, otherOptions.authStatus.isDotCom);
160958
+ const clientModel = getClientModel(model2, isDotCom(otherOptions.authStatus));
160578
160959
  const maxContextTokens = getMaxContextTokens(clientModel);
160579
160960
  return {
160580
160961
  create(options) {
@@ -161002,7 +161383,7 @@ async function createProviderConfigHelper(params) {
161002
161383
  case "anthropic": {
161003
161384
  let getAnthropicModel = function() {
161004
161385
  var _a4;
161005
- if (authStatus.isDotCom) {
161386
+ if (isDotCom(authStatus)) {
161006
161387
  return DEFAULT_PLG_ANTHROPIC_MODEL;
161007
161388
  }
161008
161389
  if (((_a4 = authStatus.configOverwrites) == null ? void 0 : _a4.provider) === "sourcegraph") {
@@ -161041,20 +161422,19 @@ async function createProviderConfigHelper(params) {
161041
161422
  return null;
161042
161423
  }
161043
161424
  }
161044
- async function manuallyGetCompletionItemsForProvider(completionsProviderConfig, document2, position, context2) {
161425
+ async function manuallyGetCompletionItemsForProvider(config, document2, position, context2) {
161045
161426
  var _a3;
161046
- const result = await completionsProviderConfig.completionsProvider.provideInlineCompletionItems(
161427
+ const result = await config.completionsProvider.provideInlineCompletionItems(
161047
161428
  document2,
161048
161429
  position,
161049
161430
  context2,
161050
161431
  new CancellationTokenSource().token
161051
161432
  );
161052
- const model2 = completionsProviderConfig.modelName;
161053
- const provider = completionsProviderConfig.providerName;
161054
161433
  const completion = ((_a3 = result == null ? void 0 : result.items[0].insertText) == null ? void 0 : _a3.toString()) || "";
161055
161434
  return {
161056
- provider,
161057
- model: model2,
161435
+ provider: config.providerName,
161436
+ model: config.modelName,
161437
+ contextStrategy: config.contextStrategy,
161058
161438
  completion
161059
161439
  };
161060
161440
  }
@@ -161078,7 +161458,7 @@ async function triggerMultiModelAutocompletionsForComparison(allCompletionsProvi
161078
161458
  const completions = await Promise.all(allPromises);
161079
161459
  let completionsOutput = "";
161080
161460
  for (const result of completions) {
161081
- completionsOutput += `Model: ${result.model}
161461
+ completionsOutput += `Model: ${result.model} Context: ${result.contextStrategy}
161082
161462
  ${result.completion}
161083
161463
 
161084
161464
  `;
@@ -161091,8 +161471,8 @@ async function createInlineCompletionItemFromMultipleProviders({
161091
161471
  statusBar,
161092
161472
  createBfgRetriever
161093
161473
  }) {
161094
- const authStatus = authProvider.instance.getAuthStatus();
161095
- if (!authStatus.isLoggedIn || config.autocompleteExperimentalMultiModelCompletions === void 0) {
161474
+ const authStatus = authProvider.instance.status;
161475
+ if (!authStatus.authenticated || config.autocompleteExperimentalMultiModelCompletions === void 0) {
161096
161476
  return {
161097
161477
  dispose: () => {
161098
161478
  }
@@ -161105,7 +161485,8 @@ async function createInlineCompletionItemFromMultipleProviders({
161105
161485
  multiModelConfigsList.push({
161106
161486
  provider: currentProviderConfig.provider,
161107
161487
  model: currentProviderConfig.model,
161108
- enableExperimentalFireworksOverrides: currentProviderConfig.enableExperimentalFireworksOverrides ?? false
161488
+ enableExperimentalFireworksOverrides: currentProviderConfig.enableExperimentalFireworksOverrides ?? false,
161489
+ context: currentProviderConfig.context
161109
161490
  });
161110
161491
  }
161111
161492
  }
@@ -161115,11 +161496,19 @@ async function createInlineCompletionItemFromMultipleProviders({
161115
161496
  }
161116
161497
  };
161117
161498
  }
161118
- const allPromises = multiModelConfigsList.map(async (currentProviderConfig) => {
161119
- const newConfig = _.cloneDeep(config);
161120
- newConfig.telemetryLevel = "off";
161121
- newConfig.autocompleteExperimentalFireworksOptions = currentProviderConfig.enableExperimentalFireworksOverrides ? config.autocompleteExperimentalFireworksOptions : void 0;
161122
- newConfig.autocompleteAdvancedModel = null;
161499
+ const allCompletionsProviders = [];
161500
+ for (const currentProviderConfig of multiModelConfigsList) {
161501
+ const newConfig = {
161502
+ ...lodashExports.cloneDeep(config),
161503
+ // Override some config to ensure we are not logging extra events.
161504
+ telemetryLevel: "off",
161505
+ // We should only override the fireworks "cody.autocomplete.experimental.fireworksOptions" when added in the config.
161506
+ autocompleteExperimentalFireworksOptions: currentProviderConfig.enableExperimentalFireworksOverrides ? config.autocompleteExperimentalFireworksOptions : void 0,
161507
+ // Don't use the advanced provider config to get the model
161508
+ autocompleteAdvancedModel: null,
161509
+ autocompleteExperimentalGraphContext: currentProviderConfig.context
161510
+ };
161511
+ completionProviderConfig.setConfig(newConfig);
161123
161512
  const providerConfig = await createProviderConfigHelper({
161124
161513
  client,
161125
161514
  authStatus,
@@ -161128,7 +161517,7 @@ async function createInlineCompletionItemFromMultipleProviders({
161128
161517
  config: newConfig
161129
161518
  });
161130
161519
  if (providerConfig) {
161131
- const authStatus2 = authProvider.instance.getAuthStatus();
161520
+ const authStatus2 = authProvider.instance.statusAuthed;
161132
161521
  const completionsProvider = new InlineCompletionItemProvider({
161133
161522
  authStatus: authStatus2,
161134
161523
  providerConfig,
@@ -161142,21 +161531,15 @@ async function createInlineCompletionItemFromMultipleProviders({
161142
161531
  isDotComUser: isDotCom(authStatus2.endpoint || ""),
161143
161532
  noInlineAccept: true
161144
161533
  });
161145
- return {
161534
+ allCompletionsProviders.push({
161146
161535
  providerName: currentProviderConfig.provider,
161147
161536
  modelName: currentProviderConfig.model,
161148
- completionsProvider
161149
- };
161150
- }
161151
- return void 0;
161152
- });
161153
- const allProviders = await Promise.all(allPromises);
161154
- const allCompletionsProviders = [];
161155
- for (const provider of allProviders) {
161156
- if (provider) {
161157
- allCompletionsProviders.push(provider);
161537
+ completionsProvider,
161538
+ contextStrategy: currentProviderConfig.context
161539
+ });
161158
161540
  }
161159
161541
  }
161542
+ completionProviderConfig.setConfig(config);
161160
161543
  disposables.push(
161161
161544
  commands$1.registerCommand(
161162
161545
  "cody.multi-model-autocomplete.manual-trigger",
@@ -161721,172 +162104,6 @@ class EnterpriseContextFactory {
161721
162104
  return this.workspaceRepoMapper;
161722
162105
  }
161723
162106
  }
161724
- const RemoteFileProvider = createRemoteFileProvider();
161725
- function createRemoteFileProvider(customTitle) {
161726
- return {
161727
- providerUri: REMOTE_FILE_PROVIDER_URI,
161728
- meta() {
161729
- return {
161730
- name: customTitle ?? "Remote Files",
161731
- mentions: {}
161732
- };
161733
- },
161734
- async mentions({ query: query2 }) {
161735
- const [repoName, filePath] = (query2 == null ? void 0 : query2.split(":")) || [];
161736
- if (!(query2 == null ? void 0 : query2.includes(":")) || !repoName.trim()) {
161737
- return await getRepositoryMentions((query2 == null ? void 0 : query2.trim()) ?? "", REMOTE_FILE_PROVIDER_URI);
161738
- }
161739
- return await getFileMentions(repoName, filePath.trim());
161740
- },
161741
- async items({ mention }) {
161742
- var _a3, _b2;
161743
- if (!((_a3 = mention == null ? void 0 : mention.data) == null ? void 0 : _a3.repoName) || !((_b2 = mention == null ? void 0 : mention.data) == null ? void 0 : _b2.filePath)) {
161744
- return [];
161745
- }
161746
- return await getFileItem(
161747
- mention.data.repoName,
161748
- mention.data.filePath,
161749
- mention.data.rev
161750
- );
161751
- }
161752
- };
161753
- }
161754
- async function getFileMentions(repoName, filePath) {
161755
- const repoRe = `^${escapeRegExp(repoName)}$`;
161756
- const fileRe = filePath ? escapeRegExp(filePath) : "^.*$";
161757
- const query2 = `repo:${repoRe} file:${fileRe} type:file count:10`;
161758
- const dataOrError = await graphqlClient.searchFileMatches(query2);
161759
- if (isError$1(dataOrError) || dataOrError === null) {
161760
- return [];
161761
- }
161762
- return dataOrError.search.results.results.map((result) => {
161763
- if (result.__typename !== "FileMatch") {
161764
- return null;
161765
- }
161766
- const url = `${graphqlClient.endpoint.replace(/\/$/, "")}${result.file.url}`;
161767
- const basename2 = displayPathBasename(URI.parse(result.file.path));
161768
- return {
161769
- uri: url,
161770
- title: basename2,
161771
- description: result.file.path,
161772
- data: {
161773
- repoName: result.repository.name,
161774
- rev: result.file.commit.oid,
161775
- filePath: result.file.path
161776
- }
161777
- };
161778
- }).filter(isDefined);
161779
- }
161780
- async function getFileItem(repoName, filePath, rev2 = "HEAD") {
161781
- var _a3, _b2;
161782
- const dataOrError = await graphqlClient.getFileContents(repoName, filePath, rev2);
161783
- if (isError$1(dataOrError)) {
161784
- return [];
161785
- }
161786
- const file = (_b2 = (_a3 = dataOrError == null ? void 0 : dataOrError.repository) == null ? void 0 : _a3.commit) == null ? void 0 : _b2.file;
161787
- if (!file) {
161788
- return [];
161789
- }
161790
- const url = `${graphqlClient.endpoint.replace(/\/$/, "")}${file.url}`;
161791
- return [
161792
- {
161793
- url,
161794
- title: `${repoName}/${file.path}`,
161795
- ai: {
161796
- content: file.content
161797
- }
161798
- }
161799
- ];
161800
- }
161801
- function escapeRegExp(str) {
161802
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
161803
- }
161804
- const CurrentRepositoryDirectoryProvider = createCurrentRepositoryDirectoryProvider();
161805
- function createCurrentRepositoryDirectoryProvider(customTitle) {
161806
- return {
161807
- providerUri: CURRENT_REPOSITORY_DIRECTORY_PROVIDER_URI,
161808
- meta() {
161809
- return {
161810
- name: "Directories",
161811
- mentions: {}
161812
- };
161813
- },
161814
- async mentions({ query: query2 }) {
161815
- var _a3, _b2;
161816
- const currentFile = (_a3 = getEditor().active) == null ? void 0 : _a3.document.uri;
161817
- const workspace$1 = (_b2 = workspace.workspaceFolders) == null ? void 0 : _b2[0].uri;
161818
- if (currentFile || workspace$1) {
161819
- const remote = (await repoNameResolver.getRepoNamesFromWorkspaceUri(
161820
- currentFile || workspace$1
161821
- ))[0];
161822
- if (remote) {
161823
- const workspaceRepoMapper = new WorkspaceRepoMapper();
161824
- const currentRepo = await workspaceRepoMapper.repoForCodebase(remote);
161825
- if (currentRepo) {
161826
- return await getDirectoryMentions(currentRepo.name, query2 == null ? void 0 : query2.trim());
161827
- }
161828
- }
161829
- }
161830
- return [];
161831
- },
161832
- async items({ mention, message }) {
161833
- var _a3, _b2;
161834
- if (!((_a3 = mention == null ? void 0 : mention.data) == null ? void 0 : _a3.repoID) || !((_b2 = mention == null ? void 0 : mention.data) == null ? void 0 : _b2.directoryPath) || !message) {
161835
- return [];
161836
- }
161837
- return await getDirectoryItem(
161838
- message,
161839
- mention.data.repoID,
161840
- mention.data.directoryPath
161841
- );
161842
- }
161843
- };
161844
- }
161845
- async function getDirectoryMentions(repoName, directoryPath) {
161846
- const repoRe = `^${escapeRegExp(repoName)}$`;
161847
- const directoryRe = directoryPath ? escapeRegExp(directoryPath) : "";
161848
- const query2 = `repo:${repoRe} file:${directoryRe}.*/.* select:file.directory count:10`;
161849
- const dataOrError = await graphqlClient.searchFileMatches(query2);
161850
- if (isError$1(dataOrError) || dataOrError === null) {
161851
- return [];
161852
- }
161853
- return dataOrError.search.results.results.map((result) => {
161854
- if (result.__typename !== "FileMatch") {
161855
- return null;
161856
- }
161857
- const url = `${graphqlClient.endpoint.replace(/\/$/, "")}${result.file.url}`;
161858
- return {
161859
- uri: url,
161860
- title: result.file.path,
161861
- description: "",
161862
- data: {
161863
- repoName: result.repository.name,
161864
- repoID: result.repository.id,
161865
- rev: result.file.commit.oid,
161866
- directoryPath: result.file.path
161867
- }
161868
- };
161869
- }).filter(isDefined);
161870
- }
161871
- async function getDirectoryItem(query2, repoID, directoryPath) {
161872
- const dataOrError = await graphqlClient.contextSearch({
161873
- repoIDs: [repoID],
161874
- query: query2,
161875
- filePatterns: [directoryPath]
161876
- });
161877
- if (isError$1(dataOrError) || dataOrError === null) {
161878
- return [];
161879
- }
161880
- return dataOrError.map(
161881
- (node) => ({
161882
- url: node.uri.toString(),
161883
- title: node.path,
161884
- ai: {
161885
- content: node.content
161886
- }
161887
- })
161888
- );
161889
- }
161890
162107
  const gitMentionsProvider = {
161891
162108
  meta() {
161892
162109
  return { name: "Git", mentions: {} };
@@ -163865,7 +164082,8 @@ async function linearApiRequest(query2, variables, settings) {
163865
164082
  method: "POST",
163866
164083
  headers: {
163867
164084
  "Content-Type": "application/json",
163868
- Authorization: `Bearer ${accessToken}`
164085
+ // API keys don't need Bearer prefix (unlike oauth)
164086
+ Authorization: accessToken.startsWith("lin_api_") ? accessToken : `Bearer ${accessToken}`
163869
164087
  },
163870
164088
  body: JSON.stringify({ query: query2, variables })
163871
164089
  });
@@ -163989,6 +164207,86 @@ const LinearIssuesProvider = {
163989
164207
  providerUri: "internal-linear-issues",
163990
164208
  ...linear_issues_default
163991
164209
  };
164210
+ const RemoteFileProvider = createRemoteFileProvider();
164211
+ function createRemoteFileProvider(customTitle) {
164212
+ return {
164213
+ providerUri: REMOTE_FILE_PROVIDER_URI,
164214
+ meta() {
164215
+ return {
164216
+ name: customTitle ?? "Remote Files",
164217
+ mentions: {}
164218
+ };
164219
+ },
164220
+ async mentions({ query: query2 }) {
164221
+ const [repoName, filePath] = (query2 == null ? void 0 : query2.split(":")) || [];
164222
+ if (!(query2 == null ? void 0 : query2.includes(":")) || !repoName.trim()) {
164223
+ return await getRepositoryMentions((query2 == null ? void 0 : query2.trim()) ?? "", REMOTE_FILE_PROVIDER_URI);
164224
+ }
164225
+ return await getFileMentions(repoName, filePath.trim());
164226
+ },
164227
+ async items({ mention }) {
164228
+ var _a3, _b2;
164229
+ if (!((_a3 = mention == null ? void 0 : mention.data) == null ? void 0 : _a3.repoName) || !((_b2 = mention == null ? void 0 : mention.data) == null ? void 0 : _b2.filePath)) {
164230
+ return [];
164231
+ }
164232
+ return await getFileItem(
164233
+ mention.data.repoName,
164234
+ mention.data.filePath,
164235
+ mention.data.rev
164236
+ );
164237
+ }
164238
+ };
164239
+ }
164240
+ async function getFileMentions(repoName, filePath) {
164241
+ const repoRe = `^${escapeRegExp(repoName)}$`;
164242
+ const fileRe = filePath ? escapeRegExp(filePath) : "^.*$";
164243
+ const query2 = `repo:${repoRe} file:${fileRe} type:file count:10`;
164244
+ const dataOrError = await graphqlClient.searchFileMatches(query2);
164245
+ if (isError$1(dataOrError) || dataOrError === null) {
164246
+ return [];
164247
+ }
164248
+ return dataOrError.search.results.results.map((result) => {
164249
+ if (result.__typename !== "FileMatch") {
164250
+ return null;
164251
+ }
164252
+ const url = `${graphqlClient.endpoint.replace(/\/$/, "")}${result.file.url}`;
164253
+ const basename2 = displayPathBasename(URI.parse(result.file.path));
164254
+ return {
164255
+ uri: url,
164256
+ title: basename2,
164257
+ description: result.file.path,
164258
+ data: {
164259
+ repoName: result.repository.name,
164260
+ rev: result.file.commit.oid,
164261
+ filePath: result.file.path
164262
+ }
164263
+ };
164264
+ }).filter(isDefined);
164265
+ }
164266
+ async function getFileItem(repoName, filePath, rev2 = "HEAD") {
164267
+ var _a3, _b2;
164268
+ const dataOrError = await graphqlClient.getFileContents(repoName, filePath, rev2);
164269
+ if (isError$1(dataOrError)) {
164270
+ return [];
164271
+ }
164272
+ const file = (_b2 = (_a3 = dataOrError == null ? void 0 : dataOrError.repository) == null ? void 0 : _a3.commit) == null ? void 0 : _b2.file;
164273
+ if (!file) {
164274
+ return [];
164275
+ }
164276
+ const url = `${graphqlClient.endpoint.replace(/\/$/, "")}${file.url}`;
164277
+ return [
164278
+ {
164279
+ url,
164280
+ title: `${repoName}/${file.path}`,
164281
+ ai: {
164282
+ content: file.content
164283
+ }
164284
+ }
164285
+ ];
164286
+ }
164287
+ function escapeRegExp(str) {
164288
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
164289
+ }
163992
164290
  const RemoteDirectoryProvider = createRemoteDirectoryProvider();
163993
164291
  function createRemoteDirectoryProvider(customTitle) {
163994
164292
  return {
@@ -164019,6 +164317,51 @@ function createRemoteDirectoryProvider(customTitle) {
164019
164317
  }
164020
164318
  };
164021
164319
  }
164320
+ async function getDirectoryMentions(repoName, directoryPath) {
164321
+ const repoRe = `^${escapeRegExp(repoName)}$`;
164322
+ const directoryRe = directoryPath ? escapeRegExp(directoryPath) : "";
164323
+ const query2 = `repo:${repoRe} file:${directoryRe}.*/.* select:file.directory count:10`;
164324
+ const dataOrError = await graphqlClient.searchFileMatches(query2);
164325
+ if (isError$1(dataOrError) || dataOrError === null) {
164326
+ return [];
164327
+ }
164328
+ return dataOrError.search.results.results.map((result) => {
164329
+ if (result.__typename !== "FileMatch") {
164330
+ return null;
164331
+ }
164332
+ const url = `${graphqlClient.endpoint.replace(/\/$/, "")}${result.file.url}`;
164333
+ return {
164334
+ uri: url,
164335
+ title: result.file.path,
164336
+ description: " ",
164337
+ data: {
164338
+ repoName: result.repository.name,
164339
+ repoID: result.repository.id,
164340
+ rev: result.file.commit.oid,
164341
+ directoryPath: result.file.path
164342
+ }
164343
+ };
164344
+ }).filter(isDefined);
164345
+ }
164346
+ async function getDirectoryItem(query2, repoID, directoryPath) {
164347
+ const dataOrError = await graphqlClient.contextSearch({
164348
+ repoIDs: [repoID],
164349
+ query: query2,
164350
+ filePatterns: [`^${directoryPath}.*`]
164351
+ });
164352
+ if (isError$1(dataOrError) || dataOrError === null) {
164353
+ return [];
164354
+ }
164355
+ return dataOrError.map(
164356
+ (node) => ({
164357
+ url: node.uri.toString(),
164358
+ title: node.path,
164359
+ ai: {
164360
+ content: node.content
164361
+ }
164362
+ })
164363
+ );
164364
+ }
164022
164365
  const RemoteRepositorySearch = createRemoteRepositoryProvider();
164023
164366
  function createRemoteRepositoryProvider(customTitle) {
164024
164367
  return {
@@ -164196,7 +164539,7 @@ function getOpenCtxProviders(configChanges, authStatusChanges, isValidSiteVersio
164196
164539
  providerUri: WEB_PROVIDER_URI
164197
164540
  }
164198
164541
  ];
164199
- if (!authStatus.isDotCom) {
164542
+ if (!isDotCom(authStatus)) {
164200
164543
  providers.push({
164201
164544
  settings: true,
164202
164545
  provider: RemoteRepositorySearch,
@@ -164208,11 +164551,6 @@ function getOpenCtxProviders(configChanges, authStatusChanges, isValidSiteVersio
164208
164551
  provider: RemoteDirectoryProvider,
164209
164552
  providerUri: RemoteDirectoryProvider.providerUri
164210
164553
  });
164211
- providers.push({
164212
- settings: true,
164213
- provider: CurrentRepositoryDirectoryProvider,
164214
- providerUri: CURRENT_REPOSITORY_DIRECTORY_PROVIDER_URI
164215
- });
164216
164554
  }
164217
164555
  providers.push({
164218
164556
  settings: true,
@@ -164632,7 +164970,7 @@ const getInput = async (document2, initialValues, source) => {
164632
164970
  const initialCursorPosition = editor.selection.active;
164633
164971
  let activeRange = initialValues.initialExpandedRange || initialValues.initialRange;
164634
164972
  let activeRangeItem = initialValues.initialIntent === "add" ? CURSOR_RANGE_ITEM : initialValues.initialExpandedRange ? EXPANDED_RANGE_ITEM : SELECTION_RANGE_ITEM;
164635
- const authStatus = authProvider.instance.getAuthStatus();
164973
+ const authStatus = authProvider.instance.statusAuthed;
164636
164974
  const isCodyPro = !authStatus.userCanUpgrade;
164637
164975
  const modelOptions = modelsService.instance.getModels(ModelUsage.Edit);
164638
164976
  const modelItems = getModelOptionItems(modelOptions, isCodyPro);
@@ -164921,7 +165259,7 @@ const getInput = async (document2, initialValues, source) => {
164921
165259
  });
164922
165260
  };
164923
165261
  function getOverridenModelForIntent(intent, currentModel, authStatus) {
164924
- if (!authStatus.isDotCom) {
165262
+ if (!isDotCom(authStatus)) {
164925
165263
  return currentModel;
164926
165264
  }
164927
165265
  switch (intent) {
@@ -165890,7 +166228,7 @@ class FixupController {
165890
166228
  return task;
165891
166229
  }
165892
166230
  async createTask(document2, instruction, userContextFiles, selectionRange, intent, mode, model2, source, destinationFile, insertionPoint, telemetryMetadata, taskId) {
165893
- const authStatus = authProvider.instance.getAuthStatus();
166231
+ const authStatus = authProvider.instance.status;
165894
166232
  const overridenModel = getOverridenModelForIntent(intent, model2, authStatus);
165895
166233
  const fixupFile = this.files.forUri(document2.uri);
165896
166234
  const task = new FixupTask(
@@ -167437,6 +167775,7 @@ class EditProvider {
167437
167775
  this.config.controller.startTask(this.config.task);
167438
167776
  const model2 = this.config.task.model;
167439
167777
  const contextWindow = modelsService.instance.getContextWindowByID(model2);
167778
+ const authStatus = authProvider.instance.statusAuthed;
167440
167779
  const {
167441
167780
  messages,
167442
167781
  stopSequences,
@@ -167444,7 +167783,7 @@ class EditProvider {
167444
167783
  responsePrefix = ""
167445
167784
  } = await buildInteraction$1({
167446
167785
  model: model2,
167447
- codyApiVersion: authProvider.instance.getAuthStatus().codyApiVersion,
167786
+ codyApiVersion: authStatus.codyApiVersion,
167448
167787
  contextWindow: contextWindow.input,
167449
167788
  task: this.config.task,
167450
167789
  editor: this.config.editor
@@ -167526,7 +167865,7 @@ class EditProvider {
167526
167865
  void this.handleResponse(text, false);
167527
167866
  return;
167528
167867
  }
167529
- if (isNetworkError(err2)) {
167868
+ if (isNetworkLikeError(err2)) {
167530
167869
  err2 = new Error("Cody could not respond due to network error.");
167531
167870
  }
167532
167871
  this.handleError(err2);
@@ -167551,7 +167890,6 @@ class EditProvider {
167551
167890
  return this.handleResponse(response, false);
167552
167891
  }
167553
167892
  async handleResponse(response, isMessageInProgress) {
167554
- var _a3;
167555
167893
  if (!response && !isMessageInProgress) {
167556
167894
  this.handleError(new Error("Cody did not respond with any text"));
167557
167895
  }
@@ -167573,7 +167911,7 @@ class EditProvider {
167573
167911
  ...countCode(response)
167574
167912
  };
167575
167913
  const { metadata: metadata2, privateMetadata } = splitSafeMetadata(legacyMetadata);
167576
- const endpoint = (_a3 = authProvider.instance.getAuthStatus()) == null ? void 0 : _a3.endpoint;
167914
+ const endpoint = authProvider.instance.status.endpoint;
167577
167915
  telemetryRecorder.recordEvent("cody.fixup.response", "hasCode", {
167578
167916
  metadata: metadata2,
167579
167917
  privateMetadata: {
@@ -167806,6 +168144,14 @@ class EditManager {
167806
168144
  model: task.model
167807
168145
  }
167808
168146
  });
168147
+ if (editor.active && (intent === "doc" || intent === "test")) {
168148
+ const newPosition = proposedRange.start;
168149
+ editor.active.selection = new Selection(newPosition, newPosition);
168150
+ editor.active.revealRange(
168151
+ new Range(newPosition, newPosition),
168152
+ TextEditorRevealType.InCenter
168153
+ );
168154
+ }
167809
168155
  const provider = this.getProviderForTask(task);
167810
168156
  await provider.startEdit();
167811
168157
  return task;
@@ -167864,6 +168210,7 @@ class EditManager {
167864
168210
  const documentRange = new Range(0, 0, document2.lineCount, 0);
167865
168211
  editor.setDecorations(SMART_APPLY_FILE_DECORATION, [documentRange]);
167866
168212
  const replacementCode = PromptString.unsafe_fromLLMResponse(configuration2.replacement);
168213
+ const authStatus = authProvider.instance.statusAuthed;
167867
168214
  const selection = await getSmartApplySelection(
167868
168215
  configuration2.id,
167869
168216
  configuration2.instruction,
@@ -167871,7 +168218,7 @@ class EditManager {
167871
168218
  configuration2.document,
167872
168219
  model2,
167873
168220
  this.options.chat,
167874
- authProvider.instance.getAuthStatus().codyApiVersion
168221
+ authStatus.codyApiVersion
167875
168222
  );
167876
168223
  editor.setDecorations(SMART_APPLY_FILE_DECORATION, []);
167877
168224
  if (!selection) {
@@ -168324,8 +168671,8 @@ async function configureExternalServices(context2, config, platform2) {
168324
168671
  Please check that the repository exists. You can override the repository with the "cody.codebase" setting.`
168325
168672
  );
168326
168673
  }
168327
- const localEmbeddings = authProvider.instance.getAuthStatus().isLoggedIn && authProvider.instance.getAuthStatus().isDotCom ? await ((_d2 = platform2.createLocalEmbeddingsController) == null ? void 0 : _d2.call(platform2, initialConfig)) : void 0;
168328
- const chatClient = new ChatClient(completionsClient, () => authProvider.instance.getAuthStatus());
168674
+ const localEmbeddings = authProvider.instance.status.authenticated && isDotCom(authProvider.instance.status) ? await ((_d2 = platform2.createLocalEmbeddingsController) == null ? void 0 : _d2.call(platform2, initialConfig)) : void 0;
168675
+ const chatClient = new ChatClient(completionsClient, () => authProvider.instance.statusAuthed);
168329
168676
  const guardrails = new SourcegraphGuardrailsClient(graphqlClient, initialConfig);
168330
168677
  const contextAPIClient = new ContextAPIClient(graphqlClient);
168331
168678
  return {
@@ -169345,7 +169692,7 @@ class MinionController extends ReactPanelController {
169345
169692
  }
169346
169693
  }
169347
169694
  async handleSetSession(id) {
169348
- const storedSessionState = await this.storage.load(authProvider.instance.getAuthStatus(), id);
169695
+ const storedSessionState = await this.storage.load(authProvider.instance.status, id);
169349
169696
  if (!storedSessionState) {
169350
169697
  throw new Error(`session not found with id: ${id}`);
169351
169698
  }
@@ -169361,7 +169708,7 @@ class MinionController extends ReactPanelController {
169361
169708
  this.postUpdateSessionIds();
169362
169709
  }
169363
169710
  async handleClearHistory() {
169364
- await this.storage.clear(authProvider.instance.getAuthStatus());
169711
+ await this.storage.clear(authProvider.instance.status);
169365
169712
  if (this.sessionState) {
169366
169713
  await this.save();
169367
169714
  }
@@ -169436,7 +169783,7 @@ class MinionController extends ReactPanelController {
169436
169783
  if (!this.sessionState) {
169437
169784
  throw new Error("no session to save");
169438
169785
  }
169439
- await this.storage.save(authProvider.instance.getAuthStatus(), {
169786
+ await this.storage.save(authProvider.instance.status, {
169440
169787
  session: this.sessionState.session
169441
169788
  });
169442
169789
  }
@@ -169494,7 +169841,7 @@ class MinionController extends ReactPanelController {
169494
169841
  var _a3;
169495
169842
  this.postMessage({
169496
169843
  type: "update-session-ids",
169497
- sessionIds: await this.storage.listIds(authProvider.instance.getAuthStatus()),
169844
+ sessionIds: await this.storage.listIds(authProvider.instance.status),
169498
169845
  currentSessionId: (_a3 = this.sessionState) == null ? void 0 : _a3.session.id
169499
169846
  });
169500
169847
  }
@@ -169618,8 +169965,8 @@ const _CodyProExpirationNotifications = class _CodyProExpirationNotifications {
169618
169965
  () => setTimeout(() => this.triggerExpirationCheck(), this.autoUpdateDelay)
169619
169966
  );
169620
169967
  }
169621
- const authStatus = authProvider.instance.getAuthStatus();
169622
- if (!authStatus.isLoggedIn || !authStatus.isDotCom) return;
169968
+ const authStatus = authProvider.instance.status;
169969
+ if (!authStatus.authenticated || !isDotCom(authStatus)) return;
169623
169970
  const useSscForCodySubscription = await featureFlagProvider.instance.evaluateFeatureFlag(
169624
169971
  FeatureFlag.UseSscForCodySubscription
169625
169972
  );
@@ -169847,7 +170194,7 @@ const showFeedbackSupportQuickPick = async () => {
169847
170194
  function groupCodyChats(authStatus) {
169848
170195
  var _a3, _b2, _c2, _d2;
169849
170196
  const chatHistoryGroups = /* @__PURE__ */ new Map();
169850
- if (!authStatus) {
170197
+ if (!authStatus || !authStatus.authenticated) {
169851
170198
  return null;
169852
170199
  }
169853
170200
  const chats = (_a3 = chatHistory.getLocalHistory(authStatus)) == null ? void 0 : _a3.chat;
@@ -169873,16 +170220,10 @@ function groupCodyChats(authStatus) {
169873
170220
  if (!chatHistoryGroups.has(timeUnit)) {
169874
170221
  chatHistoryGroups.set(timeUnit, []);
169875
170222
  }
169876
- const chatItem = {
170223
+ (_d2 = chatHistoryGroups.get(timeUnit)) == null ? void 0 : _d2.push({
169877
170224
  id,
169878
- title: chatTitle,
169879
- icon: "comment-discussion",
169880
- command: {
169881
- command: "cody.chat.panel.restore",
169882
- args: [id, chatTitle]
169883
- }
169884
- };
169885
- (_d2 = chatHistoryGroups.get(timeUnit)) == null ? void 0 : _d2.push(chatItem);
170225
+ title: chatTitle
170226
+ });
169886
170227
  }
169887
170228
  }
169888
170229
  return Object.fromEntries(chatHistoryGroups);
@@ -170126,9 +170467,9 @@ function createStatusBar() {
170126
170467
  let authStatus;
170127
170468
  const command = commands$1.registerCommand(STATUS_BAR_INTERACTION_COMMAND, async () => {
170128
170469
  telemetryRecorder.recordEvent("cody.statusbarIcon", "clicked", {
170129
- privateMetadata: { loggedIn: Boolean(authStatus == null ? void 0 : authStatus.isLoggedIn) }
170470
+ privateMetadata: { loggedIn: Boolean(authStatus == null ? void 0 : authStatus.authenticated) }
170130
170471
  });
170131
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
170472
+ if (!(authStatus == null ? void 0 : authStatus.authenticated)) {
170132
170473
  void commands$1.executeCommand("cody.chat.focus");
170133
170474
  return;
170134
170475
  }
@@ -170303,19 +170644,19 @@ function createStatusBar() {
170303
170644
  statusBarItem2.tooltip = isCodyIgnoredType ? DEFAULT_TOOLTIP_DISABLED : DEFAULT_TOOLTIP;
170304
170645
  }
170305
170646
  if (authStatus) {
170306
- if (authStatus.isOfflineMode) {
170647
+ if (authStatus.authenticated && authStatus.isOfflineMode) {
170307
170648
  statusBarItem2.text = "$(cody-logo-heavy) Offline";
170308
170649
  statusBarItem2.tooltip = "Cody is in offline mode";
170309
170650
  statusBarItem2.backgroundColor = new ThemeColor("statusBarItem.warningBackground");
170310
170651
  return;
170311
170652
  }
170312
- if (authStatus.showNetworkError) {
170653
+ if (!authStatus.authenticated && authStatus.showNetworkError) {
170313
170654
  statusBarItem2.text = "$(cody-logo-heavy) Connection Issues";
170314
170655
  statusBarItem2.tooltip = "Resolve network issues for Cody to work again";
170315
170656
  statusBarItem2.backgroundColor = new ThemeColor("statusBarItem.errorBackground");
170316
170657
  return;
170317
170658
  }
170318
- if (!authStatus.isLoggedIn) {
170659
+ if (!authStatus.authenticated) {
170319
170660
  statusBarItem2.text = "$(cody-logo-heavy) Sign In";
170320
170661
  statusBarItem2.tooltip = "Sign in to get started with Cody";
170321
170662
  statusBarItem2.backgroundColor = new ThemeColor("statusBarItem.warningBackground");
@@ -170876,96 +171217,6 @@ function removeContextRows(document2, supercompletion) {
170876
171217
  updated: newUpdated
170877
171218
  };
170878
171219
  }
170879
- class RecentEditsRetriever {
170880
- constructor(maxAgeMs, workspace$1 = workspace) {
170881
- __publicField2(this, "disposables", []);
170882
- // We use a map from the document URI to the set of tracked completions inside that document to
170883
- // improve performance of the `onDidChangeTextDocument` event handler.
170884
- __publicField2(this, "trackedDocuments", /* @__PURE__ */ new Map());
170885
- this.maxAgeMs = maxAgeMs;
170886
- this.workspace = workspace$1;
170887
- this.disposables.push(workspace$1.onDidChangeTextDocument(this.onDidChangeTextDocument.bind(this)));
170888
- this.disposables.push(workspace$1.onDidRenameFiles(this.onDidRenameFiles.bind(this)));
170889
- this.disposables.push(workspace$1.onDidDeleteFiles(this.onDidDeleteFiles.bind(this)));
170890
- }
170891
- async getDiff(uri2) {
170892
- if (await contextFiltersProvider.instance.isUriIgnored(uri2)) {
170893
- return null;
170894
- }
170895
- const trackedDocument = this.trackedDocuments.get(uri2.toString());
170896
- if (!trackedDocument) {
170897
- return null;
170898
- }
170899
- const oldContent = trackedDocument.content;
170900
- const newContent = applyChanges(
170901
- oldContent,
170902
- trackedDocument.changes.map((c) => c.change)
170903
- );
170904
- return PromptString.fromGitDiff(uri2, oldContent, newContent);
170905
- }
170906
- onDidChangeTextDocument(event) {
170907
- let trackedDocument = this.trackedDocuments.get(event.document.uri.toString());
170908
- if (!trackedDocument) {
170909
- trackedDocument = this.trackDocument(event.document);
170910
- }
170911
- const now2 = Date.now();
170912
- for (const change of event.contentChanges) {
170913
- trackedDocument.changes.push({
170914
- timestamp: now2,
170915
- change
170916
- });
170917
- }
170918
- this.reconcileOutdatedChanges();
170919
- }
170920
- onDidRenameFiles(event) {
170921
- for (const file of event.files) {
170922
- const trackedDocument = this.trackedDocuments.get(file.oldUri.toString());
170923
- if (trackedDocument) {
170924
- this.trackedDocuments.set(file.newUri.toString(), trackedDocument);
170925
- this.trackedDocuments.delete(file.oldUri.toString());
170926
- }
170927
- }
170928
- }
170929
- onDidDeleteFiles(event) {
170930
- for (const uri2 of event.files) {
170931
- this.trackedDocuments.delete(uri2.toString());
170932
- }
170933
- }
170934
- dispose() {
170935
- this.trackedDocuments.clear();
170936
- for (const disposable of this.disposables) {
170937
- disposable.dispose();
170938
- }
170939
- }
170940
- trackDocument(document2) {
170941
- const trackedDocument = {
170942
- content: document2.getText(),
170943
- changes: []
170944
- };
170945
- this.trackedDocuments.set(document2.uri.toString(), trackedDocument);
170946
- return trackedDocument;
170947
- }
170948
- reconcileOutdatedChanges() {
170949
- const now2 = Date.now();
170950
- for (const [, trackedDocument] of this.trackedDocuments) {
170951
- const firstNonOutdatedChangeIndex = trackedDocument.changes.findIndex(
170952
- (c) => now2 - c.timestamp < this.maxAgeMs
170953
- );
170954
- const outdatedChanges = trackedDocument.changes.slice(0, firstNonOutdatedChangeIndex);
170955
- trackedDocument.content = applyChanges(
170956
- trackedDocument.content,
170957
- outdatedChanges.map((c) => c.change)
170958
- );
170959
- trackedDocument.changes = trackedDocument.changes.slice(firstNonOutdatedChangeIndex);
170960
- }
170961
- }
170962
- }
170963
- function applyChanges(content, changes) {
170964
- for (const change of changes) {
170965
- content = content.slice(0, change.rangeOffset) + change.text + content.slice(change.rangeOffset + change.rangeLength);
170966
- }
170967
- return content;
170968
- }
170969
171220
  const GHOST_TEXT_COLOR = new ThemeColor("editorGhostText.foreground");
170970
171221
  const reviewHintDecorationType = window$1.createTextEditorDecorationType({
170971
171222
  after: {
@@ -171330,7 +171581,10 @@ async function start(context2, platform2) {
171330
171581
  }
171331
171582
  const register = async (context2, configWatcher, platform2, isExtensionModeDevOrTest) => {
171332
171583
  const disposables = [];
171333
- setClientNameVersion(platform2.extensionClient.clientName, platform2.extensionClient.clientVersion);
171584
+ setClientNameVersion(
171585
+ platform2.extensionClient.httpClientNameForLegacyReasons ?? platform2.extensionClient.clientName,
171586
+ platform2.extensionClient.clientVersion
171587
+ );
171334
171588
  disposables.push(manageDisplayPathEnvInfoForExtension());
171335
171589
  await initializeSingletons(platform2, configWatcher, isExtensionModeDevOrTest, disposables);
171336
171590
  disposables.push(await initVSCodeGitApi());
@@ -171384,7 +171638,8 @@ const register = async (context2, configWatcher, platform2, isExtensionModeDevOr
171384
171638
  localEmbeddings,
171385
171639
  symfRunner,
171386
171640
  contextAPIClient,
171387
- contextRetriever
171641
+ contextRetriever,
171642
+ configWatcher
171388
171643
  },
171389
171644
  disposables
171390
171645
  );
@@ -171448,7 +171703,10 @@ async function initializeSingletons(platform2, configWatcher, isExtensionModeDev
171448
171703
  void localStorage.setConfig(config);
171449
171704
  graphqlClient.setConfig(config);
171450
171705
  void featureFlagProvider.instance.refresh();
171451
- contextFiltersProvider.instance.init(repoNameResolver.getRepoNamesFromWorkspaceUri);
171706
+ contextFiltersProvider.instance.init(
171707
+ repoNameResolver.getRepoNamesFromWorkspaceUri,
171708
+ authProvider.instance
171709
+ );
171452
171710
  void modelsService.instance.onConfigChange(config);
171453
171711
  upstreamHealthProvider.instance.onConfigurationChange(config);
171454
171712
  }
@@ -171586,7 +171844,7 @@ function registerChatCommands(disposables) {
171586
171844
  commands$1.executeCommand("workbench.action.moveEditorToNewWindow");
171587
171845
  }),
171588
171846
  commands$1.registerCommand("cody.chat.history.panel", async () => {
171589
- await displayHistoryQuickPick(authProvider.instance.getAuthStatus());
171847
+ await displayHistoryQuickPick(authProvider.instance.status);
171590
171848
  }),
171591
171849
  commands$1.registerCommand(
171592
171850
  "cody.settings.extension.chat",
@@ -171602,13 +171860,16 @@ function registerChatCommands(disposables) {
171602
171860
  }
171603
171861
  function registerAuthCommands(disposables) {
171604
171862
  disposables.push(
171605
- commands$1.registerCommand("cody.auth.signin", () => authProvider.instance.signinMenu()),
171606
- commands$1.registerCommand("cody.auth.signout", () => authProvider.instance.signoutMenu()),
171607
- commands$1.registerCommand("cody.auth.account", () => authProvider.instance.accountMenu()),
171863
+ commands$1.registerCommand("cody.auth.signin", () => showSignInMenu()),
171864
+ commands$1.registerCommand("cody.auth.signout", () => showSignOutMenu()),
171865
+ commands$1.registerCommand("cody.auth.account", () => showAccountMenu()),
171608
171866
  commands$1.registerCommand("cody.auth.support", () => showFeedbackSupportQuickPick()),
171609
171867
  commands$1.registerCommand(
171610
171868
  "cody.auth.status",
171611
- () => authProvider.instance.getAuthStatus()
171869
+ () => {
171870
+ var _a3;
171871
+ return ((_a3 = authProvider.instance) == null ? void 0 : _a3.statusOrNotReadyYet) ?? null;
171872
+ }
171612
171873
  ),
171613
171874
  // Used by the agent
171614
171875
  commands$1.registerCommand(
@@ -171636,14 +171897,14 @@ function registerUpgradeHandlers(configWatcher, disposables) {
171636
171897
  handleUri: async (uri2) => {
171637
171898
  if (uri2.path === "/app-done") ;
171638
171899
  else {
171639
- authProvider.instance.tokenCallbackHandler(uri2, configWatcher.get().customHeaders);
171900
+ tokenCallbackHandler(uri2, configWatcher.get().customHeaders);
171640
171901
  }
171641
171902
  }
171642
171903
  }),
171643
171904
  // Check if user has just moved back from a browser window to upgrade cody pro
171644
171905
  window$1.onDidChangeWindowState(async (ws) => {
171645
- const authStatus = authProvider.instance.getAuthStatus();
171646
- if (ws.focused && authStatus.isDotCom && authStatus.isLoggedIn) {
171906
+ const authStatus = authProvider.instance.status;
171907
+ if (ws.focused && isDotCom(authStatus) && authStatus.authenticated) {
171647
171908
  const res = await graphqlClient.getCurrentUserCodyProEnabled();
171648
171909
  if (res instanceof Error) {
171649
171910
  logError$1("onDidChangeWindowState", "getCurrentUserCodyProEnabled", res);
@@ -171696,7 +171957,7 @@ async function registerDebugCommands(context2, disposables) {
171696
171957
  }
171697
171958
  async function tryRegisterTutorial(context2, disposables) {
171698
171959
  if (!isRunningInsideAgent()) {
171699
- const { registerInteractiveTutorial } = await import("./index-D6VgQlqI.mjs");
171960
+ const { registerInteractiveTutorial } = await import("./index-CoR5ltqq.mjs");
171700
171961
  registerInteractiveTutorial(context2).then((disposable) => disposables.push(...disposable));
171701
171962
  }
171702
171963
  }
@@ -171789,7 +172050,8 @@ function registerChat({
171789
172050
  localEmbeddings,
171790
172051
  symfRunner,
171791
172052
  contextAPIClient,
171792
- contextRetriever
172053
+ contextRetriever,
172054
+ configWatcher
171793
172055
  }, disposables) {
171794
172056
  const messageProviderOptions = {
171795
172057
  chat: chatClient,
@@ -171809,7 +172071,8 @@ function registerChat({
171809
172071
  contextRetriever,
171810
172072
  guardrails,
171811
172073
  contextAPIClient || null,
171812
- platform2.extensionClient
172074
+ platform2.extensionClient,
172075
+ configWatcher
171813
172076
  );
171814
172077
  chatsController.registerViewsAndCommands();
171815
172078
  const ghostHintDecorator = new GhostHintDecorator();