@sourcegraph/cody-web 0.7.4 → 0.7.6

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, aV 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, b8 as isError$1, bb as isDefined, bJ as onAbort, bK as CHAT_OUTPUT_TOKEN_BUDGET, bk as ModelTag, b3 as CodyIDE, bL as isEnterpriseUser, b2 as isCodyProUser, bt 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, aL 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, b7 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 requireBase64Js, b5 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, bj as isCodyProModel, b6 as CodyTaskState, aT as createExtensionAPI, aU as createMessageAPIForWebview, be 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, bw as setDisplayPathEnvInfo, bq 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, au as displayPath, cH as uriParseNameAndExtension, cI as uriDirname, an as FILE_CONTEXT_MENTION_PROVIDER, ao as SYMBOL_CONTEXT_MENTION_PROVIDER, ap as REMOTE_REPOSITORY_PROVIDER_URI, cJ as promiseFactoryToObservable, cK as webMentionProvidersMetadata, cL as allMentionProvidersMetadata, cM as combineLatest$1, cN as expandToLineRange, am as displayPathBasename, av as displayLineRange, cO as truncateTextNearestLine, cP as TokenCounter, bp as View, aQ as parseMentionQuery, cQ as tracer, bd as isAbortErrorOrSocketHangUp, cR as isContextWindowLimitError, cS as truncatePromptString, cT as inputTextWithoutContextChipsFromPromptEditorState, bc as reformatBotMessageForChat, b1 as hydrateAfterPostMessage, cU as addMessageListenersForExtensionAPI, cV as createMessageAPIForExtension, cW as startWith$1, cX as promiseToObservable$1, cY as CODY_PASSTHROUGH_VSCODE_OPEN_COMMAND_ID, cZ as editorStateFromPromptString, c_ as getEditorTabSize$1, bi as pluralize, c$ as AbortError, d0 as getEditorIndentString, b9 as RateLimitError$1, d1 as logResponseHeadersToSpan, d2 as TracedError, d3 as isNodeResponse, d4 as SpanStatusCode, aq as REMOTE_FILE_PROVIDER_URI, as as CURRENT_REPOSITORY_DIRECTORY_PROVIDER_URI, d5 as assertFileURI, ar as REMOTE_DIRECTORY_PROVIDER_URI, at as WEB_PROVIDER_URI, d6 as setOpenCtx, d7 as GIT_OPENCTX_PROVIDER_URI, d8 as ACCOUNT_UPGRADE_URL, aZ as scanForMentionTriggerInUserTextInput, ay as LARGE_FILE_WARNING_LABEL, d9 as GENERAL_HELP_LABEL, da as diffLines, db as psDedent, dc as languageFromFilename, dd as ProgrammingLanguage, de as truncatePromptStringStart, df as posixFilePaths, dg as CODY_DOC_URL, ba as CODY_FEEDBACK_URL, dh as DISCORD_URL, di as CODY_SUPPORT_URL, br as getRelativeChatPeriod, dj as SG_BLOG_URL, dk as ACCOUNT_LIMITS_INFO_URL, dl as setLogger, dm as CODY_OLLAMA_DOCS_URL, bu as browser$3 } from "./browser-5V4RMNo3.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,25 @@ 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;
8408
+ var DefaultChatCommands = /* @__PURE__ */ ((DefaultChatCommands2) => {
8409
+ DefaultChatCommands2["Explain"] = "explain";
8410
+ DefaultChatCommands2["Unit"] = "unit";
8411
+ DefaultChatCommands2["Smell"] = "smell";
8412
+ DefaultChatCommands2["Custom"] = "custom-chat";
8413
+ return DefaultChatCommands2;
8414
+ })(DefaultChatCommands || {});
8415
+ var DefaultEditCommands = /* @__PURE__ */ ((DefaultEditCommands2) => {
8416
+ DefaultEditCommands2["Test"] = "test";
8417
+ DefaultEditCommands2["Doc"] = "doc";
8418
+ DefaultEditCommands2["Edit"] = "edit";
8419
+ DefaultEditCommands2["Custom"] = "custom-edit";
8420
+ return DefaultEditCommands2;
8421
+ })(DefaultEditCommands || {});
8422
+ var CustomCommandType = /* @__PURE__ */ ((CustomCommandType2) => {
8423
+ CustomCommandType2["Workspace"] = "workspace";
8424
+ CustomCommandType2["User"] = "user";
8425
+ return CustomCommandType2;
8426
+ })(CustomCommandType || {});
8462
8427
  var define_process_default$j = { env: {} };
8463
8428
  var FeatureFlag = /* @__PURE__ */ ((FeatureFlag2) => {
8464
8429
  FeatureFlag2["TestFlagDoNotUse"] = "test-flag-do-not-use";
@@ -17859,8 +17824,8 @@ const capabilities = {
17859
17824
  };
17860
17825
  const dependencies = {
17861
17826
  "@anthropic-ai/sdk": "^0.20.8",
17862
- "@openctx/provider-linear-issues": "^0.0.6",
17863
- "@openctx/vscode-lib": "^0.0.21",
17827
+ "@openctx/provider-linear-issues": "^0.0.7",
17828
+ "@openctx/vscode-lib": "^0.0.22",
17864
17829
  "@opentelemetry/api": "^1.7.0",
17865
17830
  "@opentelemetry/core": "^1.18.1",
17866
17831
  "@opentelemetry/exporter-trace-otlp-http": "^0.45.1",
@@ -19715,10 +19680,6 @@ const emptyFileWatcher = {
19715
19680
  let clientInfo;
19716
19681
  function setClientInfo(newClientInfo) {
19717
19682
  clientInfo = newClientInfo;
19718
- setClientNameVersion(
19719
- clientInfo.legacyNameForServerIdentification ?? clientInfo.name,
19720
- clientInfo.version
19721
- );
19722
19683
  if (newClientInfo.extensionConfiguration) {
19723
19684
  setExtensionConfiguration(newClientInfo.extensionConfiguration);
19724
19685
  }
@@ -33545,52 +33506,47 @@ function getOSArch() {
33545
33506
  arch: arch2
33546
33507
  };
33547
33508
  }
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;
33509
+ class AuthProviderSimplified {
33510
+ async openExternalAuthUrl(method, tokenReceiverUrl) {
33511
+ if (!await openExternalAuthUrl(method, tokenReceiverUrl)) {
33512
+ return false;
33513
+ }
33514
+ authProvider.instance.setAuthPendingToEndpoint(DOTCOM_URL.toString());
33515
+ return true;
33557
33516
  }
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...";
33517
+ }
33518
+ function getAuthReferralCode() {
33519
+ return {
33520
+ "vscode-insiders": "CODY_INSIDERS",
33521
+ vscodium: "CODY_VSCODIUM",
33522
+ cursor: "CODY_CURSOR"
33523
+ }[env.uriScheme] || "CODY";
33524
+ }
33525
+ function openExternalAuthUrl(provider, tokenReceiverUrl) {
33526
+ const referralCode = getAuthReferralCode();
33527
+ const tokenReceiver = tokenReceiverUrl ? `&tokenReceiverUrl=${encodeURIComponent(tokenReceiverUrl)}` : "";
33528
+ const newTokenUrl = `/user/settings/tokens/new/callback?requestFrom=${referralCode}${tokenReceiver}`;
33529
+ const site = new URL(newTokenUrl, DOTCOM_URL);
33530
+ const genericLoginUrl = `${site}sign-in?returnTo=${newTokenUrl}`;
33531
+ const gitHubLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=github&pc=sams&redirect=${newTokenUrl}`;
33532
+ const gitLabLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=gitlab&pc=sams&redirect=${newTokenUrl}`;
33533
+ const googleLoginUrl = `${site}.auth/openidconnect/login?prompt_auth=google&pc=sams&redirect=${newTokenUrl}`;
33534
+ let uriSpec;
33535
+ switch (provider) {
33536
+ case "github":
33537
+ uriSpec = gitHubLoginUrl;
33538
+ break;
33539
+ case "gitlab":
33540
+ uriSpec = gitLabLoginUrl;
33541
+ break;
33542
+ case "google":
33543
+ uriSpec = googleLoginUrl;
33544
+ break;
33591
33545
  default:
33592
- return void 0;
33546
+ uriSpec = genericLoginUrl;
33547
+ break;
33593
33548
  }
33549
+ return env.openExternal(uriSpec);
33594
33550
  }
33595
33551
  let runningAuthProgressIndicator = null;
33596
33552
  function startAuthProgressIndicator() {
@@ -33614,38 +33570,285 @@ function closeAuthProgressIndicator() {
33614
33570
  runningAuthProgressIndicator == null ? void 0 : runningAuthProgressIndicator();
33615
33571
  runningAuthProgressIndicator = null;
33616
33572
  }
33573
+ async function showSignInMenu(type2, uri2) {
33574
+ const authStatus = authProvider.instance.status;
33575
+ const mode = authStatus.authenticated ? "switch" : "signin";
33576
+ logDebug("AuthProvider:signinMenu", mode);
33577
+ telemetryRecorder.recordEvent("cody.auth.login", "clicked");
33578
+ const item = await showAuthMenu(mode);
33579
+ if (!item) {
33580
+ return;
33581
+ }
33582
+ const menuID = item == null ? void 0 : item.id;
33583
+ telemetryRecorder.recordEvent("cody.auth.signin.menu", "clicked", {
33584
+ privateMetadata: { menuID }
33585
+ });
33586
+ switch (menuID) {
33587
+ case "enterprise": {
33588
+ const instanceUrl = await showInstanceURLInputBox(item.uri);
33589
+ if (!instanceUrl) {
33590
+ return;
33591
+ }
33592
+ authProvider.instance.setAuthPendingToEndpoint(instanceUrl);
33593
+ redirectToEndpointLogin(instanceUrl);
33594
+ break;
33595
+ }
33596
+ case "dotcom":
33597
+ redirectToEndpointLogin(DOTCOM_URL.href);
33598
+ break;
33599
+ case "token": {
33600
+ const instanceUrl = await showInstanceURLInputBox(item.uri);
33601
+ if (!instanceUrl) {
33602
+ return;
33603
+ }
33604
+ await signinMenuForInstanceUrl(instanceUrl);
33605
+ break;
33606
+ }
33607
+ default: {
33608
+ const selectedEndpoint = item.uri;
33609
+ const token = await secretStorage.get(selectedEndpoint);
33610
+ let authStatus2 = await authProvider.instance.auth({
33611
+ endpoint: selectedEndpoint,
33612
+ token: token || null
33613
+ });
33614
+ if (!(authStatus2 == null ? void 0 : authStatus2.authenticated)) {
33615
+ const newToken = await showAccessTokenInputBox(item.uri);
33616
+ if (!newToken) {
33617
+ return;
33618
+ }
33619
+ authStatus2 = await authProvider.instance.auth({
33620
+ endpoint: selectedEndpoint,
33621
+ token: newToken || null
33622
+ });
33623
+ }
33624
+ await showAuthResultMessage(selectedEndpoint, authStatus2);
33625
+ logDebug("AuthProvider:signinMenu", mode, selectedEndpoint);
33626
+ }
33627
+ }
33628
+ }
33629
+ function getItemLabel$1(uri2, current) {
33630
+ const icon2 = current ? "$(check) " : "";
33631
+ if (isDotCom(uri2)) {
33632
+ return `${icon2}Sourcegraph.com`;
33633
+ }
33634
+ return `${icon2}${uri2}`;
33635
+ }
33636
+ async function showAuthMenu(type2) {
33637
+ const endpointHistory = localStorage.getEndpointHistory() ?? [];
33638
+ const historySize = endpointHistory == null ? void 0 : endpointHistory.length;
33639
+ const history = historySize > 0 ? endpointHistory == null ? void 0 : endpointHistory.map((uri2, i) => ({
33640
+ id: uri2,
33641
+ label: getItemLabel$1(uri2, type2 === "switch" && i === historySize - 1),
33642
+ description: "",
33643
+ uri: uri2
33644
+ })).reverse() : [];
33645
+ const separator = [{ label: type2 === "signin" ? "previously used" : "current", kind: -1 }];
33646
+ const optionItems = [...LoginMenuOptionItems, ...separator, ...history];
33647
+ const option = await window$1.showQuickPick(
33648
+ optionItems,
33649
+ AuthMenuOptions[type2]
33650
+ );
33651
+ return option;
33652
+ }
33653
+ async function showInstanceURLInputBox(title) {
33654
+ const result = await window$1.showInputBox({
33655
+ title,
33656
+ prompt: "Enter the URL of the Sourcegraph instance. For example, https://sourcegraph.example.com.",
33657
+ placeHolder: "https://sourcegraph.example.com",
33658
+ value: "https://",
33659
+ password: false,
33660
+ ignoreFocusOut: true,
33661
+ // valide input to ensure the user is not entering a token as URL
33662
+ validateInput: (value) => {
33663
+ if (!value) {
33664
+ return null;
33665
+ }
33666
+ if (isSourcegraphToken(value)) {
33667
+ return "Please enter a valid URL";
33668
+ }
33669
+ if (value.length > 4 && !value.startsWith("http")) {
33670
+ return "URL must start with http or https";
33671
+ }
33672
+ if (!/([.]|^https?:\/\/)/.test(value)) {
33673
+ return "Please enter a valid URL";
33674
+ }
33675
+ return null;
33676
+ }
33677
+ });
33678
+ if (typeof result === "string") {
33679
+ return result.trim();
33680
+ }
33681
+ return result;
33682
+ }
33683
+ async function showAccessTokenInputBox(endpoint) {
33684
+ const result = await window$1.showInputBox({
33685
+ title: endpoint,
33686
+ prompt: 'Paste your access token. To create an access token, go to "Settings" and then "Access tokens" on the Sourcegraph instance.',
33687
+ placeHolder: "Access Token",
33688
+ password: true,
33689
+ ignoreFocusOut: true
33690
+ });
33691
+ if (typeof result === "string") {
33692
+ return result.trim();
33693
+ }
33694
+ return result;
33695
+ }
33696
+ const AuthMenuOptions = {
33697
+ signin: {
33698
+ title: "Other Sign-in Options",
33699
+ placeholder: "Choose a sign-in option"
33700
+ },
33701
+ switch: {
33702
+ title: "Switch Account",
33703
+ placeHolder: "Choose an account"
33704
+ }
33705
+ };
33706
+ const LoginMenuOptionItems = [
33707
+ {
33708
+ id: "enterprise",
33709
+ label: "Sign In to Sourcegraph Enterprise Instance",
33710
+ description: "v5.1 and above",
33711
+ totalSteps: 1,
33712
+ picked: true
33713
+ },
33714
+ {
33715
+ id: "token",
33716
+ label: "Sign In to Sourcegraph Enterprise Instance with Access Token",
33717
+ description: "v5.0 and above",
33718
+ totalSteps: 2
33719
+ },
33720
+ {
33721
+ id: "token",
33722
+ label: "Sign In with URL and Access Token",
33723
+ totalSteps: 2
33724
+ }
33725
+ ];
33726
+ async function signinMenuForInstanceUrl(instanceUrl) {
33727
+ const accessToken = await showAccessTokenInputBox(instanceUrl);
33728
+ if (!accessToken) {
33729
+ return;
33730
+ }
33731
+ const authState = await authProvider.instance.auth({
33732
+ endpoint: instanceUrl,
33733
+ token: accessToken
33734
+ });
33735
+ telemetryRecorder.recordEvent("cody.auth.signin.token", "clicked", {
33736
+ metadata: {
33737
+ success: authState.authenticated ? 1 : 0
33738
+ }
33739
+ });
33740
+ await showAuthResultMessage(instanceUrl, authState);
33741
+ }
33742
+ function redirectToEndpointLogin(uri2) {
33743
+ const endpoint = formatURL(uri2);
33744
+ if (!endpoint) {
33745
+ return;
33746
+ }
33747
+ if (env.uiKind === UIKind.Web) {
33748
+ const newTokenNoCallbackUrl = new URL("/user/settings/tokens/new", endpoint);
33749
+ void env.openExternal(Uri.parse(newTokenNoCallbackUrl.href));
33750
+ void signinMenuForInstanceUrl(endpoint);
33751
+ return;
33752
+ }
33753
+ const newTokenCallbackUrl = new URL("/user/settings/tokens/new/callback", endpoint);
33754
+ newTokenCallbackUrl.searchParams.append("requestFrom", getAuthReferralCode());
33755
+ authProvider.instance.setAuthPendingToEndpoint(endpoint);
33756
+ void env.openExternal(Uri.parse(newTokenCallbackUrl.href));
33757
+ }
33758
+ async function showAuthResultMessage(endpoint, authStatus) {
33759
+ if (authStatus == null ? void 0 : authStatus.authenticated) {
33760
+ const authority = Uri.parse(endpoint).authority;
33761
+ await window$1.showInformationMessage(`Signed in to ${authority || endpoint}`);
33762
+ } else {
33763
+ await showAuthFailureMessage(endpoint);
33764
+ }
33765
+ }
33766
+ async function showAuthFailureMessage(endpoint) {
33767
+ const authority = Uri.parse(endpoint).authority;
33768
+ await window$1.showErrorMessage(
33769
+ `Authentication failed. Please ensure Cody is enabled for ${authority} and verify your email address if required.`
33770
+ );
33771
+ }
33772
+ async function tokenCallbackHandler(uri2, customHeaders) {
33773
+ closeAuthProgressIndicator();
33774
+ const params = new URLSearchParams(uri2.query);
33775
+ const token = params.get("code");
33776
+ const endpoint = authProvider.instance.status.endpoint;
33777
+ if (!token || !endpoint) {
33778
+ return;
33779
+ }
33780
+ const authState = await authProvider.instance.auth({ endpoint, token, customHeaders });
33781
+ telemetryRecorder.recordEvent("cody.auth.fromCallback.web", "succeeded", {
33782
+ metadata: {
33783
+ success: (authState == null ? void 0 : authState.authenticated) ? 1 : 0
33784
+ }
33785
+ });
33786
+ if (authState == null ? void 0 : authState.authenticated) {
33787
+ await window$1.showInformationMessage(`Signed in to ${endpoint}`);
33788
+ } else {
33789
+ await showAuthFailureMessage(endpoint);
33790
+ }
33791
+ }
33792
+ function formatURL(uri2) {
33793
+ try {
33794
+ if (!uri2) {
33795
+ return null;
33796
+ }
33797
+ if (isSourcegraphToken(uri2)) {
33798
+ throw new Error("Access Token is not a valid URL");
33799
+ }
33800
+ if (!uri2.startsWith("http")) {
33801
+ uri2 = `https://${uri2}`;
33802
+ }
33803
+ const endpointUri = new URL(uri2);
33804
+ return endpointUri.href;
33805
+ } catch (error) {
33806
+ console.error("Invalid URL: ", error);
33807
+ return null;
33808
+ }
33809
+ }
33810
+ async function showSignOutMenu() {
33811
+ telemetryRecorder.recordEvent("cody.auth.logout", "clicked");
33812
+ const { endpoint } = authProvider.instance.status;
33813
+ if (endpoint) {
33814
+ await signOut(endpoint);
33815
+ logDebug("AuthProvider:signoutMenu", endpoint);
33816
+ }
33817
+ }
33818
+ async function signOut(endpoint) {
33819
+ await secretStorage.deleteToken(endpoint);
33820
+ await localStorage.deleteEndpoint();
33821
+ await authProvider.instance.auth({ endpoint, token: null });
33822
+ await commands$1.executeCommand("setContext", "cody.activated", false);
33823
+ }
33617
33824
  function newAuthStatus(options) {
33618
33825
  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 };
33826
+ if (!options.authenticated) {
33827
+ return { authenticated: false, endpoint: options.endpoint, showInvalidAccessTokenError: true };
33631
33828
  }
33632
- if (!authenticated) {
33633
- return { ...unauthenticatedStatus, endpoint };
33829
+ const { isOfflineMode, username, endpoint, siteVersion, userOrganizations } = options;
33830
+ if (isOfflineMode) {
33831
+ return {
33832
+ authenticated: true,
33833
+ endpoint,
33834
+ username,
33835
+ codyApiVersion: 0,
33836
+ siteVersion: "offline",
33837
+ isOfflineMode: true
33838
+ };
33634
33839
  }
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;
33840
+ const isDotCom_ = isDotCom(endpoint);
33841
+ const primaryEmail = typeof options.primaryEmail === "string" ? options.primaryEmail : (_a3 = options.primaryEmail) == null ? void 0 : _a3.email;
33842
+ const requiresVerifiedEmail = isDotCom_;
33843
+ const hasVerifiedEmail = requiresVerifiedEmail && options.authenticated && options.hasVerifiedEmail;
33639
33844
  return {
33640
33845
  ...options,
33641
- showInvalidAccessTokenError: false,
33642
33846
  endpoint,
33643
33847
  primaryEmail,
33644
33848
  requiresVerifiedEmail,
33645
33849
  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"))
33850
+ codyApiVersion: inferCodyApiVersion(siteVersion, isDotCom_),
33851
+ isFireworksTracingEnabled: isDotCom_ && !!(userOrganizations == null ? void 0 : userOrganizations.nodes.find((org) => org.name === "sourcegraph"))
33649
33852
  };
33650
33853
  }
33651
33854
  const countGeneratedCode = (text) => {
@@ -33729,7 +33932,7 @@ function getEnterpriseOutputLimit(model2) {
33729
33932
  async function syncModels(authStatus) {
33730
33933
  var _a3, _b2;
33731
33934
  modelsService.instance.setAuthStatus(authStatus);
33732
- if (authStatus.isOfflineMode) {
33935
+ if (authStatus.authenticated && authStatus.isOfflineMode) {
33733
33936
  modelsService.instance.setModels([]);
33734
33937
  return;
33735
33938
  }
@@ -33742,12 +33945,15 @@ async function syncModels(authStatus) {
33742
33945
  logDebug("ModelsService", "new models API enabled");
33743
33946
  const serverSideModels = await fetchServerSideModels(authStatus.endpoint || "");
33744
33947
  if (serverSideModels) {
33745
- modelsService.instance.setServerSentModels(serverSideModels);
33948
+ modelsService.instance.setServerSentModels({
33949
+ ...serverSideModels,
33950
+ models: maybeAdjustContextWindows(serverSideModels.models)
33951
+ });
33746
33952
  registerModelsFromVSCodeConfiguration();
33747
33953
  return;
33748
33954
  }
33749
33955
  }
33750
- if (authStatus.isDotCom) {
33956
+ if (isDotCom(authStatus)) {
33751
33957
  modelsService.instance.setModels(getDotComDefaultModels());
33752
33958
  registerModelsFromVSCodeConfiguration();
33753
33959
  return;
@@ -33799,6 +34005,13 @@ async function fetchServerSideModels(endpoint) {
33799
34005
  const client = new RestClient(endpoint, userAccessToken, customHeaders);
33800
34006
  return await client.getAvailableModels();
33801
34007
  }
34008
+ const maybeAdjustContextWindows = (models) => models.map((model2) => {
34009
+ let maxInputTokens = model2.contextWindow.maxInputTokens;
34010
+ if (/^mi(x|s)tral/.test(model2.modelName)) {
34011
+ maxInputTokens = Math.round(model2.contextWindow.maxInputTokens * 0.85);
34012
+ }
34013
+ return { ...model2, contextWindow: { ...model2.contextWindow, maxInputTokens } };
34014
+ });
33802
34015
  function logFirstEnrollmentEvent(key, isEnabled) {
33803
34016
  const isEnrolled = localStorage.getEnrollmentHistory(key);
33804
34017
  const eventName = getFeatureFlagEventName(key);
@@ -33843,159 +34056,18 @@ const maybeStartInteractiveTutorial = async () => {
33843
34056
  }
33844
34057
  return commands$1.executeCommand("cody.tutorial.start");
33845
34058
  };
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
34059
  const HAS_AUTHENTICATED_BEFORE_KEY = "has-authenticated-before";
33985
34060
  class AuthProvider {
33986
34061
  constructor(config) {
33987
- __publicField2(this, "endpointHistory", []);
33988
34062
  __publicField2(this, "client", null);
33989
- __publicField2(this, "status", defaultAuthStatus);
34063
+ __publicField2(this, "_status", null);
33990
34064
  __publicField2(this, "didChangeEvent", new AgentEventEmitter());
33991
34065
  __publicField2(this, "disposables", [this.didChangeEvent]);
33992
34066
  __publicField2(this, "changes", fromVSCodeEvent(
33993
34067
  this.didChangeEvent.event,
33994
- this.getAuthStatus.bind(this)
33995
- ));
34068
+ () => this._status ?? NO_INITIAL_VALUE
34069
+ ).pipe(distinctUntilChanged$1()));
33996
34070
  this.config = config;
33997
- this.status.endpoint = "init";
33998
- this.loadEndpointHistory();
33999
34071
  }
34000
34072
  dispose() {
34001
34073
  for (const d2 of this.disposables) {
@@ -34018,114 +34090,6 @@ class AuthProvider {
34018
34090
  isExtensionStartup: true
34019
34091
  }).catch((error) => logError$2("AuthProvider:init:failed", lastEndpoint, { verbose: error }));
34020
34092
  }
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
34093
  // Create Auth Status
34130
34094
  async makeAuthStatus(config, isOfflineMode) {
34131
34095
  var _a3;
@@ -34134,15 +34098,22 @@ class AuthProvider {
34134
34098
  const isCodyWeb = workspace.getConfiguration().get("cody.advanced.agent.ide") === CodyIDE.Web;
34135
34099
  if (isOfflineMode) {
34136
34100
  const lastUser = localStorage.getLastStoredUser();
34137
- return { ...offlineModeAuthStatus, ...lastUser };
34101
+ return {
34102
+ endpoint: (lastUser == null ? void 0 : lastUser.endpoint) ?? "https://offline.sourcegraph.com",
34103
+ username: (lastUser == null ? void 0 : lastUser.username) ?? "offline-user",
34104
+ authenticated: true,
34105
+ isOfflineMode: true,
34106
+ codyApiVersion: 0,
34107
+ siteVersion: ""
34108
+ };
34138
34109
  }
34139
34110
  if (isCodyWeb) {
34140
34111
  if (!endpoint) {
34141
- return { ...defaultAuthStatus, endpoint };
34112
+ return { authenticated: false, endpoint };
34142
34113
  }
34143
34114
  } else {
34144
34115
  if (!token || !endpoint) {
34145
- return { ...defaultAuthStatus, endpoint };
34116
+ return { authenticated: false, endpoint };
34146
34117
  }
34147
34118
  }
34148
34119
  if (this.config !== config || !this.client) {
@@ -34155,24 +34126,27 @@ class AuthProvider {
34155
34126
  this.client.getCurrentUserInfo()
34156
34127
  ]);
34157
34128
  logDebug("CodyLLMConfiguration", JSON.stringify(codyLLMConfiguration));
34158
- if (isError$1(userInfo) && isNetworkError(userInfo)) {
34159
- return { ...networkErrorAuthStatus, endpoint };
34129
+ if (isError$1(userInfo) && isNetworkLikeError(userInfo)) {
34130
+ return { authenticated: false, showNetworkError: true, endpoint };
34160
34131
  }
34161
34132
  if (!userInfo || isError$1(userInfo)) {
34162
- return { ...unauthenticatedStatus, endpoint };
34133
+ return { authenticated: false, endpoint, showInvalidAccessTokenError: true };
34134
+ }
34135
+ if (!siteHasCodyEnabled) {
34136
+ window$1.showErrorMessage(
34137
+ `Cody is not enabled on this Sourcegraph instance (${endpoint}). Ask a site administrator to enable it.`
34138
+ );
34139
+ return { authenticated: false, endpoint };
34163
34140
  }
34164
34141
  const configOverwrites = isError$1(codyLLMConfiguration) ? void 0 : codyLLMConfiguration;
34165
- const isDotCom2 = this.client.isDotCom();
34166
- if (!isDotCom2) {
34142
+ if (!isDotCom(endpoint)) {
34167
34143
  return newAuthStatus({
34168
34144
  ...userInfo,
34169
34145
  endpoint,
34170
- isDotCom: isDotCom2,
34171
34146
  siteVersion,
34172
34147
  configOverwrites,
34173
34148
  authenticated: true,
34174
34149
  hasVerifiedEmail: false,
34175
- siteHasCodyEnabled,
34176
34150
  userCanUpgrade: false
34177
34151
  });
34178
34152
  }
@@ -34181,8 +34155,6 @@ class AuthProvider {
34181
34155
  return newAuthStatus({
34182
34156
  ...userInfo,
34183
34157
  endpoint,
34184
- isDotCom: isDotCom2,
34185
- siteHasCodyEnabled,
34186
34158
  siteVersion,
34187
34159
  configOverwrites,
34188
34160
  authenticated: !!userInfo.id,
@@ -34190,8 +34162,25 @@ class AuthProvider {
34190
34162
  primaryEmail: ((_a3 = userInfo.primaryEmail) == null ? void 0 : _a3.email) ?? ""
34191
34163
  });
34192
34164
  }
34193
- getAuthStatus() {
34194
- return this.status;
34165
+ get status() {
34166
+ if (!this._status) {
34167
+ throw new Error("AuthStatus is not initialized");
34168
+ }
34169
+ return this._status;
34170
+ }
34171
+ /** Like {@link AuthProvider.status} but throws if not authed. */
34172
+ get statusAuthed() {
34173
+ if (!this._status) {
34174
+ throw new Error("AuthStatus is not initialized");
34175
+ }
34176
+ if (!this._status.authenticated) {
34177
+ throw new Error("Not authenticated");
34178
+ }
34179
+ return this._status;
34180
+ }
34181
+ /** Like {@link AuthProvider.status} but returns null instead of throwing if not ready. */
34182
+ get statusOrNotReadyYet() {
34183
+ return this._status;
34195
34184
  }
34196
34185
  // It processes the authentication steps and stores the login info before sharing the auth status with chatview
34197
34186
  async auth({
@@ -34201,8 +34190,12 @@ class AuthProvider {
34201
34190
  isExtensionStartup = false,
34202
34191
  isOfflineMode = false
34203
34192
  }) {
34193
+ const formattedEndpoint = formatURL(endpoint);
34194
+ if (!formattedEndpoint) {
34195
+ throw new Error(`invalid endpoint URL: ${JSON.stringify(endpoint)}`);
34196
+ }
34204
34197
  const config = {
34205
- serverEndpoint: formatURL(endpoint) ?? "",
34198
+ serverEndpoint: formattedEndpoint,
34206
34199
  accessToken: token,
34207
34200
  customHeaders: customHeaders || this.config.customHeaders
34208
34201
  };
@@ -34211,17 +34204,24 @@ class AuthProvider {
34211
34204
  if (!isOfflineMode) {
34212
34205
  await this.storeAuthInfo(config.serverEndpoint, config.accessToken);
34213
34206
  }
34214
- await commands$1.executeCommand("setContext", "cody.activated", authStatus.isLoggedIn);
34207
+ await commands$1.executeCommand(
34208
+ "setContext",
34209
+ "cody.activated",
34210
+ authStatus.authenticated
34211
+ );
34215
34212
  await this.setAuthStatus(authStatus);
34216
- if (isExtensionStartup && authStatus.isLoggedIn) {
34213
+ if (isExtensionStartup && authStatus.authenticated) {
34217
34214
  await this.setHasAuthenticatedBefore();
34218
- } else if (authStatus.isLoggedIn) {
34215
+ } else if (authStatus.authenticated) {
34219
34216
  this.handleFirstEverAuthentication();
34220
34217
  }
34221
34218
  return authStatus;
34222
34219
  } catch (error) {
34223
34220
  logDebug("AuthProvider:auth", "failed", error);
34224
- return await this.reloadAuthStatus().catch(() => unauthenticatedStatus);
34221
+ return await this.reloadAuthStatus().catch(() => ({
34222
+ authenticated: false,
34223
+ endpoint: config.serverEndpoint
34224
+ }));
34225
34225
  }
34226
34226
  }
34227
34227
  // Set auth status in case of reload
@@ -34236,13 +34236,10 @@ class AuthProvider {
34236
34236
  }
34237
34237
  // Set auth status and share it with chatview
34238
34238
  async setAuthStatus(authStatus) {
34239
- if (this.status === authStatus) {
34240
- return;
34241
- }
34242
- this.status = authStatus;
34243
- if (authStatus.endpoint === "init") {
34239
+ if (this._status === authStatus) {
34244
34240
  return;
34245
34241
  }
34242
+ this._status = authStatus;
34246
34243
  await this.updateAuthStatus(authStatus);
34247
34244
  }
34248
34245
  async updateAuthStatus(authStatus) {
@@ -34253,61 +34250,18 @@ class AuthProvider {
34253
34250
  } catch (error) {
34254
34251
  logDebug("AuthProvider", "updateAuthStatus error", error);
34255
34252
  } finally {
34256
- this.didChangeEvent.fire(this.getAuthStatus());
34253
+ this.didChangeEvent.fire(this.status);
34257
34254
  let eventValue;
34258
- if (authStatus.showNetworkError || authStatus.showInvalidAccessTokenError) {
34259
- eventValue = "failed";
34260
- } else if (authStatus.isLoggedIn) {
34255
+ if (authStatus.authenticated) {
34261
34256
  eventValue = "connected";
34257
+ } else if (authStatus.showNetworkError || authStatus.showInvalidAccessTokenError) {
34258
+ eventValue = "failed";
34262
34259
  } else {
34263
34260
  eventValue = "disconnected";
34264
34261
  }
34265
34262
  telemetryRecorder.recordEvent("cody.auth", eventValue);
34266
34263
  }
34267
34264
  }
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
34265
  // Store endpoint in local storage, token in secret storage, and update endpoint history.
34312
34266
  async storeAuthInfo(endpoint, token) {
34313
34267
  if (!endpoint) {
@@ -34317,13 +34271,10 @@ class AuthProvider {
34317
34271
  if (token) {
34318
34272
  await secretStorage.storeToken(endpoint, token);
34319
34273
  }
34320
- this.loadEndpointHistory();
34321
34274
  }
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();
34275
+ setAuthPendingToEndpoint(endpoint) {
34276
+ this._status = { authenticated: false, endpoint };
34277
+ this.didChangeEvent.fire(this._status);
34327
34278
  }
34328
34279
  // Logs a telemetry event if the user has never authenticated to Sourcegraph.
34329
34280
  handleFirstEverAuthentication() {
@@ -34339,42 +34290,6 @@ class AuthProvider {
34339
34290
  }
34340
34291
  }
34341
34292
  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
34293
  const { platform, arch } = getOSArch();
34379
34294
  const getExtensionDetails = (config) => ({
34380
34295
  ide: config.agentIDE ?? CodyIDE.VSCode,
@@ -35097,7 +35012,7 @@ class RepoNameResolver {
35097
35012
  throw new Error("RepoNameResolver not initialized");
35098
35013
  }
35099
35014
  const uniqueRemoteUrls = Array.from(new Set(remoteUrls));
35100
- if (authProvider.instance.getAuthStatus().isDotCom) {
35015
+ if (isDotCom(authProvider.instance.status)) {
35101
35016
  return uniqueRemoteUrls.map(convertGitCloneURLToCodebaseName).filter(isDefined);
35102
35017
  }
35103
35018
  const repoNames = await Promise.all(
@@ -42858,7 +42773,7 @@ function logError(error) {
42858
42773
  }
42859
42774
  captureException(error);
42860
42775
  const message = error.message;
42861
- const traceId = isNetworkError$1(error) ? error.traceId : void 0;
42776
+ const traceId = isNetworkError(error) ? error.traceId : void 0;
42862
42777
  if (!errorCounts.has(message)) {
42863
42778
  errorCounts.set(message, 0);
42864
42779
  logCompletionErrorEvent({ message, traceId, count: 1 });
@@ -43976,7 +43891,6 @@ class AgentWebviewPanel {
43976
43891
  __publicField2(this, "panelID", v4());
43977
43892
  __publicField2(this, "chatID");
43978
43893
  // also known as `sessionID` in some parts of the Cody codebase
43979
- __publicField2(this, "models");
43980
43894
  __publicField2(this, "remoteRepos");
43981
43895
  __publicField2(this, "isInitialized", false);
43982
43896
  __publicField2(this, "isMessageInProgress");
@@ -43988,6 +43902,7 @@ class AgentWebviewPanel {
43988
43902
  __publicField2(this, "postMessage", new AgentEventEmitter());
43989
43903
  __publicField2(this, "onDidPostMessage", this.postMessage.event);
43990
43904
  __publicField2(this, "attributionResults", /* @__PURE__ */ new Map());
43905
+ __publicField2(this, "_extensionAPI");
43991
43906
  this.panel = defaultWebviewPanel({
43992
43907
  viewType,
43993
43908
  title,
@@ -44048,6 +43963,23 @@ class AgentWebviewPanel {
44048
43963
  get onDidChangeViewState() {
44049
43964
  return this.panel.onDidChangeViewState;
44050
43965
  }
43966
+ /**
43967
+ * Call an extension host API exposed to the "webview". See {@link WebviewToExtensionAPI}.
43968
+ */
43969
+ get extensionAPI() {
43970
+ if (!this._extensionAPI) {
43971
+ this._extensionAPI = createExtensionAPI(
43972
+ createMessageAPIForWebview({
43973
+ postMessage: (message) => this.receiveMessage.fire(message),
43974
+ onMessage: (callback) => {
43975
+ const disposable = this.onDidPostMessage(callback);
43976
+ return () => disposable.dispose();
43977
+ }
43978
+ })
43979
+ );
43980
+ }
43981
+ return this._extensionAPI;
43982
+ }
44051
43983
  reveal() {
44052
43984
  this.panel.reveal();
44053
43985
  }
@@ -46702,17 +46634,60 @@ var define_process_default$7 = { env: {} };
46702
46634
  }).call(this);
46703
46635
  LocalStorage_2 = LocalStorage2;
46704
46636
  }).call(commonjsGlobal);
46637
+ async function migrateChatHistoryCODY3538(storage) {
46638
+ const hasMigrated = storage.get(MIGRATED_CHAT_HISTORY_KEY_CODY_3538);
46639
+ if (hasMigrated) {
46640
+ return;
46641
+ }
46642
+ 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;
46643
+ const history = storage.get(KEY_LOCAL_HISTORY, null);
46644
+ for (const accountHistory of Object.values(history ?? {})) {
46645
+ for (const [chatId, chat2] of Object.entries(accountHistory.chat)) {
46646
+ if (uuidRegex.test(chatId) || uuidRegex.test(chat2.lastInteractionTimestamp)) {
46647
+ let lastInteraction;
46648
+ const timestamp = Date.parse(chat2.lastInteractionTimestamp);
46649
+ if (Number.isNaN(timestamp)) {
46650
+ lastInteraction = /* @__PURE__ */ new Date();
46651
+ } else {
46652
+ lastInteraction = new Date(timestamp);
46653
+ }
46654
+ const newId = lastInteraction.toUTCString();
46655
+ chat2.id = newId;
46656
+ chat2.lastInteractionTimestamp = newId;
46657
+ delete accountHistory.chat[chatId];
46658
+ accountHistory.chat[newId] = chat2;
46659
+ }
46660
+ }
46661
+ }
46662
+ await storage.update(KEY_LOCAL_HISTORY, history);
46663
+ await storage.update(MIGRATED_CHAT_HISTORY_KEY_CODY_3538, true);
46664
+ }
46665
+ const MIGRATED_CHAT_HISTORY_KEY_CODY_3538 = "migrated-chat-history-cody-3538";
46666
+ const KEY_LOCAL_HISTORY = "cody-local-chatHistory-v2";
46667
+ async function migrate(storage) {
46668
+ await migrateChatHistoryCODY3538(storage);
46669
+ }
46705
46670
  class AgentGlobalState {
46706
- constructor(ide, dir) {
46671
+ constructor(ide, manager, dir) {
46707
46672
  __publicField2(this, "db");
46673
+ this.manager = manager;
46708
46674
  if (dir) {
46709
46675
  this.db = new LocalStorageDB(ide, dir);
46710
46676
  } else {
46711
46677
  this.db = new InMemoryDB();
46712
46678
  }
46713
- this.set("notification.setupDismissed", "true");
46714
- this.set("completion.inline.hasAcceptedFirstCompletion", true);
46715
- this.set("extension.hasActivatedPreviously", "true");
46679
+ if (manager === "client") {
46680
+ this.set("notification.setupDismissed", "true");
46681
+ this.set("completion.inline.hasAcceptedFirstCompletion", true);
46682
+ this.set("extension.hasActivatedPreviously", "true");
46683
+ }
46684
+ }
46685
+ static async initialize(ide, dir) {
46686
+ const globalState = new AgentGlobalState(ide, dir ? "server" : "client", dir);
46687
+ if (globalState.db instanceof LocalStorageDB) {
46688
+ await migrate(globalState);
46689
+ }
46690
+ return globalState;
46716
46691
  }
46717
46692
  set(key, value) {
46718
46693
  this.db.set(key, value);
@@ -46723,9 +46698,15 @@ class AgentGlobalState {
46723
46698
  }
46724
46699
  }
46725
46700
  keys() {
46701
+ if (this.manager === "server") {
46702
+ return this.db.keys();
46703
+ }
46726
46704
  return [localStorage.LAST_USED_ENDPOINT, localStorage.ANONYMOUS_USER_ID_KEY, ...this.db.keys()];
46727
46705
  }
46728
46706
  get(key, defaultValue) {
46707
+ if (this.manager === "server") {
46708
+ return this.db.get(key) ?? defaultValue;
46709
+ }
46729
46710
  switch (key) {
46730
46711
  case localStorage.LAST_USED_ENDPOINT:
46731
46712
  return extensionConfiguration == null ? void 0 : extensionConfiguration.serverEndpoint;
@@ -46799,6 +46780,10 @@ class MessageHandler {
46799
46780
  __publicField2(this, "requestHandlers", /* @__PURE__ */ new Map());
46800
46781
  __publicField2(this, "notificationHandlers", /* @__PURE__ */ new Map());
46801
46782
  __publicField2(this, "disposables", []);
46783
+ /*<M extends keyof WebviewToExtensionAPI>(
46784
+ method: M,
46785
+ ...args: Parameters<WebviewToExtensionAPI[M]>
46786
+ ): ReturnType<WebviewToExtensionAPI[M]> {}*/
46802
46787
  __publicField2(this, "alive", true);
46803
46788
  this.conn = conn2;
46804
46789
  this.disposables.push(
@@ -47061,7 +47046,7 @@ class Agent extends MessageHandler {
47061
47046
  "*",
47062
47047
  new IndentationBasedFoldingRangeProvider()
47063
47048
  );
47064
- this.globalState = this.newGlobalState(clientInfo2);
47049
+ this.globalState = await this.newGlobalState(clientInfo2);
47065
47050
  if (clientInfo2.capabilities && ((_a3 = clientInfo2.capabilities) == null ? void 0 : _a3.webview) === void 0) {
47066
47051
  clientInfo2.capabilities.webview = "agentic";
47067
47052
  }
@@ -47143,8 +47128,7 @@ class Agent extends MessageHandler {
47143
47128
  return {
47144
47129
  name: "cody-agent",
47145
47130
  authenticated: authStatus == null ? void 0 : authStatus.authenticated,
47146
- codyEnabled: authStatus == null ? void 0 : authStatus.siteHasCodyEnabled,
47147
- codyVersion: authStatus == null ? void 0 : authStatus.siteVersion,
47131
+ codyVersion: (authStatus == null ? void 0 : authStatus.authenticated) ? authStatus.siteVersion : void 0,
47148
47132
  authStatus
47149
47133
  };
47150
47134
  } catch (error) {
@@ -47801,6 +47785,9 @@ class Agent extends MessageHandler {
47801
47785
  });
47802
47786
  this.registerAuthenticatedRequest("chat/restore", async ({ modelID, messages, chatID }) => {
47803
47787
  const authStatus = await commands$1.executeCommand("cody.auth.status");
47788
+ if (!authStatus.authenticated) {
47789
+ throw new Error("Not authenticated");
47790
+ }
47804
47791
  modelID ?? (modelID = modelsService.instance.getDefaultChatModel() ?? "");
47805
47792
  const chatMessages = (messages == null ? void 0 : messages.map(PromptString.unsafe_deserializeChatMessage)) ?? [];
47806
47793
  const chatModel = new ChatModel(modelID, chatID, chatMessages);
@@ -47819,6 +47806,9 @@ class Agent extends MessageHandler {
47819
47806
  this.registerAuthenticatedRequest("chat/export", async (input) => {
47820
47807
  const { fullHistory = false } = input ?? {};
47821
47808
  const authStatus = await commands$1.executeCommand("cody.auth.status");
47809
+ if (!authStatus.authenticated) {
47810
+ throw new Error("Not authenticated");
47811
+ }
47822
47812
  const localHistory = chatHistory.getLocalHistory(authStatus);
47823
47813
  if (localHistory != null) {
47824
47814
  return Object.entries(localHistory == null ? void 0 : localHistory.chat).filter(
@@ -47844,6 +47834,9 @@ class Agent extends MessageHandler {
47844
47834
  id: params2.chatId
47845
47835
  });
47846
47836
  const authStatus = await commands$1.executeCommand("cody.auth.status");
47837
+ if (!authStatus.authenticated) {
47838
+ throw new Error("Not authenticated");
47839
+ }
47847
47840
  const localHistory = await chatHistory.getLocalHistory(authStatus);
47848
47841
  if (localHistory != null) {
47849
47842
  return Object.entries(localHistory == null ? void 0 : localHistory.chat).map(([chatID, chatTranscript]) => ({
@@ -47860,6 +47853,11 @@ class Agent extends MessageHandler {
47860
47853
  });
47861
47854
  return { remoteRepos: panel2.remoteRepos };
47862
47855
  });
47856
+ this.registerAuthenticatedRequest("chat/setModel", async ({ id, model: model2 }) => {
47857
+ const panel2 = this.webPanels.getPanelOrError(id);
47858
+ await waitUntilComplete(panel2.extensionAPI.setChatModel(model2));
47859
+ return null;
47860
+ });
47863
47861
  const submitOrEditHandler = async ({ id, message }, token) => {
47864
47862
  if (message.command !== "submit" && message.command !== "edit") {
47865
47863
  throw new Error('Invalid message, must have a command of "submit"');
@@ -47985,18 +47983,18 @@ class Agent extends MessageHandler {
47985
47983
  pendingPromise.finally(() => this.pendingPromises.delete(pendingPromise));
47986
47984
  }
47987
47985
  }
47988
- newGlobalState(clientInfo2) {
47986
+ async newGlobalState(clientInfo2) {
47989
47987
  var _a3;
47990
47988
  switch ((_a3 = clientInfo2.capabilities) == null ? void 0 : _a3.globalState) {
47991
47989
  case "server-managed":
47992
- return new AgentGlobalState(
47990
+ return AgentGlobalState.initialize(
47993
47991
  clientInfo2.name,
47994
47992
  clientInfo2.globalStateDir ?? codyPaths().data
47995
47993
  );
47996
47994
  case "client-managed":
47997
47995
  throw new Error("client-managed global state is not supported");
47998
47996
  default:
47999
- return new AgentGlobalState(clientInfo2.name);
47997
+ return AgentGlobalState.initialize(clientInfo2.name);
48000
47998
  }
48001
47999
  }
48002
48000
  createFixupControlApplicator(files) {
@@ -48029,6 +48027,10 @@ class Agent extends MessageHandler {
48029
48027
  var _a3;
48030
48028
  return ((_a3 = this.clientInfo) == null ? void 0 : _a3.name.toLowerCase()) || "uninitialized-agent";
48031
48029
  }
48030
+ get httpClientNameForLegacyReasons() {
48031
+ var _a3;
48032
+ return ((_a3 = this.clientInfo) == null ? void 0 : _a3.legacyNameForServerIdentification) ?? void 0;
48033
+ }
48032
48034
  get clientVersion() {
48033
48035
  var _a3;
48034
48036
  return ((_a3 = this.clientInfo) == null ? void 0 : _a3.version) || "0.0.0";
@@ -48175,8 +48177,6 @@ class Agent extends MessageHandler {
48175
48177
  panel2.isMessageInProgress = message.isMessageInProgress;
48176
48178
  panel2.messageInProgressChange.fire(message);
48177
48179
  }
48178
- } else if (message.type === "chatModels") {
48179
- panel2.models = message.models;
48180
48180
  } else if (message.type === "context/remote-repos") {
48181
48181
  panel2.remoteRepos = message.repos;
48182
48182
  } else if (message.type === "errors") {
@@ -49431,7 +49431,7 @@ class CommandsProvider {
49431
49431
  * Used for retreiving context for the command field in custom command
49432
49432
  */
49433
49433
  async runShell(shell2) {
49434
- const { getContextFileFromShell } = await import("./shell-CvNNoU2J.mjs");
49434
+ const { getContextFileFromShell } = await import("./shell-w-Sycwnw.mjs");
49435
49435
  return getContextFileFromShell(shell2);
49436
49436
  }
49437
49437
  /**
@@ -49442,7 +49442,7 @@ class CommandsProvider {
49442
49442
  if (!isFileURI(uri2)) {
49443
49443
  throw new Error("history only supported on local file paths");
49444
49444
  }
49445
- const { getContextFileFromGitLog } = await import("./git-log-CKjP84c8.mjs");
49445
+ const { getContextFileFromGitLog } = await import("./git-log-DUAthDkb.mjs");
49446
49446
  return getContextFileFromGitLog(uri2, options);
49447
49447
  }
49448
49448
  dispose() {
@@ -49526,6 +49526,66 @@ class ExtensionApi {
49526
49526
  this.extensionMode = extensionMode;
49527
49527
  }
49528
49528
  }
49529
+ async function showAccountMenu() {
49530
+ const authStatus = authProvider.instance.statusAuthed;
49531
+ const selected = await openAccountMenuFirstStep(authStatus);
49532
+ if (selected === void 0) {
49533
+ return;
49534
+ }
49535
+ switch (selected) {
49536
+ case "Manage Account": {
49537
+ const uri2 = Uri.parse(ACCOUNT_USAGE_URL.toString()).with({
49538
+ query: `cody_client_user=${encodeURIComponent(authStatus.username)}`
49539
+ });
49540
+ void env.openExternal(uri2);
49541
+ break;
49542
+ }
49543
+ case "Switch Account...":
49544
+ await showSignInMenu();
49545
+ break;
49546
+ case "Sign Out":
49547
+ await showSignOutMenu();
49548
+ break;
49549
+ }
49550
+ }
49551
+ async function openAccountMenuFirstStep(authStatus) {
49552
+ const isOffline = !!authStatus.isOfflineMode;
49553
+ const isDotComInstance = isDotCom(authStatus.endpoint) && !isOffline;
49554
+ const displayName2 = authStatus.displayName || authStatus.username;
49555
+ const email = authStatus.primaryEmail || "No Email";
49556
+ const username = authStatus.username || authStatus.displayName;
49557
+ const planDetail = `Plan: ${authStatus.userCanUpgrade ? "Cody Free" : "Cody Pro"}`;
49558
+ const enterpriseDetail = `Enterprise Instance:
49559
+ ${authStatus.endpoint}`;
49560
+ const offlineDetail = "Use Cody offline with Ollama";
49561
+ const options = isDotComInstance ? [
49562
+ "Manage Account"
49563
+ /* Manage */
49564
+ ] : [];
49565
+ options.push(
49566
+ "Switch Account...",
49567
+ "Sign Out"
49568
+ /* SignOut */
49569
+ );
49570
+ const messageOptions = {
49571
+ modal: true,
49572
+ detail: isOffline ? offlineDetail : isDotComInstance ? planDetail : enterpriseDetail
49573
+ };
49574
+ const online = isDotComInstance ? `Signed in as ${displayName2} (${email})` : `Signed in as @${username}`;
49575
+ const offline = "Offline Mode";
49576
+ const message = isOffline ? offline : online;
49577
+ const option = await window$1.showInformationMessage(message, messageOptions, ...options);
49578
+ switch (option !== void 0) {
49579
+ case (option == null ? void 0 : option.startsWith("Sign Out")):
49580
+ return "Sign Out";
49581
+ case (option == null ? void 0 : option.startsWith("Manage")):
49582
+ return "Manage Account";
49583
+ case (option == null ? void 0 : option.startsWith("Switch")):
49584
+ return "Switch Account...";
49585
+ default:
49586
+ return void 0;
49587
+ }
49588
+ }
49529
49589
  const executeSmartApply = async (args2) => {
49530
49590
  return commands$1.executeCommand("cody.command.smart-apply", args2);
49531
49591
  };
@@ -49602,13 +49662,16 @@ async function handleCodeFromInsertAtCursor(text) {
49602
49662
  throw new Error("No editor or selection found to insert text");
49603
49663
  }
49604
49664
  const edit2 = new AgentWorkspaceEdit();
49605
- edit2.insert(activeEditor.document.uri, selectionRange.start, `${text}
49606
- `);
49665
+ if (selectionRange.isEmpty) {
49666
+ edit2.insert(activeEditor.document.uri, selectionRange.start, text.trimEnd());
49667
+ } else {
49668
+ edit2.replace(activeEditor.document.uri, selectionRange, text.trimEnd());
49669
+ }
49607
49670
  setLastStoredCode(text, "insertButton");
49608
49671
  await workspace.applyEdit(edit2);
49609
49672
  }
49610
49673
  function getSmartApplyModel(authStatus) {
49611
- if (!authStatus.isDotCom) {
49674
+ if (!isDotCom(authStatus)) {
49612
49675
  return;
49613
49676
  }
49614
49677
  return "anthropic/claude-3-5-sonnet-20240620";
@@ -52938,21 +53001,25 @@ function getMentionMenuData(query2, chatModel) {
52938
53001
  }
52939
53002
  async function getChatContextItemsForMention(options, _2) {
52940
53003
  const MAX_RESULTS = 20;
52941
- const { mentionQuery, telemetryRecorder: telemetryRecorder2, remoteRepositoriesNames, rangeFilter = true } = options;
53004
+ const { mentionQuery, telemetryRecorder: telemetryRecorder2, rangeFilter = true } = options;
52942
53005
  switch (mentionQuery.provider) {
52943
53006
  case null:
52944
53007
  telemetryRecorder2 == null ? void 0 : telemetryRecorder2.empty();
52945
53008
  return getOpenTabsContextFile();
52946
53009
  case SYMBOL_CONTEXT_MENTION_PROVIDER.id:
52947
53010
  telemetryRecorder2 == null ? void 0 : telemetryRecorder2.withProvider(mentionQuery.provider);
52948
- return getSymbolContextFiles(mentionQuery.text, MAX_RESULTS, remoteRepositoriesNames);
53011
+ return getSymbolContextFiles(
53012
+ mentionQuery.text,
53013
+ MAX_RESULTS,
53014
+ mentionQuery.contextRemoteRepositoriesNames
53015
+ );
52949
53016
  case FILE_CONTEXT_MENTION_PROVIDER.id: {
52950
53017
  telemetryRecorder2 == null ? void 0 : telemetryRecorder2.withProvider(mentionQuery.provider);
52951
53018
  const files = mentionQuery.text ? await getFileContextFiles({
52952
53019
  query: mentionQuery.text,
52953
53020
  range: mentionQuery.range,
52954
53021
  maxResults: MAX_RESULTS,
52955
- repositoriesNames: remoteRepositoriesNames
53022
+ repositoriesNames: mentionQuery.contextRemoteRepositoriesNames
52956
53023
  }) : await getOpenTabsContextFile();
52957
53024
  if (mentionQuery.range && files.length > 0 && rangeFilter) {
52958
53025
  const item = await getContextFileFromUri(
@@ -52969,7 +53036,7 @@ async function getChatContextItemsForMention(options, _2) {
52969
53036
  return [];
52970
53037
  }
52971
53038
  const items = await openCtx.controller.mentions(
52972
- { query: mentionQuery.text },
53039
+ { query: mentionQuery.text, ...await getActiveEditorContextForOpenCtxMentions() },
52973
53040
  // get mention items for the selected provider only.
52974
53041
  { providerUri: mentionQuery.provider }
52975
53042
  );
@@ -52979,6 +53046,13 @@ async function getChatContextItemsForMention(options, _2) {
52979
53046
  }
52980
53047
  }
52981
53048
  }
53049
+ async function getActiveEditorContextForOpenCtxMentions() {
53050
+ var _a3, _b2, _c2;
53051
+ const uri2 = (_b2 = (_a3 = window$1.activeTextEditor) == null ? void 0 : _a3.document.uri) == null ? void 0 : _b2.toString();
53052
+ const activeWorkspaceURI = uri2 && (workspaceReposMonitor == null ? void 0 : workspaceReposMonitor.getFolderURIs().find((folderURI) => uri2 == null ? void 0 : uri2.startsWith(folderURI.toString())));
53053
+ const codebase = activeWorkspaceURI && ((_c2 = (await fetchRepoMetadataForFolder(activeWorkspaceURI))[0]) == null ? void 0 : _c2.repoName);
53054
+ return { uri: uri2, codebase };
53055
+ }
52982
53056
  function contextItemMentionFromOpenCtxItem(item) {
52983
53057
  var _a3;
52984
53058
  const isIgnored = (_a3 = item.data) == null ? void 0 : _a3.isIgnored;
@@ -53059,7 +53133,7 @@ function startClientStateBroadcaster({
53059
53133
  return Disposable.from(...disposables);
53060
53134
  }
53061
53135
  async function getCorpusContextItemsForEditorState(useRemote) {
53062
- var _a3;
53136
+ var _a3, _b2, _c2;
53063
53137
  const items = [];
53064
53138
  if (useRemote && workspaceReposMonitor) {
53065
53139
  const repoMetadata = await workspaceReposMonitor.getRepoMetadata();
@@ -53103,7 +53177,27 @@ async function getCorpusContextItemsForEditorState(useRemote) {
53103
53177
  });
53104
53178
  }
53105
53179
  }
53106
- return items;
53180
+ const providers = (_c2 = await ((_b2 = openCtx.controller) == null ? void 0 : _b2.meta({}))) == null ? void 0 : _c2.filter((meta) => {
53181
+ var _a4;
53182
+ return (_a4 = meta.mentions) == null ? void 0 : _a4.autoInclude;
53183
+ });
53184
+ if (!providers) {
53185
+ return items;
53186
+ }
53187
+ const activeEditorContext = await getActiveEditorContextForOpenCtxMentions();
53188
+ const openctxMentions = (await Promise.all(
53189
+ providers.map(async (provider) => {
53190
+ var _a4, _b3;
53191
+ const mentions = await ((_b3 = (_a4 = openCtx) == null ? void 0 : _a4.controller) == null ? void 0 : _b3.mentions(activeEditorContext, provider)) || [];
53192
+ return mentions.map((mention) => ({
53193
+ ...mention,
53194
+ provider: "openctx",
53195
+ type: "openctx",
53196
+ uri: URI.parse(mention.uri)
53197
+ }));
53198
+ })
53199
+ )).flat();
53200
+ return [...items, ...openctxMentions];
53107
53201
  }
53108
53202
  function idempotentPostMessage(rawPostMessage) {
53109
53203
  let lastMessage;
@@ -54055,7 +54149,7 @@ class AuthDependentRetrievers {
54055
54149
  return workspace.getConfiguration().get("cody.advanced.agent.ide") === CodyIDE.Web;
54056
54150
  }
54057
54151
  isConsumer() {
54058
- return authProvider.instance.getAuthStatus().isDotCom;
54152
+ return isDotCom(authProvider.instance.status);
54059
54153
  }
54060
54154
  allowRemoteContext() {
54061
54155
  return this.isCodyWeb() || !this.isConsumer();
@@ -54080,7 +54174,8 @@ class ChatController {
54080
54174
  startTokenReceiver,
54081
54175
  contextAPIClient,
54082
54176
  contextRetriever,
54083
- extensionClient
54177
+ extensionClient,
54178
+ configWatcher
54084
54179
  }) {
54085
54180
  __publicField2(this, "chatModel");
54086
54181
  __publicField2(this, "chatClient");
@@ -54091,6 +54186,7 @@ class ChatController {
54091
54186
  __publicField2(this, "guardrails");
54092
54187
  __publicField2(this, "startTokenReceiver");
54093
54188
  __publicField2(this, "contextAPIClient");
54189
+ __publicField2(this, "configWatcher");
54094
54190
  __publicField2(this, "disposables", []);
54095
54191
  __publicField2(this, "initDoer", new InitDoer());
54096
54192
  __publicField2(this, "submitOrEditOperation");
@@ -54107,6 +54203,7 @@ class ChatController {
54107
54203
  this.editor = editor;
54108
54204
  this.extensionClient = extensionClient;
54109
54205
  this.contextRetriever = contextRetriever;
54206
+ this.configWatcher = configWatcher;
54110
54207
  this.chatModel = new ChatModel(getDefaultModelID());
54111
54208
  this.guardrails = guardrails;
54112
54209
  this.startTokenReceiver = startTokenReceiver;
@@ -54178,13 +54275,6 @@ class ChatController {
54178
54275
  case "abort":
54179
54276
  this.handleAbort();
54180
54277
  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
54278
  case "getUserContext": {
54189
54279
  const result = await getChatContextItemsForMention({
54190
54280
  mentionQuery: parseMentionQuery(message.query, null)
@@ -54205,7 +54295,7 @@ class ChatController {
54205
54295
  await handleSmartApply(
54206
54296
  message.id,
54207
54297
  message.code,
54208
- authProvider.instance.getAuthStatus(),
54298
+ authProvider.instance.status,
54209
54299
  message.instruction,
54210
54300
  message.fileName
54211
54301
  );
@@ -54290,7 +54380,7 @@ class ChatController {
54290
54380
  break;
54291
54381
  case "auth": {
54292
54382
  if (message.authKind === "callback" && message.endpoint) {
54293
- authProvider.instance.redirectToEndpointLogin(message.endpoint);
54383
+ redirectToEndpointLogin(message.endpoint);
54294
54384
  break;
54295
54385
  }
54296
54386
  if (message.authKind === "offline") {
@@ -54313,11 +54403,11 @@ class ChatController {
54313
54403
  "succeeded",
54314
54404
  {
54315
54405
  metadata: {
54316
- success: (authStatus == null ? void 0 : authStatus.isLoggedIn) ? 1 : 0
54406
+ success: (authStatus == null ? void 0 : authStatus.authenticated) ? 1 : 0
54317
54407
  }
54318
54408
  }
54319
54409
  );
54320
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
54410
+ if (!(authStatus == null ? void 0 : authStatus.authenticated)) {
54321
54411
  void window$1.showErrorMessage(
54322
54412
  "Authentication failed. Please check your token and try again."
54323
54413
  );
@@ -54343,7 +54433,7 @@ class ChatController {
54343
54433
  break;
54344
54434
  }
54345
54435
  if (message.authKind === "signout") {
54346
- await authProvider.instance.signoutMenu();
54436
+ await showSignOutMenu();
54347
54437
  this.setWebviewView(View.Login);
54348
54438
  break;
54349
54439
  }
@@ -54360,7 +54450,7 @@ class ChatController {
54360
54450
  endpoint: DOTCOM_URL.href,
54361
54451
  token
54362
54452
  });
54363
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
54453
+ if (!(authStatus == null ? void 0 : authStatus.authenticated)) {
54364
54454
  void window$1.showErrorMessage(
54365
54455
  "Authentication failed. Please check your token and try again."
54366
54456
  );
@@ -54372,10 +54462,10 @@ class ChatController {
54372
54462
  }
54373
54463
  case "troubleshoot/reloadAuth": {
54374
54464
  await authProvider.instance.reloadAuthStatus();
54375
- const nextAuth = authProvider.instance.getAuthStatus();
54465
+ const nextAuth = authProvider.instance.status;
54376
54466
  telemetryRecorder.recordEvent("cody.troubleshoot", "reloadAuth", {
54377
54467
  metadata: {
54378
- success: nextAuth.isLoggedIn ? 1 : 0
54468
+ success: nextAuth.authenticated ? 1 : 0
54379
54469
  }
54380
54470
  });
54381
54471
  break;
@@ -54409,8 +54499,8 @@ class ChatController {
54409
54499
  // =======================================================================
54410
54500
  setAuthStatus(status) {
54411
54501
  void this.sendConfig();
54412
- if (status.isLoggedIn) {
54413
- this.handleSetChatModel(getDefaultModelID());
54502
+ if (status.authenticated) {
54503
+ this.chatModel.updateModel(getDefaultModelID());
54414
54504
  }
54415
54505
  }
54416
54506
  // When the webview sends the 'ready' message, respond by posting the view config
@@ -54419,7 +54509,7 @@ class ChatController {
54419
54509
  }
54420
54510
  async sendConfig() {
54421
54511
  var _a3;
54422
- const authStatus = authProvider.instance.getAuthStatus();
54512
+ const authStatus = authProvider.instance.status;
54423
54513
  const configForWebview = await this.getConfigForWebview();
54424
54514
  const workspaceFolderUris = ((_a3 = workspace.workspaceFolders) == null ? void 0 : _a3.map((folder2) => folder2.uri.toString())) ?? [];
54425
54515
  const clientConfig = await ClientConfigSingleton.getInstance().getConfig();
@@ -54436,7 +54526,8 @@ class ChatController {
54436
54526
  chat: (clientConfig == null ? void 0 : clientConfig.chatEnabled) ?? true,
54437
54527
  attribution: (clientConfig == null ? void 0 : clientConfig.attributionEnabled) ?? false,
54438
54528
  serverSentModels: (clientConfig == null ? void 0 : clientConfig.modelsAPIEnabled) ?? false
54439
- }
54529
+ },
54530
+ isDotComUser: isDotCom(authStatus)
54440
54531
  });
54441
54532
  logDebug("ChatController", "updateViewConfig", {
54442
54533
  verbose: configForWebview
@@ -54450,7 +54541,7 @@ class ChatController {
54450
54541
  isMessageInProgress: false,
54451
54542
  chatID: this.chatModel.sessionID
54452
54543
  }));
54453
- this.handleSetChatModel(this.chatModel.modelID);
54544
+ this.chatModel.updateModel(this.chatModel.modelID);
54454
54545
  await this.saveSession();
54455
54546
  this.initDoer.signalInitialized();
54456
54547
  await this.sendConfig();
@@ -54461,7 +54552,7 @@ class ChatController {
54461
54552
  async handleUserMessageSubmission(requestID, inputText, submitType, mentions, editorState, legacyAddEnhancedContext, signal2, source, command) {
54462
54553
  return tracer.startActiveSpan("chat.submit", async (span2) => {
54463
54554
  span2.setAttribute("sampled", true);
54464
- const authStatus = authProvider.instance.getAuthStatus();
54555
+ const authStatus = authProvider.instance.statusAuthed;
54465
54556
  const sharedProperties = {
54466
54557
  requestID,
54467
54558
  chatModel: this.chatModel.modelID,
@@ -54526,6 +54617,7 @@ class ChatController {
54526
54617
  prompter2,
54527
54618
  signal2,
54528
54619
  requestID,
54620
+ authStatus.codyApiVersion,
54529
54621
  contextAlternatives
54530
54622
  );
54531
54623
  void this.sendChatExecutedTelemetry(
@@ -54554,7 +54646,7 @@ class ChatController {
54554
54646
  });
54555
54647
  }
54556
54648
  async sendChatExecutedTelemetry(span2, firstTokenSpan, inputText, sharedProperties, context2) {
54557
- const authStatus = authProvider.instance.getAuthStatus();
54649
+ const authStatus = authProvider.instance.status;
54558
54650
  const contextSummary = {};
54559
54651
  for (const { source } of context2.used) {
54560
54652
  if (!source) {
@@ -54578,7 +54670,7 @@ class ChatController {
54578
54670
  ...contextSummary,
54579
54671
  // Flag indicating this is a transcript event to go through ML data pipeline. Only for DotCom users
54580
54672
  // See https://github.com/sourcegraph/sourcegraph/pull/59524
54581
- recordsPrivateMetadataTranscript: authStatus.isDotCom ? 1 : 0
54673
+ recordsPrivateMetadataTranscript: isDotCom(authStatus) ? 1 : 0
54582
54674
  },
54583
54675
  privateMetadata: {
54584
54676
  properties: properties2,
@@ -54586,7 +54678,7 @@ class ChatController {
54586
54678
  // 🚨 SECURITY: chat transcripts are to be included only for DotCom users AND for V2 telemetry
54587
54679
  // V2 telemetry exports privateMetadata only for DotCom users
54588
54680
  // the condition below is an additional safeguard measure
54589
- promptText: authStatus.isDotCom && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET)
54681
+ promptText: isDotCom(authStatus) && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET)
54590
54682
  }
54591
54683
  });
54592
54684
  }
@@ -54710,10 +54802,6 @@ class ChatController {
54710
54802
  this.postViewTranscript();
54711
54803
  telemetryRecorder.recordEvent("cody.sidebar.abortButton", "clicked");
54712
54804
  }
54713
- handleSetChatModel(modelID) {
54714
- this.chatModel.updateModel(modelID);
54715
- this.postChatModels();
54716
- }
54717
54805
  async handleGetUserEditorContext(uri2) {
54718
54806
  var _a3;
54719
54807
  const selection = (_a3 = window$1.activeTextEditor) == null ? void 0 : _a3.selection;
@@ -54813,17 +54901,6 @@ class ChatController {
54813
54901
  void this.postMessage({ type: "errors", errors: error.message });
54814
54902
  captureException(error);
54815
54903
  }
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
54904
  /**
54828
54905
  * Low-level utility to post a message to the webview, pending initialization.
54829
54906
  *
@@ -54843,20 +54920,16 @@ class ChatController {
54843
54920
  /**
54844
54921
  * Constructs the prompt and updates the UI with the context used in the prompt.
54845
54922
  */
54846
- async buildPrompt(prompter2, abortSignal, requestID, contextAlternatives) {
54923
+ async buildPrompt(prompter2, abortSignal, requestID, codyApiVersion, contextAlternatives) {
54847
54924
  var _a3;
54848
- const { prompt, context: context2 } = await prompter2.makePrompt(
54849
- this.chatModel,
54850
- authProvider.instance.getAuthStatus().codyApiVersion
54851
- );
54925
+ const { prompt, context: context2 } = await prompter2.makePrompt(this.chatModel, codyApiVersion);
54852
54926
  abortSignal.throwIfAborted();
54853
54927
  this.chatModel.setLastMessageContext([...context2.used, ...context2.ignored], contextAlternatives);
54854
54928
  (_a3 = this.contextAPIClient) == null ? void 0 : _a3.recordContext(requestID, context2.used, context2.ignored);
54855
54929
  return { prompt, context: context2 };
54856
54930
  }
54857
54931
  async buildPrivateContextSummary(context2) {
54858
- const isDotCom2 = authProvider.instance.getAuthStatus().isDotCom;
54859
- if (!isDotCom2) {
54932
+ if (!isDotCom(authProvider.instance.status)) {
54860
54933
  return {};
54861
54934
  }
54862
54935
  if (!workspaceReposMonitor) {
@@ -54991,7 +55064,7 @@ class ChatController {
54991
55064
  this.chatModel.addBotMessage({ text: messageText });
54992
55065
  void this.saveSession();
54993
55066
  this.postViewTranscript();
54994
- const authStatus = authProvider.instance.getAuthStatus();
55067
+ const authStatus = authProvider.instance.status;
54995
55068
  const generatedCode = countGeneratedCode(messageText.toString());
54996
55069
  const responseEventAction = generatedCode.charCount > 0 ? "hasCode" : "noCode";
54997
55070
  telemetryRecorder.recordEvent("cody.chatResponse", responseEventAction, {
@@ -55002,13 +55075,13 @@ class ChatController {
55002
55075
  ...generatedCode,
55003
55076
  // Flag indicating this is a transcript event to go through ML data pipeline. Only for dotcom users
55004
55077
  // See https://github.com/sourcegraph/sourcegraph/pull/59524
55005
- recordsPrivateMetadataTranscript: authStatus.isDotCom ? 1 : 0
55078
+ recordsPrivateMetadataTranscript: isDotCom(authStatus) ? 1 : 0
55006
55079
  },
55007
55080
  privateMetadata: {
55008
55081
  // 🚨 SECURITY: chat transcripts are to be included only for DotCom users AND for V2 telemetry
55009
55082
  // V2 telemetry exports privateMetadata only for DotCom users
55010
55083
  // the condition below is an aditional safegaurd measure
55011
- responseText: authStatus.isDotCom && truncatePromptString(messageText, CHAT_OUTPUT_TOKEN_BUDGET),
55084
+ responseText: isDotCom(authStatus) && truncatePromptString(messageText, CHAT_OUTPUT_TOKEN_BUDGET),
55012
55085
  chatModel: this.chatModel.modelID
55013
55086
  }
55014
55087
  });
@@ -55027,7 +55100,7 @@ class ChatController {
55027
55100
  // current in-progress completion. If the chat does not exist, then this
55028
55101
  // is a no-op.
55029
55102
  async restoreSession(sessionID) {
55030
- const oldTranscript = chatHistory.getChat(authProvider.instance.getAuthStatus(), sessionID);
55103
+ const oldTranscript = chatHistory.getChat(authProvider.instance.statusAuthed, sessionID);
55031
55104
  if (!oldTranscript) {
55032
55105
  return;
55033
55106
  }
@@ -55037,15 +55110,18 @@ class ChatController {
55037
55110
  this.postViewTranscript();
55038
55111
  }
55039
55112
  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
- });
55113
+ const authStatus = authProvider.instance.status;
55114
+ if (authStatus.authenticated) {
55115
+ const allHistory = await chatHistory.saveChat(
55116
+ authStatus,
55117
+ this.chatModel.toSerializedChatTranscript()
55118
+ );
55119
+ if (allHistory) {
55120
+ void this.postMessage({
55121
+ type: "history",
55122
+ localHistory: allHistory
55123
+ });
55124
+ }
55049
55125
  }
55050
55126
  }
55051
55127
  async clearAndRestartSession() {
@@ -55066,7 +55142,7 @@ class ChatController {
55066
55142
  return this.webviewPanelOrView;
55067
55143
  }
55068
55144
  const viewType = CodyChatEditorViewType;
55069
- const panelTitle = ((_a3 = chatHistory.getChat(authProvider.instance.getAuthStatus(), this.chatModel.sessionID)) == null ? void 0 : _a3.chatTitle) || getChatPanelTitle(lastQuestion);
55145
+ const panelTitle = ((_a3 = chatHistory.getChat(authProvider.instance.statusAuthed, this.chatModel.sessionID)) == null ? void 0 : _a3.chatTitle) || getChatPanelTitle(lastQuestion);
55070
55146
  const viewColumn = activePanelViewColumn || ViewColumn.Beside;
55071
55147
  const webviewPath = Uri.joinPath(this.extensionUri, "dist", "webviews");
55072
55148
  const panel2 = window$1.createWebviewPanel(
@@ -55140,7 +55216,19 @@ class ChatController {
55140
55216
  evaluatedFeatureFlag: (flag2) => featureFlagProvider.instance.evaluatedFeatureFlag(flag2),
55141
55217
  prompts: (query2) => promiseFactoryToObservable(
55142
55218
  (signal2) => mergedPromptsAndLegacyCommands(query2, signal2)
55143
- )
55219
+ ),
55220
+ models: () => combineLatest$1([
55221
+ this.configWatcher.changes,
55222
+ modelsService.instance.selectedOrDefaultModelChanges.pipe(
55223
+ startWith$1(void 0)
55224
+ )
55225
+ ]).pipe(map$1(() => modelsService.instance.getModels(ModelUsage.Chat))),
55226
+ setChatModel: (model2) => {
55227
+ this.chatModel.updateModel(model2);
55228
+ return promiseToObservable$1(
55229
+ modelsService.instance.setSelectedModel(ModelUsage.Chat, model2)
55230
+ );
55231
+ }
55144
55232
  }
55145
55233
  )
55146
55234
  );
@@ -55180,7 +55268,7 @@ class ChatController {
55180
55268
  let gitMetadata = "";
55181
55269
  if (workspaceReposMonitor) {
55182
55270
  const { isPublic: isWorkspacePublic, repoMetadata } = await workspaceReposMonitor.getRepoMetadataIfPublic();
55183
- if (authStatus.isDotCom && legacyAddEnhancedContext && isWorkspacePublic) {
55271
+ if (isDotCom(authStatus) && legacyAddEnhancedContext && isWorkspacePublic) {
55184
55272
  gitMetadata = JSON.stringify(repoMetadata);
55185
55273
  }
55186
55274
  }
@@ -55188,7 +55276,7 @@ class ChatController {
55188
55276
  metadata: {
55189
55277
  // Flag indicating this is a transcript event to go through ML data pipeline. Only for DotCom users
55190
55278
  // See https://github.com/sourcegraph/sourcegraph/pull/59524
55191
- recordsPrivateMetadataTranscript: authStatus.endpoint && authStatus.isDotCom ? 1 : 0,
55279
+ recordsPrivateMetadataTranscript: authStatus.endpoint && isDotCom(authStatus) ? 1 : 0,
55192
55280
  addEnhancedContext: legacyAddEnhancedContext ? 1 : 0,
55193
55281
  // All mentions
55194
55282
  mentionsTotal: mentions.length,
@@ -55226,7 +55314,7 @@ class ChatController {
55226
55314
  // 🚨 SECURITY: chat transcripts are to be included only for DotCom users AND for V2 telemetry
55227
55315
  // V2 telemetry exports privateMetadata only for DotCom users
55228
55316
  // the condition below is an additional safeguard measure
55229
- promptText: authStatus.isDotCom && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET),
55317
+ promptText: isDotCom(authStatus) && truncatePromptString(inputText, CHAT_INPUT_TOKEN_BUDGET),
55230
55318
  gitMetadata
55231
55319
  }
55232
55320
  });
@@ -55303,7 +55391,7 @@ function combineContext(explicitMentions, openCtxContext, priorityContext, retri
55303
55391
  }
55304
55392
  const CodyChatEditorViewType = "cody.editorPanel";
55305
55393
  class ChatsController {
55306
- constructor(options, chatClient, enterpriseContext, localEmbeddings, symf, contextRetriever, guardrails, contextAPIClient, extensionClient) {
55394
+ constructor(options, chatClient, enterpriseContext, localEmbeddings, symf, contextRetriever, guardrails, contextAPIClient, extensionClient, configWatcher) {
55307
55395
  // Chat view in the panel (typically in the sidebar)
55308
55396
  __publicField2(this, "panel");
55309
55397
  // Chat views in editor panels
@@ -55321,6 +55409,7 @@ class ChatsController {
55321
55409
  this.guardrails = guardrails;
55322
55410
  this.contextAPIClient = contextAPIClient;
55323
55411
  this.extensionClient = extensionClient;
55412
+ this.configWatcher = configWatcher;
55324
55413
  logDebug("ChatsController:constructor", "init");
55325
55414
  this.panel = this.createChatController();
55326
55415
  this.disposables.push(
@@ -55330,17 +55419,12 @@ class ChatsController {
55330
55419
  );
55331
55420
  }
55332
55421
  async setAuthStatus(authStatus) {
55333
- const hasLoggedOut = !authStatus.isLoggedIn;
55422
+ const hasLoggedOut = !authStatus.authenticated;
55334
55423
  const hasSwitchedAccount = this.currentAuthAccount && this.currentAuthAccount.endpoint !== authStatus.endpoint;
55335
55424
  if (hasLoggedOut || hasSwitchedAccount) {
55336
55425
  this.disposeAllChats();
55337
55426
  }
55338
- const endpoint = authStatus.endpoint ?? "";
55339
- this.currentAuthAccount = {
55340
- endpoint,
55341
- primaryEmail: authStatus.primaryEmail,
55342
- username: authStatus.username
55343
- };
55427
+ this.currentAuthAccount = authStatus.authenticated ? { ...authStatus } : void 0;
55344
55428
  this.panel.setAuthStatus(authStatus);
55345
55429
  }
55346
55430
  async restoreToPanel(panel2, chatID) {
@@ -55560,8 +55644,8 @@ class ChatsController {
55560
55644
  */
55561
55645
  async exportHistory() {
55562
55646
  telemetryRecorder.recordEvent("cody.exportChatHistoryButton", "clicked");
55563
- const authStatus = authProvider.instance.getAuthStatus();
55564
- if (authStatus.isLoggedIn) {
55647
+ const authStatus = authProvider.instance.status;
55648
+ if (authStatus.authenticated) {
55565
55649
  try {
55566
55650
  const historyJson = chatHistory.getLocalHistory(authStatus);
55567
55651
  const exportPath = await window$1.showSaveDialog({
@@ -55585,7 +55669,7 @@ class ChatsController {
55585
55669
  async clearHistory(chatID) {
55586
55670
  const ClearWithoutConfirmID = "clear-all-no-confirm";
55587
55671
  const isClearAll = !chatID || chatID === ClearWithoutConfirmID;
55588
- const authStatus = authProvider.instance.getAuthStatus();
55672
+ const authStatus = authProvider.instance.statusAuthed;
55589
55673
  if (isClearAll) {
55590
55674
  if (chatID !== ClearWithoutConfirmID) {
55591
55675
  const userConfirmation = await window$1.showWarningMessage(
@@ -55673,7 +55757,8 @@ class ChatsController {
55673
55757
  startTokenReceiver: this.options.startTokenReceiver,
55674
55758
  contextAPIClient: this.contextAPIClient,
55675
55759
  contextRetriever: this.contextRetriever,
55676
- extensionClient: this.extensionClient
55760
+ extensionClient: this.extensionClient,
55761
+ configWatcher: this.configWatcher
55677
55762
  });
55678
55763
  }
55679
55764
  disposeChat(chatID, includePanel) {
@@ -56133,7 +56218,7 @@ class GhostHintDecorator {
56133
56218
  trailing: true
56134
56219
  }
56135
56220
  );
56136
- const initialAuth = authProvider.instance.getAuthStatus();
56221
+ const initialAuth = authProvider.instance.status;
56137
56222
  this.updateEnablement(initialAuth);
56138
56223
  this.permanentDisposables.push(
56139
56224
  subscriptionDisposable(
@@ -56143,7 +56228,7 @@ class GhostHintDecorator {
56143
56228
  this.permanentDisposables.push(
56144
56229
  workspace.onDidChangeConfiguration((e) => {
56145
56230
  if (e.affectsConfiguration("cody")) {
56146
- this.updateEnablement(authProvider.instance.getAuthStatus());
56231
+ this.updateEnablement(authProvider.instance.status);
56147
56232
  }
56148
56233
  }),
56149
56234
  workspace.onDidChangeTextDocument((event) => {
@@ -56276,7 +56361,7 @@ class GhostHintDecorator {
56276
56361
  }
56277
56362
  async updateEnablement(authStatus) {
56278
56363
  const featureEnablement = await getGhostHintEnablement();
56279
- if (!authStatus.isLoggedIn || !(featureEnablement.Document || featureEnablement.EditOrChat || featureEnablement.Generate)) {
56364
+ if (!authStatus.authenticated || !(featureEnablement.Document || featureEnablement.EditOrChat || featureEnablement.Generate)) {
56280
56365
  this.disposeActive();
56281
56366
  return;
56282
56367
  }
@@ -160290,7 +160375,7 @@ function createFastPathClient(requestParams, abortController, params) {
160290
160375
  logResponseHeadersToSpan(span2, response);
160291
160376
  const traceId = (_f2 = getActiveTraceAndSpanId()) == null ? void 0 : _f2.traceId;
160292
160377
  if (response.status === 429) {
160293
- const upgradeIsAvailable = authStatus.userCanUpgrade;
160378
+ const upgradeIsAvailable = !!authStatus.userCanUpgrade;
160294
160379
  throw recordErrorToSpan(
160295
160380
  span2,
160296
160381
  await createRateLimitErrorFromResponse(response, upgradeIsAvailable)
@@ -160491,7 +160576,7 @@ class FireworksProvider extends Provider {
160491
160576
  );
160492
160577
  const isNode = typeof define_process_default !== "undefined";
160493
160578
  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
160579
+ (isDotCom(this.authStatus) || this.isLocalInstance) && define_process_default.env.CODY_DISABLE_FASTPATH !== "true" && // Used for testing
160495
160580
  // The fast path client only supports Node.js style response streams
160496
160581
  isNode ? dotcomTokenToGatewayToken(config.accessToken) : void 0;
160497
160582
  }
@@ -160574,7 +160659,7 @@ function createProviderConfig$3({
160574
160659
  model: model2,
160575
160660
  ...otherOptions
160576
160661
  }) {
160577
- const clientModel = getClientModel(model2, otherOptions.authStatus.isDotCom);
160662
+ const clientModel = getClientModel(model2, isDotCom(otherOptions.authStatus));
160578
160663
  const maxContextTokens = getMaxContextTokens(clientModel);
160579
160664
  return {
160580
160665
  create(options) {
@@ -161002,7 +161087,7 @@ async function createProviderConfigHelper(params) {
161002
161087
  case "anthropic": {
161003
161088
  let getAnthropicModel = function() {
161004
161089
  var _a4;
161005
- if (authStatus.isDotCom) {
161090
+ if (isDotCom(authStatus)) {
161006
161091
  return DEFAULT_PLG_ANTHROPIC_MODEL;
161007
161092
  }
161008
161093
  if (((_a4 = authStatus.configOverwrites) == null ? void 0 : _a4.provider) === "sourcegraph") {
@@ -161091,8 +161176,8 @@ async function createInlineCompletionItemFromMultipleProviders({
161091
161176
  statusBar,
161092
161177
  createBfgRetriever
161093
161178
  }) {
161094
- const authStatus = authProvider.instance.getAuthStatus();
161095
- if (!authStatus.isLoggedIn || config.autocompleteExperimentalMultiModelCompletions === void 0) {
161179
+ const authStatus = authProvider.instance.status;
161180
+ if (!authStatus.authenticated || config.autocompleteExperimentalMultiModelCompletions === void 0) {
161096
161181
  return {
161097
161182
  dispose: () => {
161098
161183
  }
@@ -161116,10 +161201,15 @@ async function createInlineCompletionItemFromMultipleProviders({
161116
161201
  };
161117
161202
  }
161118
161203
  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;
161204
+ const newConfig = {
161205
+ ...lodashExports.cloneDeep(config),
161206
+ // Override some config to ensure we are not logging extra events.
161207
+ telemetryLevel: "off",
161208
+ // We should only override the fireworks "cody.autocomplete.experimental.fireworksOptions" when added in the config.
161209
+ autocompleteExperimentalFireworksOptions: currentProviderConfig.enableExperimentalFireworksOverrides ? config.autocompleteExperimentalFireworksOptions : void 0,
161210
+ // Don't use the advanced provider config to get the model
161211
+ autocompleteAdvancedModel: null
161212
+ };
161123
161213
  const providerConfig = await createProviderConfigHelper({
161124
161214
  client,
161125
161215
  authStatus,
@@ -161128,7 +161218,7 @@ async function createInlineCompletionItemFromMultipleProviders({
161128
161218
  config: newConfig
161129
161219
  });
161130
161220
  if (providerConfig) {
161131
- const authStatus2 = authProvider.instance.getAuthStatus();
161221
+ const authStatus2 = authProvider.instance.statusAuthed;
161132
161222
  const completionsProvider = new InlineCompletionItemProvider({
161133
161223
  authStatus: authStatus2,
161134
161224
  providerConfig,
@@ -163865,7 +163955,8 @@ async function linearApiRequest(query2, variables, settings) {
163865
163955
  method: "POST",
163866
163956
  headers: {
163867
163957
  "Content-Type": "application/json",
163868
- Authorization: `Bearer ${accessToken}`
163958
+ // API keys don't need Bearer prefix (unlike oauth)
163959
+ Authorization: accessToken.startsWith("lin_api_") ? accessToken : `Bearer ${accessToken}`
163869
163960
  },
163870
163961
  body: JSON.stringify({ query: query2, variables })
163871
163962
  });
@@ -164196,7 +164287,7 @@ function getOpenCtxProviders(configChanges, authStatusChanges, isValidSiteVersio
164196
164287
  providerUri: WEB_PROVIDER_URI
164197
164288
  }
164198
164289
  ];
164199
- if (!authStatus.isDotCom) {
164290
+ if (!isDotCom(authStatus)) {
164200
164291
  providers.push({
164201
164292
  settings: true,
164202
164293
  provider: RemoteRepositorySearch,
@@ -164632,7 +164723,7 @@ const getInput = async (document2, initialValues, source) => {
164632
164723
  const initialCursorPosition = editor.selection.active;
164633
164724
  let activeRange = initialValues.initialExpandedRange || initialValues.initialRange;
164634
164725
  let activeRangeItem = initialValues.initialIntent === "add" ? CURSOR_RANGE_ITEM : initialValues.initialExpandedRange ? EXPANDED_RANGE_ITEM : SELECTION_RANGE_ITEM;
164635
- const authStatus = authProvider.instance.getAuthStatus();
164726
+ const authStatus = authProvider.instance.statusAuthed;
164636
164727
  const isCodyPro = !authStatus.userCanUpgrade;
164637
164728
  const modelOptions = modelsService.instance.getModels(ModelUsage.Edit);
164638
164729
  const modelItems = getModelOptionItems(modelOptions, isCodyPro);
@@ -164921,7 +165012,7 @@ const getInput = async (document2, initialValues, source) => {
164921
165012
  });
164922
165013
  };
164923
165014
  function getOverridenModelForIntent(intent, currentModel, authStatus) {
164924
- if (!authStatus.isDotCom) {
165015
+ if (!isDotCom(authStatus)) {
164925
165016
  return currentModel;
164926
165017
  }
164927
165018
  switch (intent) {
@@ -165890,7 +165981,7 @@ class FixupController {
165890
165981
  return task;
165891
165982
  }
165892
165983
  async createTask(document2, instruction, userContextFiles, selectionRange, intent, mode, model2, source, destinationFile, insertionPoint, telemetryMetadata, taskId) {
165893
- const authStatus = authProvider.instance.getAuthStatus();
165984
+ const authStatus = authProvider.instance.status;
165894
165985
  const overridenModel = getOverridenModelForIntent(intent, model2, authStatus);
165895
165986
  const fixupFile = this.files.forUri(document2.uri);
165896
165987
  const task = new FixupTask(
@@ -167437,6 +167528,7 @@ class EditProvider {
167437
167528
  this.config.controller.startTask(this.config.task);
167438
167529
  const model2 = this.config.task.model;
167439
167530
  const contextWindow = modelsService.instance.getContextWindowByID(model2);
167531
+ const authStatus = authProvider.instance.statusAuthed;
167440
167532
  const {
167441
167533
  messages,
167442
167534
  stopSequences,
@@ -167444,7 +167536,7 @@ class EditProvider {
167444
167536
  responsePrefix = ""
167445
167537
  } = await buildInteraction$1({
167446
167538
  model: model2,
167447
- codyApiVersion: authProvider.instance.getAuthStatus().codyApiVersion,
167539
+ codyApiVersion: authStatus.codyApiVersion,
167448
167540
  contextWindow: contextWindow.input,
167449
167541
  task: this.config.task,
167450
167542
  editor: this.config.editor
@@ -167526,7 +167618,7 @@ class EditProvider {
167526
167618
  void this.handleResponse(text, false);
167527
167619
  return;
167528
167620
  }
167529
- if (isNetworkError(err2)) {
167621
+ if (isNetworkLikeError(err2)) {
167530
167622
  err2 = new Error("Cody could not respond due to network error.");
167531
167623
  }
167532
167624
  this.handleError(err2);
@@ -167551,7 +167643,6 @@ class EditProvider {
167551
167643
  return this.handleResponse(response, false);
167552
167644
  }
167553
167645
  async handleResponse(response, isMessageInProgress) {
167554
- var _a3;
167555
167646
  if (!response && !isMessageInProgress) {
167556
167647
  this.handleError(new Error("Cody did not respond with any text"));
167557
167648
  }
@@ -167573,7 +167664,7 @@ class EditProvider {
167573
167664
  ...countCode(response)
167574
167665
  };
167575
167666
  const { metadata: metadata2, privateMetadata } = splitSafeMetadata(legacyMetadata);
167576
- const endpoint = (_a3 = authProvider.instance.getAuthStatus()) == null ? void 0 : _a3.endpoint;
167667
+ const endpoint = authProvider.instance.status.endpoint;
167577
167668
  telemetryRecorder.recordEvent("cody.fixup.response", "hasCode", {
167578
167669
  metadata: metadata2,
167579
167670
  privateMetadata: {
@@ -167864,6 +167955,7 @@ class EditManager {
167864
167955
  const documentRange = new Range(0, 0, document2.lineCount, 0);
167865
167956
  editor.setDecorations(SMART_APPLY_FILE_DECORATION, [documentRange]);
167866
167957
  const replacementCode = PromptString.unsafe_fromLLMResponse(configuration2.replacement);
167958
+ const authStatus = authProvider.instance.statusAuthed;
167867
167959
  const selection = await getSmartApplySelection(
167868
167960
  configuration2.id,
167869
167961
  configuration2.instruction,
@@ -167871,7 +167963,7 @@ class EditManager {
167871
167963
  configuration2.document,
167872
167964
  model2,
167873
167965
  this.options.chat,
167874
- authProvider.instance.getAuthStatus().codyApiVersion
167966
+ authStatus.codyApiVersion
167875
167967
  );
167876
167968
  editor.setDecorations(SMART_APPLY_FILE_DECORATION, []);
167877
167969
  if (!selection) {
@@ -168324,8 +168416,8 @@ async function configureExternalServices(context2, config, platform2) {
168324
168416
  Please check that the repository exists. You can override the repository with the "cody.codebase" setting.`
168325
168417
  );
168326
168418
  }
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());
168419
+ const localEmbeddings = authProvider.instance.status.authenticated && isDotCom(authProvider.instance.status) ? await ((_d2 = platform2.createLocalEmbeddingsController) == null ? void 0 : _d2.call(platform2, initialConfig)) : void 0;
168420
+ const chatClient = new ChatClient(completionsClient, () => authProvider.instance.statusAuthed);
168329
168421
  const guardrails = new SourcegraphGuardrailsClient(graphqlClient, initialConfig);
168330
168422
  const contextAPIClient = new ContextAPIClient(graphqlClient);
168331
168423
  return {
@@ -169345,7 +169437,7 @@ class MinionController extends ReactPanelController {
169345
169437
  }
169346
169438
  }
169347
169439
  async handleSetSession(id) {
169348
- const storedSessionState = await this.storage.load(authProvider.instance.getAuthStatus(), id);
169440
+ const storedSessionState = await this.storage.load(authProvider.instance.status, id);
169349
169441
  if (!storedSessionState) {
169350
169442
  throw new Error(`session not found with id: ${id}`);
169351
169443
  }
@@ -169361,7 +169453,7 @@ class MinionController extends ReactPanelController {
169361
169453
  this.postUpdateSessionIds();
169362
169454
  }
169363
169455
  async handleClearHistory() {
169364
- await this.storage.clear(authProvider.instance.getAuthStatus());
169456
+ await this.storage.clear(authProvider.instance.status);
169365
169457
  if (this.sessionState) {
169366
169458
  await this.save();
169367
169459
  }
@@ -169436,7 +169528,7 @@ class MinionController extends ReactPanelController {
169436
169528
  if (!this.sessionState) {
169437
169529
  throw new Error("no session to save");
169438
169530
  }
169439
- await this.storage.save(authProvider.instance.getAuthStatus(), {
169531
+ await this.storage.save(authProvider.instance.status, {
169440
169532
  session: this.sessionState.session
169441
169533
  });
169442
169534
  }
@@ -169494,7 +169586,7 @@ class MinionController extends ReactPanelController {
169494
169586
  var _a3;
169495
169587
  this.postMessage({
169496
169588
  type: "update-session-ids",
169497
- sessionIds: await this.storage.listIds(authProvider.instance.getAuthStatus()),
169589
+ sessionIds: await this.storage.listIds(authProvider.instance.status),
169498
169590
  currentSessionId: (_a3 = this.sessionState) == null ? void 0 : _a3.session.id
169499
169591
  });
169500
169592
  }
@@ -169618,8 +169710,8 @@ const _CodyProExpirationNotifications = class _CodyProExpirationNotifications {
169618
169710
  () => setTimeout(() => this.triggerExpirationCheck(), this.autoUpdateDelay)
169619
169711
  );
169620
169712
  }
169621
- const authStatus = authProvider.instance.getAuthStatus();
169622
- if (!authStatus.isLoggedIn || !authStatus.isDotCom) return;
169713
+ const authStatus = authProvider.instance.status;
169714
+ if (!authStatus.authenticated || !isDotCom(authStatus)) return;
169623
169715
  const useSscForCodySubscription = await featureFlagProvider.instance.evaluateFeatureFlag(
169624
169716
  FeatureFlag.UseSscForCodySubscription
169625
169717
  );
@@ -169847,7 +169939,7 @@ const showFeedbackSupportQuickPick = async () => {
169847
169939
  function groupCodyChats(authStatus) {
169848
169940
  var _a3, _b2, _c2, _d2;
169849
169941
  const chatHistoryGroups = /* @__PURE__ */ new Map();
169850
- if (!authStatus) {
169942
+ if (!authStatus || !authStatus.authenticated) {
169851
169943
  return null;
169852
169944
  }
169853
169945
  const chats = (_a3 = chatHistory.getLocalHistory(authStatus)) == null ? void 0 : _a3.chat;
@@ -169873,16 +169965,10 @@ function groupCodyChats(authStatus) {
169873
169965
  if (!chatHistoryGroups.has(timeUnit)) {
169874
169966
  chatHistoryGroups.set(timeUnit, []);
169875
169967
  }
169876
- const chatItem = {
169968
+ (_d2 = chatHistoryGroups.get(timeUnit)) == null ? void 0 : _d2.push({
169877
169969
  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);
169970
+ title: chatTitle
169971
+ });
169886
169972
  }
169887
169973
  }
169888
169974
  return Object.fromEntries(chatHistoryGroups);
@@ -170126,9 +170212,9 @@ function createStatusBar() {
170126
170212
  let authStatus;
170127
170213
  const command = commands$1.registerCommand(STATUS_BAR_INTERACTION_COMMAND, async () => {
170128
170214
  telemetryRecorder.recordEvent("cody.statusbarIcon", "clicked", {
170129
- privateMetadata: { loggedIn: Boolean(authStatus == null ? void 0 : authStatus.isLoggedIn) }
170215
+ privateMetadata: { loggedIn: Boolean(authStatus == null ? void 0 : authStatus.authenticated) }
170130
170216
  });
170131
- if (!(authStatus == null ? void 0 : authStatus.isLoggedIn)) {
170217
+ if (!(authStatus == null ? void 0 : authStatus.authenticated)) {
170132
170218
  void commands$1.executeCommand("cody.chat.focus");
170133
170219
  return;
170134
170220
  }
@@ -170303,19 +170389,19 @@ function createStatusBar() {
170303
170389
  statusBarItem2.tooltip = isCodyIgnoredType ? DEFAULT_TOOLTIP_DISABLED : DEFAULT_TOOLTIP;
170304
170390
  }
170305
170391
  if (authStatus) {
170306
- if (authStatus.isOfflineMode) {
170392
+ if (authStatus.authenticated && authStatus.isOfflineMode) {
170307
170393
  statusBarItem2.text = "$(cody-logo-heavy) Offline";
170308
170394
  statusBarItem2.tooltip = "Cody is in offline mode";
170309
170395
  statusBarItem2.backgroundColor = new ThemeColor("statusBarItem.warningBackground");
170310
170396
  return;
170311
170397
  }
170312
- if (authStatus.showNetworkError) {
170398
+ if (!authStatus.authenticated && authStatus.showNetworkError) {
170313
170399
  statusBarItem2.text = "$(cody-logo-heavy) Connection Issues";
170314
170400
  statusBarItem2.tooltip = "Resolve network issues for Cody to work again";
170315
170401
  statusBarItem2.backgroundColor = new ThemeColor("statusBarItem.errorBackground");
170316
170402
  return;
170317
170403
  }
170318
- if (!authStatus.isLoggedIn) {
170404
+ if (!authStatus.authenticated) {
170319
170405
  statusBarItem2.text = "$(cody-logo-heavy) Sign In";
170320
170406
  statusBarItem2.tooltip = "Sign in to get started with Cody";
170321
170407
  statusBarItem2.backgroundColor = new ThemeColor("statusBarItem.warningBackground");
@@ -171330,7 +171416,10 @@ async function start(context2, platform2) {
171330
171416
  }
171331
171417
  const register = async (context2, configWatcher, platform2, isExtensionModeDevOrTest) => {
171332
171418
  const disposables = [];
171333
- setClientNameVersion(platform2.extensionClient.clientName, platform2.extensionClient.clientVersion);
171419
+ setClientNameVersion(
171420
+ platform2.extensionClient.httpClientNameForLegacyReasons ?? platform2.extensionClient.clientName,
171421
+ platform2.extensionClient.clientVersion
171422
+ );
171334
171423
  disposables.push(manageDisplayPathEnvInfoForExtension());
171335
171424
  await initializeSingletons(platform2, configWatcher, isExtensionModeDevOrTest, disposables);
171336
171425
  disposables.push(await initVSCodeGitApi());
@@ -171384,7 +171473,8 @@ const register = async (context2, configWatcher, platform2, isExtensionModeDevOr
171384
171473
  localEmbeddings,
171385
171474
  symfRunner,
171386
171475
  contextAPIClient,
171387
- contextRetriever
171476
+ contextRetriever,
171477
+ configWatcher
171388
171478
  },
171389
171479
  disposables
171390
171480
  );
@@ -171448,7 +171538,10 @@ async function initializeSingletons(platform2, configWatcher, isExtensionModeDev
171448
171538
  void localStorage.setConfig(config);
171449
171539
  graphqlClient.setConfig(config);
171450
171540
  void featureFlagProvider.instance.refresh();
171451
- contextFiltersProvider.instance.init(repoNameResolver.getRepoNamesFromWorkspaceUri);
171541
+ contextFiltersProvider.instance.init(
171542
+ repoNameResolver.getRepoNamesFromWorkspaceUri,
171543
+ authProvider.instance
171544
+ );
171452
171545
  void modelsService.instance.onConfigChange(config);
171453
171546
  upstreamHealthProvider.instance.onConfigurationChange(config);
171454
171547
  }
@@ -171586,7 +171679,7 @@ function registerChatCommands(disposables) {
171586
171679
  commands$1.executeCommand("workbench.action.moveEditorToNewWindow");
171587
171680
  }),
171588
171681
  commands$1.registerCommand("cody.chat.history.panel", async () => {
171589
- await displayHistoryQuickPick(authProvider.instance.getAuthStatus());
171682
+ await displayHistoryQuickPick(authProvider.instance.status);
171590
171683
  }),
171591
171684
  commands$1.registerCommand(
171592
171685
  "cody.settings.extension.chat",
@@ -171602,13 +171695,16 @@ function registerChatCommands(disposables) {
171602
171695
  }
171603
171696
  function registerAuthCommands(disposables) {
171604
171697
  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()),
171698
+ commands$1.registerCommand("cody.auth.signin", () => showSignInMenu()),
171699
+ commands$1.registerCommand("cody.auth.signout", () => showSignOutMenu()),
171700
+ commands$1.registerCommand("cody.auth.account", () => showAccountMenu()),
171608
171701
  commands$1.registerCommand("cody.auth.support", () => showFeedbackSupportQuickPick()),
171609
171702
  commands$1.registerCommand(
171610
171703
  "cody.auth.status",
171611
- () => authProvider.instance.getAuthStatus()
171704
+ () => {
171705
+ var _a3;
171706
+ return ((_a3 = authProvider.instance) == null ? void 0 : _a3.statusOrNotReadyYet) ?? null;
171707
+ }
171612
171708
  ),
171613
171709
  // Used by the agent
171614
171710
  commands$1.registerCommand(
@@ -171636,14 +171732,14 @@ function registerUpgradeHandlers(configWatcher, disposables) {
171636
171732
  handleUri: async (uri2) => {
171637
171733
  if (uri2.path === "/app-done") ;
171638
171734
  else {
171639
- authProvider.instance.tokenCallbackHandler(uri2, configWatcher.get().customHeaders);
171735
+ tokenCallbackHandler(uri2, configWatcher.get().customHeaders);
171640
171736
  }
171641
171737
  }
171642
171738
  }),
171643
171739
  // Check if user has just moved back from a browser window to upgrade cody pro
171644
171740
  window$1.onDidChangeWindowState(async (ws) => {
171645
- const authStatus = authProvider.instance.getAuthStatus();
171646
- if (ws.focused && authStatus.isDotCom && authStatus.isLoggedIn) {
171741
+ const authStatus = authProvider.instance.status;
171742
+ if (ws.focused && isDotCom(authStatus) && authStatus.authenticated) {
171647
171743
  const res = await graphqlClient.getCurrentUserCodyProEnabled();
171648
171744
  if (res instanceof Error) {
171649
171745
  logError$1("onDidChangeWindowState", "getCurrentUserCodyProEnabled", res);
@@ -171696,7 +171792,7 @@ async function registerDebugCommands(context2, disposables) {
171696
171792
  }
171697
171793
  async function tryRegisterTutorial(context2, disposables) {
171698
171794
  if (!isRunningInsideAgent()) {
171699
- const { registerInteractiveTutorial } = await import("./index-D6VgQlqI.mjs");
171795
+ const { registerInteractiveTutorial } = await import("./index-2bvntcGe.mjs");
171700
171796
  registerInteractiveTutorial(context2).then((disposable) => disposables.push(...disposable));
171701
171797
  }
171702
171798
  }
@@ -171789,7 +171885,8 @@ function registerChat({
171789
171885
  localEmbeddings,
171790
171886
  symfRunner,
171791
171887
  contextAPIClient,
171792
- contextRetriever
171888
+ contextRetriever,
171889
+ configWatcher
171793
171890
  }, disposables) {
171794
171891
  const messageProviderOptions = {
171795
171892
  chat: chatClient,
@@ -171809,7 +171906,8 @@ function registerChat({
171809
171906
  contextRetriever,
171810
171907
  guardrails,
171811
171908
  contextAPIClient || null,
171812
- platform2.extensionClient
171909
+ platform2.extensionClient,
171910
+ configWatcher
171813
171911
  );
171814
171912
  chatsController.registerViewsAndCommands();
171815
171913
  const ghostHintDecorator = new GhostHintDecorator();