@sourcegraph/cody-web 0.31.0 → 0.31.1

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,8 +18,8 @@ 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, _f, _g, _h, _constructing2, _i, _j, _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, _k, _l, _m, _n, _o;
21
- import { b8 as Observable, ch as unsubscribe, ci as AsyncSerialScheduler, cj as authStatus, ck as debounceTime, cl as switchMapReplayOperation, cm as interval, cn as map$1, co as filter$2, cp as startWith$1, cq as switchMap$1, cr as promiseFactoryToObservable, cs as retry$1, bE as isError$3, ct as distinctUntilChanged$1, c2 as firstValueFrom$1, c3 as skipPendingOperation, cu as logDebug$1, cv as graphqlClient, cw as isAbortError, cx as logError$2, cy as semver, cz as pendingOperation, cA as pick, bN as ModelTag, cB as getModelInfo, cC as CHAT_INPUT_TOKEN_BUDGET, cD as CHAT_OUTPUT_TOKEN_BUDGET, cE as EXTENDED_CHAT_INPUT_TOKEN_BUDGET, cF as EXTENDED_USER_CONTEXT_TOKEN_BUDGET, cG as createSubscriber, cH as fromVSCodeEvent, bf as isEqual, cI as cenv, bn as isDotCom, cJ as currentAuthStatus, cK as isFileURI, w as wrapInActiveSpan, cL as INCLUDE_EVERYTHING_CONTEXT_FILTERS, cM as EXCLUDE_EVERYTHING_CONTEXT_FILTERS, cN as onAbort, cO as addCodyClientIdentificationHeaders, cP as addTraceparent, cQ as addAuthHeaders, cR as fetch$3, cS as verifyResponseCode, cT as combineLatest$1, cU as take$2, cV as clientCapabilities, cW as shareReplay$1, cX as tap$2, cY as featureFlagProvider, bs as FeatureFlag, cZ as getExperimentalClientModelByFeatureFlag, bV as ToolCodyModelName, c_ as TOOL_CODY_MODEL, c$ as getEnterpriseContextWindow, d0 as ANSWER_TOKENS, d1 as storeLastValue, d2 as resolvedConfig, d3 as userProductSubscription, bY as firstResultFromOperation, d4 as isEnterpriseUser, bA as isCodyProUser, d as ps, d5 as currentResolvedConfig, cd as PromptString, bB as CodyIDE, d6 as CORPUS_CONTEXT_ALLOCATION, d7 as isCustomModel, d8 as recordErrorToSpan, d9 as addClientInfoParams, da as dependentAbortController, az as FILE_CONTEXT_MENTION_PROVIDER, aA as SYMBOL_CONTEXT_MENTION_PROVIDER, aB as REMOTE_REPOSITORY_PROVIDER_URI, aC as REMOTE_FILE_PROVIDER_URI, aD as REMOTE_DIRECTORY_PROVIDER_URI, aE as WEB_PROVIDER_URI, t as telemetryRecorder, C as ContextItemSource, bH as lodashExports, db as isS2, dc as GIT_OPENCTX_PROVIDER_URI, dd as CODE_SEARCH_PROVIDER_URI, bD as cryptoJsExports, de as currentOpenCtxController, aW as URI, df as MulticastSubject, dg as AsyncSerialScheduler_1, i as getDefaultExportFromCjs, b as workspace, p as path, dh as vscode, R as Range, c as commands$1, a as window$1, di as Selection, U as Uri, dj as AgentEventEmitter, dk as MarkdownString, g as Disposable, dl as TextEditorRevealType, dm as ThemeIcon, dn as StatusBarAlignment, dp as readFile, dq as env, dr as UIKind, l as languages$1, h as commonjsGlobal, ds as _baseAssignValue, dt as eq_1, du as isArrayLike_1, dv as isObjectLike_1, dw as _copyObject, dx as keysIn_1, dy as _cloneBufferExports, dz as _cloneTypedArray, dA as _copyArray, dB as _initCloneObject, dC as isArguments_1, dD as isArray_1, dE as isBufferExports, dF as isFunction_1, dG as isObject_1, dH as isPlainObject_1, dI as isTypedArray_1, dJ as _Stack, dK as identity_1, dL as _overRest, dM as _setToString, dN as _isIndex, bo as isSourcegraphToken, dO as v4, dP as CONFIG_KEY, cb as CodyAutoSuggestionMode, dQ as ConfigurationTarget, dR as pathBrowserify, dS as stat, dT as extensions, dU as version$2, dV as setExtensionVersion, dW as withLatestFrom, dX as NEVER, dY as abortableOperation, dZ as disposableSubscription, d_ as setAuthStatusObservable, d$ as DOTCOM_URL, e0 as normalizeServerEndpointURL, e1 as ProgressLocation, e2 as SourcegraphGraphQLAPIClient, e3 as isExternalProviderAuthError, e4 as isNetworkLikeError, e5 as resolveAuth, e6 as QuickPickItemKind, e7 as getAuthErrorMessage, e8 as isWorkspaceInstance, e9 as SUPPORTED_URI_SCHEMAS, ea as _baseIsEqual, eb as keys_1, ec as _baseGet, ed as _castPath, ee as isLength_1, ef as _toKey, eg as _isKey, eh as toNumber_1, ei as _baseFindIndex, ej as require$$0$2, ek as NetworkError, el as isRateLimitError, em as isAuthError, en as FileType, e as dedent$1, eo as FoldingRange, ep as CancellationTokenSource, eq as SymbolKind, bJ as isDefined, er as convertGitCloneURLToCodebaseName, es as pluck, et as toRangeData, P as Position, eu as DefaultChatCommands, ev as pathFunctionsForURI, ew as uriParseNameAndExtension, ex as uriDirname, ey as Utils$1, ez as uriExtname, eA as uriBasename, eB as DefaultEditCommands, eC as subscriptionDisposable, eD as NoOpTelemetryRecorderProvider, eE as TimestampTelemetryProcessor_1, eF as updateGlobalTelemetryInstances, eG as TelemetryRecorderProvider, eH as telemetryRecorderProvider, eI as createGitDiff, eJ as catchError$1, eK as AgentWorkspaceEdit, eL as TextDocumentChangeReason, eM as omit$1, eN as displayPathWithoutWorkspaceFolderPrefix, eO as getEditorInsertSpaces, eP as escapeRegExp$1, eQ as isNetworkError, bU as isCodyProModel, eR as http, eS as open, bC as CodyTaskState, f as CodeLens, eT as defaultWebviewPanel, b9 as createExtensionAPI, ba as createMessageAPIForWebview, eU as EndOfLine, eV as ViewColumn, eW as Location, eX as onDidChangeActiveTextEditor, eY as tabGroups, eZ as workspaceTextDocuments, e_ as visibleTextEditors, e$ as onDidChangeVisibleTextEditors, f0 as fs, f1 as onDidCloseTextDocument, f2 as setCreateWebviewPanel, f3 as getAugmentedNamespace, f4 as extensionConfiguration, f5 as main$1, f6 as setAgent, f7 as setWorkspaceDocuments, f8 as onDidRegisterNewCodeActionProvider, f9 as onDidUnregisterNewCodeActionProvider, fa as onDidRegisterNewCodeLensProvider, fb as onDidUnregisterNewCodeLensProvider, fc as setClientInfo, fd as AgentWorkspaceConfiguration, fe as firstNonPendingAuthStatus, ff as setWorkspaceFolders, fg as onDidChangeWorkspaceFolders, fh as onDidChangeWindowState, fi as onDidOpenTextDocument, fj as onDidSaveTextDocument, fk as packageJson, fl as progressBars, fm as CodeActionTriggerKind, fn as CodeAction, fo as UriString, D as DiagnosticSeverity, fp as diagnostics, fq as isIntegrationTesting, fr as TESTING_TELEMETRY_EXPORTER, fs as dist, ft as completionProvider, fu as InlineCompletionTriggerKind, fv as checkIfEnterpriseUser, fw as currentAuthStatusAuthed, fx as waitUntilComplete, fy as setExtensionConfiguration, fz as onDidChangeConfiguration, fA as onDidChangeTextDocument, fB as onDidChangeTextEditorSelection, fC as workspaceFolders$1, fD as isTokenOrEndpointChange, bX as isMacOS, fE as QuickInputButtons, bS as CustomCommandType, fF as RelativePattern, ce as setDisplayPathEnvInfo, fG as isWindows, fH as currentAuthStatusOrNotReadyYet, fI as currentUserProductSubscription, b$ as ACCOUNT_USAGE_URL, bb as debounce$1, aG as displayPath, fJ as structuredPatch, fK as isDotComAuthed, fL as dedupeWith$1, fM as AbortError, fN as TimeoutError, fO as createDisposables, fP as getClientInfoQueryParams, fQ as tracer, fR as getClientIdentificationHeaders, fS as logResponseHeadersToSpan, fT as getActiveTraceAndSpanId, fU as TracedError, fV as isNodeResponse, br as SpanStatusCode, bF as RateLimitError$2, fW as capitalize, fX as createTwoFilesPatch, T as ThemeColor, fY as getEditorTabSize$1, bv as whitespace, bt as svg, bw as find$1, bx as stringify$1, by as stringify$2, bz as ccount, bu as html$4, fZ as InlineCompletionItem, f_ as isFreeUser, f$ as exec, g0 as _baseGetTag, g1 as MAX_BYTES_PER_FILE, g2 as debounce_1, cc as isErrorLike, g3 as mentionProvidersMetadata, g4 as expandToLineRange, aJ as displayPathBasename, aH as displayLineRange, g5 as openctxController, bO as DeepCodyAgentID, b5 as parseMentionQuery, g6 as openCtxProviderMetadata, g7 as editorStateFromPromptString, g8 as inputTextWithoutContextChipsFromPromptEditorState, bM as isAbortErrorOrSocketHangUp, s as spawn, g9 as ToolCodyModelRef, ga as PromptMode, gb as skip$1, bq as context, gc as extractContextFromTraceparent, gd as isContextWindowLimitError, bl as forceHydration, bL as reformatBotMessageForChat, bm as hydrateAfterPostMessage, ge as addMessageListenersForExtensionAPI, gf as createMessageAPIForExtension, bT as View, gg as CODY_PASSTHROUGH_VSCODE_OPEN_COMMAND_ID, gh as CodeActionKind, c6 as pluralize, gi as assertFileURI, gj as defer$2, gk as merge$2, gl as ruleSearchPaths, gm as isRuleFilename, gn as parseRuleFile, go as languageFromFilename, aF as RULES_PROVIDER_URI, gp as ruleTitle, gq as createCodeSearchProvider, gr as psDedent, gs as DecorationRangeBehavior, gt as ProgrammingLanguage, gu as MAX_CURRENT_FILE_TOKENS, gv as formatRuleForPrompt, gw as posixFilePaths, gx as SURROUNDING_LINES, gy as ACCOUNT_UPGRADE_URL, bg as scanForMentionTriggerInUserTextInput, aL as LARGE_FILE_WARNING_LABEL, gz as GENERAL_HELP_LABEL, gA as diffLines, gB as CODY_SUPPORT_URL, gC as CODY_DOC_URL, gD as CODY_FEEDBACK_URL, gE as DISCORD_URL, bW as getRelativeChatPeriod, gF as globalAgentRef, gG as VSCODE_CHANGELOG_URL, gH as SG_CHANGELOG_URL, gI as ACCOUNT_LIMITS_INFO_URL, gJ as assertUnreachable, gK as promise, gL as ExtensionMode, gM as setLogger, gN as setClientCapabilities, gO as setResolvedConfigurationObservable, gP as _, gQ as setClientNameVersion, gR as setOpenCtxControllerObservable, gS as CODY_OLLAMA_DOCS_URL, ca as browser$2 } from "./vscode-shim-DuhCkl0x.mjs";
22
- import { r as requireUtil, i as inherits_browserExports, a as utilExports } from "./util-Bt98Paeh.mjs";
21
+ import { b9 as Observable, ck as unsubscribe, cl as AsyncSerialScheduler, cm as authStatus, cn as debounceTime, co as switchMapReplayOperation, cp as interval, cq as map$1, cr as filter$2, cs as startWith$1, ct as switchMap$1, cu as promiseFactoryToObservable, cv as retry$1, bH as isError$3, cw as distinctUntilChanged$1, c5 as firstValueFrom$1, c6 as skipPendingOperation, cx as logDebug$1, cy as graphqlClient, cz as isAbortError, cA as logError$2, cB as semver, cC as pendingOperation, cD as pick, bQ as ModelTag, cE as getModelInfo, cF as CHAT_INPUT_TOKEN_BUDGET, cG as CHAT_OUTPUT_TOKEN_BUDGET, cH as EXTENDED_CHAT_INPUT_TOKEN_BUDGET, cI as EXTENDED_USER_CONTEXT_TOKEN_BUDGET, cJ as TRANSIENT_REFETCH_INTERVAL_HINT, cK as createSubscriber, cL as fromVSCodeEvent, bg as isEqual, cM as cenv, bK as lodashExports, cN as EXCLUDE_EVERYTHING_CONTEXT_FILTERS, bo as isDotCom, cO as currentAuthStatus, cP as isFileURI, w as wrapInActiveSpan, cQ as INCLUDE_EVERYTHING_CONTEXT_FILTERS, cR as onAbort, cS as addCodyClientIdentificationHeaders, cT as addTraceparent, cU as addAuthHeaders, cV as fetch$3, cW as verifyResponseCode, cX as combineLatest$1, cY as take$2, cZ as clientCapabilities, c_ as shareReplay$1, c$ as tap$2, d0 as featureFlagProvider, bv as FeatureFlag, d1 as getExperimentalClientModelByFeatureFlag, bY as ToolCodyModelName, d2 as TOOL_CODY_MODEL, d3 as getEnterpriseContextWindow, d4 as ANSWER_TOKENS, d5 as storeLastValue, d6 as resolvedConfig, d7 as userProductSubscription, b$ as firstResultFromOperation, d8 as isEnterpriseUser, bD as isCodyProUser, d as ps, d9 as currentResolvedConfig, cg as PromptString, bE as CodyIDE, da as CORPUS_CONTEXT_ALLOCATION, db as isCustomModel, dc as recordErrorToSpan, dd as addClientInfoParams, de as dependentAbortController, az as FILE_CONTEXT_MENTION_PROVIDER, aA as SYMBOL_CONTEXT_MENTION_PROVIDER, aB as REMOTE_REPOSITORY_PROVIDER_URI, aC as REMOTE_FILE_PROVIDER_URI, aD as REMOTE_DIRECTORY_PROVIDER_URI, aE as WEB_PROVIDER_URI, t as telemetryRecorder, C as ContextItemSource, df as isS2, dg as GIT_OPENCTX_PROVIDER_URI, dh as CODE_SEARCH_PROVIDER_URI, bG as cryptoJsExports, di as currentOpenCtxController, aX as URI, dj as MulticastSubject, dk as AsyncSerialScheduler_1, i as getDefaultExportFromCjs, b as workspace, p as path, dl as vscode, R as Range, c as commands$1, a as window$1, dm as Selection, U as Uri, dn as AgentEventEmitter, dp as MarkdownString, g as Disposable, dq as TextEditorRevealType, dr as ThemeIcon, ds as StatusBarAlignment, dt as readFile, du as env, dv as UIKind, l as languages$1, h as commonjsGlobal, dw as InvalidAccessTokenError, dx as _baseAssignValue, dy as eq_1, dz as isArrayLike_1, dA as isObjectLike_1, dB as _copyObject, dC as keysIn_1, dD as _cloneBufferExports, dE as _cloneTypedArray, dF as _copyArray, dG as _initCloneObject, dH as isArguments_1, dI as isArray_1, dJ as isBufferExports, dK as isFunction_1, dL as isObject_1, dM as isPlainObject_1, dN as isTypedArray_1, dO as _Stack, dP as identity_1, dQ as _overRest, dR as _setToString, dS as _isIndex, br as isSourcegraphToken, dT as v4, dU as CONFIG_KEY, ce as CodyAutoSuggestionMode, dV as ConfigurationTarget, dW as pathBrowserify, dX as stat, dY as extensions, dZ as version$2, d_ as setExtensionVersion, d$ as withLatestFrom, e0 as NEVER, e1 as abortableOperation, e2 as isNeedsAuthChallengeError, e3 as EMPTY$1, e4 as disposableSubscription, e5 as setAuthStatusObservable, e6 as DOTCOM_URL, bq as isAvailabilityError, e7 as isInvalidAccessTokenError, e8 as normalizeServerEndpointURL, e9 as isEnterpriseUserDotComError, ea as ProgressLocation, eb as AuthConfigError, ec as SourcegraphGraphQLAPIClient, ed as isExternalProviderAuthError, ee as isNetworkLikeError, ef as NeedsAuthChallengeError, eg as AvailabilityError, eh as EnterpriseUserDotComError, ei as resolveAuth, ej as QuickPickItemKind, ek as isWorkspaceInstance, el as getAuthHeaders, em as SUPPORTED_URI_SCHEMAS, en as _baseIsEqual, eo as keys_1, ep as _baseGet, eq as _castPath, er as isLength_1, es as _toKey, et as _isKey, eu as toNumber_1, ev as _baseFindIndex, ew as require$$0$2, ex as NetworkError, ey as isRateLimitError, bp as isAuthError, ez as FileType, e as dedent$1, eA as FoldingRange, eB as CancellationTokenSource, eC as SymbolKind, bM as isDefined, eD as convertGitCloneURLToCodebaseName, eE as pluck, eF as toRangeData, P as Position, eG as DefaultChatCommands, eH as pathFunctionsForURI, eI as uriParseNameAndExtension, eJ as uriDirname, eK as Utils$1, eL as uriExtname, eM as uriBasename, eN as DefaultEditCommands, eO as subscriptionDisposable, eP as NoOpTelemetryRecorderProvider, eQ as TimestampTelemetryProcessor_1, eR as updateGlobalTelemetryInstances, eS as TelemetryRecorderProvider, eT as telemetryRecorderProvider, eU as createGitDiff, eV as catchError$1, eW as AgentWorkspaceEdit, eX as TextDocumentChangeReason, eY as omit$1, eZ as displayPathWithoutWorkspaceFolderPrefix, e_ as getEditorInsertSpaces, e$ as escapeRegExp$1, f0 as isNetworkError, bX as isCodyProModel, f1 as http, f2 as open, bF as CodyTaskState, f as CodeLens, f3 as defaultWebviewPanel, ba as createExtensionAPI, bb as createMessageAPIForWebview, f4 as EndOfLine, f5 as ViewColumn, f6 as Location, f7 as onDidChangeActiveTextEditor, f8 as tabGroups, f9 as workspaceTextDocuments, fa as visibleTextEditors, fb as onDidChangeVisibleTextEditors, fc as fs, fd as onDidCloseTextDocument, fe as setCreateWebviewPanel, ff as getAugmentedNamespace, fg as extensionConfiguration, fh as main$1, fi as setAgent, fj as setWorkspaceDocuments, fk as onDidRegisterNewCodeActionProvider, fl as onDidUnregisterNewCodeActionProvider, fm as onDidRegisterNewCodeLensProvider, fn as onDidUnregisterNewCodeLensProvider, fo as setClientInfo, fp as AgentWorkspaceConfiguration, fq as firstNonPendingAuthStatus, fr as setWorkspaceFolders, fs as onDidChangeWorkspaceFolders, ft as onDidChangeWindowState, fu as onDidOpenTextDocument, fv as onDidSaveTextDocument, fw as packageJson, fx as progressBars, fy as CodeActionTriggerKind, fz as CodeAction, fA as UriString, D as DiagnosticSeverity, fB as diagnostics, fC as isIntegrationTesting, fD as TESTING_TELEMETRY_EXPORTER, fE as dist, fF as completionProvider, fG as InlineCompletionTriggerKind, fH as checkIfEnterpriseUser, fI as currentAuthStatusAuthed, fJ as waitUntilComplete, fK as setExtensionConfiguration, fL as onDidChangeConfiguration, fM as onDidChangeTextDocument, fN as onDidChangeTextEditorSelection, fO as workspaceFolders$1, fP as isTokenOrEndpointChange, b_ as isMacOS, fQ as QuickInputButtons, bV as CustomCommandType, fR as RelativePattern, ch as setDisplayPathEnvInfo, fS as isWindows, fT as currentAuthStatusOrNotReadyYet, fU as currentUserProductSubscription, c2 as ACCOUNT_USAGE_URL, bc as debounce$1, aG as displayPath, fV as structuredPatch, fW as isDotComAuthed, fX as dedupeWith$1, fY as AbortError, fZ as TimeoutError, f_ as createDisposables, f$ as getClientInfoQueryParams, g0 as tracer, g1 as getClientIdentificationHeaders, g2 as setJSONAcceptContentTypeHeaders, g3 as logResponseHeadersToSpan, g4 as getActiveTraceAndSpanId, g5 as isCustomAuthChallengeResponse, g6 as TracedError, g7 as isNodeResponse, bu as SpanStatusCode, bI as RateLimitError$2, g8 as capitalize, g9 as createTwoFilesPatch, T as ThemeColor, ga as getEditorTabSize$1, by as whitespace, bw as svg, bz as find$1, bA as stringify$1, bB as stringify$2, bC as ccount, bx as html$4, gb as InlineCompletionItem, gc as isFreeUser, gd as exec, ge as _baseGetTag, gf as MAX_BYTES_PER_FILE, gg as debounce_1, cf as isErrorLike, gh as mentionProvidersMetadata, aJ as displayPathBasename, gi as expandToLineRange, aH as displayLineRange, gj as openctxController, bR as DeepCodyAgentID, b6 as parseMentionQuery, gk as openCtxProviderMetadata, gl as editorStateFromPromptString, gm as inputTextWithoutContextChipsFromPromptEditorState, bP as isAbortErrorOrSocketHangUp, s as spawn, gn as ToolCodyModelRef, go as PromptMode, gp as skip$1, bt as context, gq as extractContextFromTraceparent, gr as isContextWindowLimitError, bm as forceHydration, bO as reformatBotMessageForChat, bn as hydrateAfterPostMessage, gs as addMessageListenersForExtensionAPI, gt as createMessageAPIForExtension, bW as View, gu as CODY_PASSTHROUGH_VSCODE_OPEN_COMMAND_ID, gv as CodeActionKind, c9 as pluralize, gw as assertFileURI, gx as defer$2, gy as merge$2, gz as ruleSearchPaths, gA as isRuleFilename, gB as parseRuleFile, gC as languageFromFilename, aF as RULES_PROVIDER_URI, gD as ruleTitle, gE as createCodeSearchProvider, gF as psDedent, gG as DecorationRangeBehavior, gH as ProgrammingLanguage, gI as MAX_CURRENT_FILE_TOKENS, gJ as formatRuleForPrompt, gK as posixFilePaths, gL as SURROUNDING_LINES, gM as ACCOUNT_UPGRADE_URL, bh as scanForMentionTriggerInUserTextInput, aL as LARGE_FILE_WARNING_LABEL, gN as GENERAL_HELP_LABEL, gO as diffLines, gP as CODY_SUPPORT_URL, gQ as CODY_DOC_URL, gR as CODY_FEEDBACK_URL, gS as DISCORD_URL, bZ as getRelativeChatPeriod, gT as globalAgentRef, gU as VSCODE_CHANGELOG_URL, gV as SG_CHANGELOG_URL, gW as ACCOUNT_LIMITS_INFO_URL, gX as assertUnreachable, gY as promise, gZ as ExtensionMode, g_ as setLogger, g$ as setClientCapabilities, h0 as setResolvedConfigurationObservable, h1 as _, h2 as setClientNameVersion, h3 as setOpenCtxControllerObservable, h4 as CODY_OLLAMA_DOCS_URL, cd as browser$2 } from "./vscode-shim-BMQfq1RF.mjs";
22
+ import { r as requireUtil, i as inherits_browserExports, a as utilExports } from "./util-DVisVv7-.mjs";
23
23
  var NOTHING = Symbol.for("immer-nothing");
24
24
  var DRAFTABLE = Symbol.for("immer-draftable");
25
25
  var DRAFT_STATE = Symbol.for("immer-state");
@@ -7653,18 +7653,6 @@ __publicField2(_RE2JS, "DISABLE_UNICODE_GROUPS", 8);
7653
7653
  */
7654
7654
  __publicField2(_RE2JS, "LONGEST_MATCH", 16);
7655
7655
  let RE2JS = _RE2JS;
7656
- const REFETCH_INTERVAL_MAP = {
7657
- durable: {
7658
- initialInterval: 60 * 60 * 1e3,
7659
- // 1 hour
7660
- backoff: 1
7661
- },
7662
- ephemeral: {
7663
- initialInterval: 7 * 1e3,
7664
- // 7 seconds
7665
- backoff: 1.5
7666
- }
7667
- };
7668
7656
  const allowedSchemes = /* @__PURE__ */ new Set(["http", "https"]);
7669
7657
  function canonicalizeContextFilters(filters) {
7670
7658
  if (isEqual(filters, INCLUDE_EVERYTHING_CONTEXT_FILTERS)) {
@@ -7685,30 +7673,28 @@ const _ContextFiltersProvider = class _ContextFiltersProvider {
7685
7673
  __publicField2(this, "parsedContextFilters", null);
7686
7674
  __publicField2(this, "cache", new LRUCache$1({ max: 128 }));
7687
7675
  __publicField2(this, "lastFetchDelay", 0);
7688
- __publicField2(this, "lastResultLifetime");
7689
- __publicField2(this, "fetchIntervalId");
7676
+ __publicField2(this, "lastFetchTimestamp", 0);
7677
+ __publicField2(this, "lastResultLifetime", Promise.resolve(
7678
+ TRANSIENT_REFETCH_INTERVAL_HINT
7679
+ ));
7690
7680
  __publicField2(this, "contextFiltersSubscriber", createSubscriber());
7691
7681
  __publicField2(this, "onContextFiltersChanged", this.contextFiltersSubscriber.subscribe);
7692
- __publicField2(this, "isTesting", false);
7693
7682
  }
7694
7683
  // Visible for testing.
7695
7684
  get timerStateForTest() {
7696
7685
  return { delay: this.lastFetchDelay, lifetime: this.lastResultLifetime };
7697
7686
  }
7698
- // Fetches context filters and updates the cached filter results. Returns
7699
- // 'ephemeral' if the results should be re-queried sooner because they
7700
- // are transient results arising from, say, a network error; or 'durable'
7701
- // if the results can be cached for a while.
7687
+ // Fetches context filters and updates the cached filter results
7702
7688
  async fetchContextFilters() {
7703
7689
  try {
7704
- const { filters, transient } = await graphqlClient.contextFilters();
7690
+ const { filters, refetchIntervalHint } = await graphqlClient.contextFilters();
7705
7691
  this.setContextFilters(filters);
7706
- return transient ? "ephemeral" : "durable";
7692
+ return refetchIntervalHint;
7707
7693
  } catch (error) {
7708
7694
  logError$2("ContextFiltersProvider", "fetchContextFilters", {
7709
7695
  verbose: error
7710
7696
  });
7711
- return "ephemeral";
7697
+ return TRANSIENT_REFETCH_INTERVAL_HINT;
7712
7698
  }
7713
7699
  }
7714
7700
  get changes() {
@@ -7721,7 +7707,6 @@ const _ContextFiltersProvider = class _ContextFiltersProvider {
7721
7707
  );
7722
7708
  }
7723
7709
  setContextFilters(contextFilters) {
7724
- var _a3, _b2;
7725
7710
  if (isEqual(contextFilters, this.lastContextFiltersResponse)) {
7726
7711
  return;
7727
7712
  }
@@ -7733,40 +7718,43 @@ const _ContextFiltersProvider = class _ContextFiltersProvider {
7733
7718
  verbose: contextFilters
7734
7719
  });
7735
7720
  }
7736
- this.parsedContextFilters = {
7721
+ this.parsedContextFilters = this.parseContextFilter(
7722
+ lodashExports.isError(contextFilters) ? EXCLUDE_EVERYTHING_CONTEXT_FILTERS : contextFilters
7723
+ );
7724
+ this.contextFiltersSubscriber.notify(this.lastContextFiltersResponse);
7725
+ }
7726
+ parseContextFilter(contextFilters) {
7727
+ var _a3, _b2;
7728
+ return {
7737
7729
  include: ((_a3 = contextFilters.include) == null ? void 0 : _a3.map(parseContextFilterItem)) || null,
7738
7730
  exclude: ((_b2 = contextFilters.exclude) == null ? void 0 : _b2.map(parseContextFilterItem)) || null
7739
7731
  };
7740
- this.contextFiltersSubscriber.notify(contextFilters);
7741
7732
  }
7742
7733
  /**
7743
7734
  * Overrides context filters for testing.
7744
7735
  */
7745
7736
  setTestingContextFilters(contextFilters) {
7746
7737
  if (contextFilters === null) {
7747
- this.isTesting = false;
7748
7738
  this.reset();
7749
7739
  } else {
7750
- this.isTesting = true;
7751
7740
  this.setContextFilters(contextFilters);
7752
7741
  }
7753
7742
  }
7754
- startRefetchTimer(intervalHint) {
7755
- if (this.lastResultLifetime === intervalHint) {
7756
- this.lastFetchDelay *= REFETCH_INTERVAL_MAP[intervalHint].backoff;
7757
- } else {
7758
- this.lastFetchDelay = REFETCH_INTERVAL_MAP[intervalHint].initialInterval;
7759
- this.lastResultLifetime = intervalHint;
7760
- }
7761
- this.fetchIntervalId = setTimeout(async () => {
7762
- this.startRefetchTimer(await this.fetchContextFilters());
7763
- }, this.lastFetchDelay);
7764
- }
7765
7743
  async fetchIfNeeded() {
7766
- if (!this.fetchIntervalId && !this.isTesting) {
7767
- const intervalHint = await this.fetchContextFilters();
7768
- this.startRefetchTimer(intervalHint);
7769
- }
7744
+ this.lastResultLifetime = this.lastResultLifetime.then(async (intervalHint) => {
7745
+ if (this.lastFetchTimestamp + this.lastFetchDelay < Date.now()) {
7746
+ this.lastFetchTimestamp = Date.now();
7747
+ const nextIntervalHint = await this.fetchContextFilters();
7748
+ if (isEqual(intervalHint, nextIntervalHint)) {
7749
+ this.lastFetchDelay *= nextIntervalHint.backoff;
7750
+ } else {
7751
+ this.lastFetchDelay = nextIntervalHint.initialInterval;
7752
+ }
7753
+ return nextIntervalHint;
7754
+ }
7755
+ return intervalHint;
7756
+ });
7757
+ await this.lastResultLifetime;
7770
7758
  }
7771
7759
  async isRepoNameIgnored(repoName) {
7772
7760
  if (isDotCom(currentAuthStatus())) {
@@ -7808,6 +7796,10 @@ const _ContextFiltersProvider = class _ContextFiltersProvider {
7808
7796
  if (this.hasIgnoreEverythingFilters()) {
7809
7797
  return "has-ignore-everything-filters";
7810
7798
  }
7799
+ const maybeError = this.lastContextFiltersResponse;
7800
+ if (lodashExports.isError(maybeError)) {
7801
+ return maybeError;
7802
+ }
7811
7803
  if (!isFileURI(uri)) {
7812
7804
  logDebug$1("ContextFiltersProvider", "isUriIgnored", `non-file URI ${uri.scheme}`);
7813
7805
  return "non-file-uri";
@@ -7833,15 +7825,12 @@ const _ContextFiltersProvider = class _ContextFiltersProvider {
7833
7825
  return false;
7834
7826
  }
7835
7827
  reset() {
7828
+ this.lastFetchTimestamp = 0;
7829
+ this.lastResultLifetime = Promise.resolve(TRANSIENT_REFETCH_INTERVAL_HINT);
7836
7830
  this.lastFetchDelay = 0;
7837
- this.lastResultLifetime = void 0;
7838
7831
  this.lastContextFiltersResponse = null;
7839
7832
  this.parsedContextFilters = null;
7840
7833
  this.cache.clear();
7841
- if (this.fetchIntervalId) {
7842
- clearTimeout(this.fetchIntervalId);
7843
- this.fetchIntervalId = void 0;
7844
- }
7845
7834
  }
7846
7835
  dispose() {
7847
7836
  this.reset();
@@ -8586,6 +8575,9 @@ class ModelsService {
8586
8575
  const modelsList = this.models.map((m) => m.id).join(", ");
8587
8576
  throw new Error(`${errorMessage} Available models: ${modelsList}`);
8588
8577
  }
8578
+ getModelsByTag(tag2) {
8579
+ return this.models.filter((m) => m.tags.includes(tag2));
8580
+ }
8589
8581
  isStreamDisabled(modelID) {
8590
8582
  const model2 = this.getModelByID(modelID);
8591
8583
  return (model2 == null ? void 0 : model2.tags.includes(ModelTag.StreamDisabled)) ?? false;
@@ -8772,7 +8764,7 @@ async function currentSiteVersion() {
8772
8764
  }
8773
8765
  async function isValidVersion({ minimumVersion }) {
8774
8766
  const currentVersion = await currentSiteVersion();
8775
- if (currentVersion instanceof Error) {
8767
+ if (isError$3(currentVersion)) {
8776
8768
  return false;
8777
8769
  }
8778
8770
  return checkVersion({ minimumVersion, currentVersion: currentVersion.siteVersion });
@@ -8837,6 +8829,9 @@ class ChatClient {
8837
8829
  currentSiteVersion(),
8838
8830
  await firstValueFrom$1(authStatus)
8839
8831
  ]);
8832
+ if (lodashExports.isError(versions)) {
8833
+ throw versions;
8834
+ }
8840
8835
  if (!authStatus_.authenticated) {
8841
8836
  throw new Error("not authenticated");
8842
8837
  }
@@ -8847,10 +8842,10 @@ class ChatClient {
8847
8842
  const isLastMessageFromHuman = messages.length > 0 && messages.at(-1).speaker === "human";
8848
8843
  const isFireworks = ((_d2 = params == null ? void 0 : params.model) == null ? void 0 : _d2.startsWith("fireworks/")) || ((_e2 = params == null ? void 0 : params.model) == null ? void 0 : _e2.startsWith("fireworks::"));
8849
8844
  const augmentedMessages = isFireworks || useApiV1 ? sanitizeMessages(messages) : isLastMessageFromHuman ? messages.concat([{ speaker: "assistant" }]) : messages;
8850
- const messagesToSend = augmentedMessages.map(({ speaker, text: text2, cache_enabled }) => ({
8845
+ const messagesToSend = augmentedMessages.map(({ speaker, text: text2, cacheEnabled }) => ({
8851
8846
  text: text2,
8852
8847
  speaker,
8853
- cache_enabled
8848
+ cacheEnabled
8854
8849
  }));
8855
8850
  const completionParams = {
8856
8851
  ...DEFAULT_CHAT_COMPLETION_PARAMETERS,
@@ -8894,6 +8889,9 @@ function sanitizeMessages(messages) {
8894
8889
  return sanitizedMessages;
8895
8890
  }
8896
8891
  const DEFAULT_PREAMBLE = ps`You are Cody, an AI coding assistant from Sourcegraph.`;
8892
+ function getDefaultSystemPrompt() {
8893
+ return DEFAULT_PREAMBLE;
8894
+ }
8897
8895
  const SMART_APPLY_PREAMBLE = ps`If your answer contains fenced code blocks in Markdown, include the relevant full file path in the code block tag using this structure: \`\`\`$LANGUAGE:$FILEPATH\`\`\`
8898
8896
  For executable terminal commands: enclose each command in individual "bash" language code block without comments and new lines inside.`;
8899
8897
  const CHAT_PREAMBLE = DEFAULT_PREAMBLE.concat(SMART_APPLY_PREAMBLE);
@@ -9663,7 +9661,7 @@ async function getBytes$2(stream, onChunk) {
9663
9661
  onChunk(result.value);
9664
9662
  }
9665
9663
  }
9666
- function getLines(onLine) {
9664
+ function getLines$1(onLine) {
9667
9665
  let buffer2;
9668
9666
  let position;
9669
9667
  let fieldLength;
@@ -9810,7 +9808,7 @@ function fetchEventSource(input, _a3) {
9810
9808
  try {
9811
9809
  const response = await fetch2(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
9812
9810
  await onopen(response);
9813
- await getBytes$2(response.body, getLines(getMessages((id) => {
9811
+ await getBytes$2(response.body, getLines$1(getMessages((id) => {
9814
9812
  if (id) {
9815
9813
  headers[LastEventId] = id;
9816
9814
  } else {
@@ -9847,15 +9845,42 @@ function defaultOnOpen(response) {
9847
9845
  class CompletionsResponseBuilder {
9848
9846
  constructor(apiVersion) {
9849
9847
  __publicField2(this, "totalCompletion", "");
9848
+ __publicField2(this, "thinkingBuffer", []);
9850
9849
  this.apiVersion = apiVersion;
9851
9850
  }
9852
9851
  nextCompletion(completion, deltaText) {
9852
+ const thinkingText = this.getThinkingText();
9853
9853
  if (this.apiVersion >= 2) {
9854
9854
  this.totalCompletion += deltaText ?? "";
9855
- return this.totalCompletion;
9855
+ } else {
9856
+ this.totalCompletion = completion ?? "";
9857
+ }
9858
+ return thinkingText + this.totalCompletion;
9859
+ }
9860
+ /**
9861
+ * Processes and accumulates thinking steps during the completion stream.
9862
+ * Thinking steps must start at the beginning of completion and are enclosed in <think> tags.
9863
+ * When the completion starts streaming, the previous <think> tag is closed.
9864
+ *
9865
+ * @param deltaThinking - The incremental thinking text to be added
9866
+ * @returns The formatted thinking text wrapped in XML tags
9867
+ */
9868
+ nextThinking(deltaThinking) {
9869
+ if (deltaThinking) {
9870
+ this.thinkingBuffer.push(deltaThinking);
9856
9871
  }
9857
- this.totalCompletion = completion ?? "";
9858
- return this.totalCompletion;
9872
+ return this.getThinkingText();
9873
+ }
9874
+ /**
9875
+ * Generates the formatted thinking text by combining all thinking steps.
9876
+ * Wraps the combined thinking text in <think> tags and adds a newline if content exists.
9877
+ *
9878
+ * @returns Formatted thinking text with XML tags, or empty string if no thinking steps exist
9879
+ */
9880
+ getThinkingText() {
9881
+ const thinking = this.thinkingBuffer.join("");
9882
+ return thinking ? `<think>${thinking}</think>
9883
+ ` : "";
9859
9884
  }
9860
9885
  static fromUrl(url) {
9861
9886
  const apiVersion = Number.parseInt(new URL(url).searchParams.get("api-version") ?? "0", 10);
@@ -11879,7 +11904,7 @@ async function serializePrompts(messages, modelID) {
11879
11904
  messages.map(async (m) => {
11880
11905
  var _a4;
11881
11906
  const text2 = await ((_a4 = m.text) == null ? void 0 : _a4.toFilteredString(contextFiltersProvider));
11882
- if (serverSupportsPromptCaching() && m.cache_enabled) {
11907
+ if (serverSupportsPromptCaching() && m.cacheEnabled) {
11883
11908
  return {
11884
11909
  speaker: m.speaker,
11885
11910
  content: [
@@ -11941,15 +11966,7 @@ class SourcegraphBrowserCompletionsClient extends SourcegraphCompletionsClient {
11941
11966
  // otherwise tries to call document.addEventListener
11942
11967
  async onopen(response) {
11943
11968
  if (!response.ok && response.headers.get("content-type") !== "text/event-stream") {
11944
- let errorMessage = null;
11945
- try {
11946
- errorMessage = await response.text();
11947
- } catch (error2) {
11948
- console.error(error2);
11949
- }
11950
- const error = new Error(
11951
- errorMessage === null || errorMessage.length === 0 ? `Request failed with status code ${response.status}` : errorMessage
11952
- );
11969
+ const error = await verifyResponseCode(response).catch((err2) => err2);
11953
11970
  cb.onError(error, response.status);
11954
11971
  abort2.abort();
11955
11972
  return;
@@ -11999,6 +12016,7 @@ class SourcegraphBrowserCompletionsClient extends SourcegraphCompletionsClient {
11999
12016
  const { url, serializedParams } = await this.prepareRequest(params, requestParams);
12000
12017
  const headersInstance = new Headers({
12001
12018
  "Content-Type": "application/json; charset=utf-8",
12019
+ Accept: "text/event-stream",
12002
12020
  ...configuration.customHeaders,
12003
12021
  ...requestParams.customHeaders
12004
12022
  });
@@ -12013,13 +12031,7 @@ class SourcegraphBrowserCompletionsClient extends SourcegraphCompletionsClient {
12013
12031
  headers: headersInstance,
12014
12032
  body: JSON.stringify(serializedParams),
12015
12033
  signal: signal2
12016
- });
12017
- if (!response.ok) {
12018
- const errorMessage = await response.text();
12019
- throw new Error(
12020
- errorMessage.length === 0 ? `Request failed with status code ${response.status}` : errorMessage
12021
- );
12022
- }
12034
+ }).then(verifyResponseCode);
12023
12035
  const data2 = await response.json();
12024
12036
  if (data2 == null ? void 0 : data2.completion) {
12025
12037
  cb.onChange(data2.completion);
@@ -22044,7 +22056,7 @@ function newAuthStatus(options) {
22044
22056
  return {
22045
22057
  authenticated: false,
22046
22058
  endpoint: options.endpoint,
22047
- error: { type: "invalid-access-token" },
22059
+ error: new InvalidAccessTokenError(),
22048
22060
  pendingValidation: false
22049
22061
  };
22050
22062
  }
@@ -22354,6 +22366,7 @@ class LocalStorage {
22354
22366
  __publicField2(this, "MODEL_PREFERENCES_KEY", "cody-model-preferences");
22355
22367
  __publicField2(this, "CODY_CHAT_MEMORY", "cody-chat-memory");
22356
22368
  __publicField2(this, "AUTO_EDITS_ONBOARDING_NOTIFICATION_COUNT", "cody-auto-edit-notification-info");
22369
+ __publicField2(this, "DEVICE_PIXEL_RATIO", "device-pixel-ratio");
22357
22370
  __publicField2(this, "keys", {
22358
22371
  deepCodyLastUsedDate: "DEEP_CODY_LAST_USED_DATE",
22359
22372
  deepCodyDailyUsageCount: "DEEP_CODY_DAILY_CHAT_USAGE"
@@ -22606,6 +22619,12 @@ class LocalStorage {
22606
22619
  await this.set(this.keys.deepCodyDailyUsageCount, newQuota);
22607
22620
  await this.set(this.keys.deepCodyLastUsedDate, lastUsed);
22608
22621
  }
22622
+ getDevicePixelRatio() {
22623
+ return this.get(this.DEVICE_PIXEL_RATIO);
22624
+ }
22625
+ async setDevicePixelRatio(ratio) {
22626
+ await this.set(this.DEVICE_PIXEL_RATIO, ratio);
22627
+ }
22609
22628
  get(key2) {
22610
22629
  return this.storage.get(key2, null);
22611
22630
  }
@@ -22748,7 +22767,6 @@ function getConfiguration(config = workspace.getConfiguration()) {
22748
22767
  internalDebugState: getHiddenSetting("internal.debug.state", false),
22749
22768
  autocompleteAdvancedModel: getHiddenSetting("autocomplete.advanced.model", null),
22750
22769
  autocompleteExperimentalGraphContext: getHiddenSetting("autocomplete.experimental.graphContext", null),
22751
- experimentalCommitMessage: getHiddenSetting("experimental.commitMessage", true),
22752
22770
  experimentalNoodle: getHiddenSetting("experimental.noodle", false),
22753
22771
  experimentalTracing: getHiddenSetting("experimental.tracing", false),
22754
22772
  experimentalSupercompletions: getHiddenSetting("experimental.supercompletions", false),
@@ -22959,6 +22977,8 @@ function getFeatureFlagEventName(key2) {
22959
22977
  return "interactiveTutorial";
22960
22978
  case FeatureFlag.DeepCody:
22961
22979
  return "deepCody";
22980
+ case FeatureFlag.CodyPromptCachingOnMessages:
22981
+ return "promptCachingOnMessages";
22962
22982
  default:
22963
22983
  return "UnregisteredFeature";
22964
22984
  }
@@ -23013,13 +23033,12 @@ class AuthProvider {
23013
23033
  this.subscriptions.push(
23014
23034
  ClientConfigSingleton.getInstance().updates.pipe(
23015
23035
  abortableOperation(async (config, signal2) => {
23016
- var _a3;
23017
23036
  const nextAuthStatus = await validateCredentials(
23018
23037
  await currentResolvedConfig(),
23019
23038
  signal2,
23020
23039
  config
23021
23040
  );
23022
- if (!nextAuthStatus.authenticated && ((_a3 = nextAuthStatus.error) == null ? void 0 : _a3.type) === "enterprise-user-logged-into-dotcom") {
23041
+ if (!nextAuthStatus.authenticated && isEnterpriseUserDotComError(nextAuthStatus.error)) {
23023
23042
  this.status.next(nextAuthStatus);
23024
23043
  }
23025
23044
  })
@@ -23028,16 +23047,29 @@ class AuthProvider {
23028
23047
  this.subscriptions.push(
23029
23048
  combineLatest$1(
23030
23049
  credentialsChangesNeedingValidation,
23031
- this.refreshRequests.pipe(startWith$1(void 0))
23050
+ this.refreshRequests.pipe(startWith$1(true))
23032
23051
  ).pipe(
23033
- abortableOperation(async ([config], signal2) => {
23052
+ abortableOperation(async ([config, resetInitialAuthStatus], signal2) => {
23034
23053
  if (clientCapabilities().isCodyWeb) {
23035
23054
  return;
23036
23055
  }
23037
- await this.validateAndUpdateAuthStatus(config, signal2);
23056
+ await this.validateAndUpdateAuthStatus(config, signal2, resetInitialAuthStatus);
23038
23057
  })
23039
23058
  ).subscribe({})
23040
23059
  );
23060
+ this.subscriptions.push(
23061
+ authStatus.pipe(
23062
+ switchMap$1((authStatus2) => {
23063
+ if (!authStatus2.authenticated && isNeedsAuthChallengeError(authStatus2.error)) {
23064
+ const intervalMsec = 2500;
23065
+ return interval(intervalMsec);
23066
+ }
23067
+ return EMPTY$1;
23068
+ })
23069
+ ).subscribe(() => {
23070
+ this.refreshRequests.next(false);
23071
+ })
23072
+ );
23041
23073
  this.subscriptions.push(
23042
23074
  authStatus.subscribe((authStatus2) => {
23043
23075
  try {
@@ -23064,14 +23096,16 @@ class AuthProvider {
23064
23096
  )
23065
23097
  );
23066
23098
  }
23067
- async validateAndUpdateAuthStatus(credentials, signal2) {
23068
- this.status.next({
23069
- authenticated: false,
23070
- pendingValidation: true,
23071
- endpoint: credentials.auth.serverEndpoint
23072
- });
23099
+ async validateAndUpdateAuthStatus(credentials, signal2, resetInitialAuthStatus) {
23100
+ if (resetInitialAuthStatus ?? true) {
23101
+ this.status.next({
23102
+ authenticated: false,
23103
+ pendingValidation: true,
23104
+ endpoint: credentials.auth.serverEndpoint
23105
+ });
23106
+ }
23073
23107
  try {
23074
- const authStatus2 = await validateCredentials(credentials, signal2);
23108
+ const authStatus2 = await validateCredentials(credentials, signal2, void 0);
23075
23109
  signal2 == null ? void 0 : signal2.throwIfAborted();
23076
23110
  this.status.next(authStatus2);
23077
23111
  await this.handleAuthTelemetry(authStatus2, signal2);
@@ -23099,9 +23133,9 @@ class AuthProvider {
23099
23133
  /**
23100
23134
  * Refresh the auth status.
23101
23135
  */
23102
- refresh() {
23136
+ refresh(resetInitialAuthStatus = true) {
23103
23137
  this.lastValidatedAndStoredCredentials.next(null);
23104
- this.refreshRequests.next();
23138
+ this.refreshRequests.next(resetInitialAuthStatus);
23105
23139
  }
23106
23140
  signout(endpoint) {
23107
23141
  if (this.lastEndpoint !== endpoint) {
@@ -23193,12 +23227,11 @@ function startAuthTelemetryReporter() {
23193
23227
  });
23194
23228
  }
23195
23229
  function reportAuthTelemetryEvent(authStatus2) {
23196
- var _a3, _b2;
23197
23230
  if (authStatus2.pendingValidation) {
23198
23231
  return;
23199
23232
  }
23200
23233
  let eventValue;
23201
- if (!authStatus2.authenticated && (((_a3 = authStatus2.error) == null ? void 0 : _a3.type) === "network-error" || ((_b2 = authStatus2.error) == null ? void 0 : _b2.type) === "invalid-access-token")) {
23234
+ if (!authStatus2.authenticated && (isAvailabilityError(authStatus2.error) || isInvalidAccessTokenError(authStatus2.error))) {
23202
23235
  eventValue = "failed";
23203
23236
  } else if (authStatus2.authenticated) {
23204
23237
  eventValue = "connected";
@@ -23301,7 +23334,7 @@ async function showSignInMenu(type, uri) {
23301
23334
  const { configuration } = await currentResolvedConfig();
23302
23335
  const auth = await resolveAuth(selectedEndpoint, configuration, secretStorage);
23303
23336
  let authStatus22 = await authProvider.validateAndStoreCredentials(auth, "store-if-valid");
23304
- if (!(authStatus22 == null ? void 0 : authStatus22.authenticated)) {
23337
+ if (!(authStatus22 == null ? void 0 : authStatus22.authenticated) && isInvalidAccessTokenError(authStatus22.error)) {
23305
23338
  const token = await showAccessTokenInputBox(selectedEndpoint);
23306
23339
  if (!token) {
23307
23340
  return;
@@ -23461,7 +23494,7 @@ async function showAuthResultMessage(endpoint, authStatus2) {
23461
23494
  }
23462
23495
  async function showAuthFailureMessage(endpoint, authStatus2) {
23463
23496
  if (authStatus2 == null ? void 0 : authStatus2.error) {
23464
- await window$1.showErrorMessage(getAuthErrorMessage(authStatus2.error).message);
23497
+ await window$1.showErrorMessage(authStatus2.error.message);
23465
23498
  }
23466
23499
  }
23467
23500
  async function tokenCallbackHandler(uri) {
@@ -23551,10 +23584,7 @@ async function validateCredentials(config, signal2, clientConfig) {
23551
23584
  authenticated: false,
23552
23585
  endpoint: config.auth.serverEndpoint,
23553
23586
  pendingValidation: false,
23554
- error: {
23555
- type: "auth-config-error",
23556
- message: ((_a3 = config.auth.error) == null ? void 0 : _a3.message) ?? config.auth.error
23557
- }
23587
+ error: new AuthConfigError(((_a3 = config.auth.error) == null ? void 0 : _a3.message) ?? config.auth.error)
23558
23588
  };
23559
23589
  }
23560
23590
  if (!config.auth.credentials && !clientCapabilities().isCodyWeb) {
@@ -23578,20 +23608,21 @@ async function validateCredentials(config, signal2, clientConfig) {
23578
23608
  logDebug("auth", userInfo.message);
23579
23609
  return {
23580
23610
  authenticated: false,
23581
- error: { type: "external-auth-provider-error", message: userInfo.message },
23611
+ error: userInfo,
23582
23612
  endpoint: config.auth.serverEndpoint,
23583
23613
  pendingValidation: false
23584
23614
  };
23585
23615
  }
23586
- if (isNetworkLikeError(userInfo)) {
23616
+ const needsAuthChallenge = isNeedsAuthChallengeError(userInfo);
23617
+ if (isNetworkLikeError(userInfo) || needsAuthChallenge) {
23587
23618
  logDebug(
23588
23619
  "auth",
23589
- `Failed to authenticate to ${config.auth.serverEndpoint} due to likely network error`,
23620
+ `Failed to authenticate to ${config.auth.serverEndpoint} due to likely network or endpoint availability error`,
23590
23621
  userInfo.message
23591
23622
  );
23592
23623
  return {
23593
23624
  authenticated: false,
23594
- error: { type: "network-error" },
23625
+ error: needsAuthChallenge ? new NeedsAuthChallengeError() : new AvailabilityError(),
23595
23626
  endpoint: config.auth.serverEndpoint,
23596
23627
  pendingValidation: false
23597
23628
  };
@@ -23606,7 +23637,7 @@ async function validateCredentials(config, signal2, clientConfig) {
23606
23637
  return {
23607
23638
  authenticated: false,
23608
23639
  endpoint: config.auth.serverEndpoint,
23609
- error: { type: "invalid-access-token" },
23640
+ error: new InvalidAccessTokenError(),
23610
23641
  pendingValidation: false
23611
23642
  };
23612
23643
  }
@@ -23622,10 +23653,9 @@ async function validateCredentials(config, signal2, clientConfig) {
23622
23653
  authenticated: false,
23623
23654
  endpoint: config.auth.serverEndpoint,
23624
23655
  pendingValidation: false,
23625
- error: {
23626
- type: "enterprise-user-logged-into-dotcom",
23627
- enterprise: getEnterpriseName(((_b2 = userInfo.primaryEmail) == null ? void 0 : _b2.email) || "")
23628
- }
23656
+ error: new EnterpriseUserDotComError(
23657
+ getEnterpriseName(((_b2 = userInfo.primaryEmail) == null ? void 0 : _b2.email) || "")
23658
+ )
23629
23659
  };
23630
23660
  }
23631
23661
  }
@@ -23645,6 +23675,30 @@ function getEnterpriseName(email) {
23645
23675
  const name = domain.split(".")[0];
23646
23676
  return name.charAt(0).toUpperCase() + name.slice(1);
23647
23677
  }
23678
+ async function requestEndpointSettingsDeliveryToSearchPlugin() {
23679
+ const searchExtension = extensions.all.find(
23680
+ ({ packageJSON }) => ["sourcegraph.@sourcegraph/vscode", "sourcegraph.sourcegraph"].includes(packageJSON.id)
23681
+ );
23682
+ const config = await firstResultFromOperation(resolvedConfig);
23683
+ searchExtension == null ? void 0 : searchExtension.activate().then(async () => {
23684
+ var _a3;
23685
+ const commandId = "sourcegraph.setEndpointSettings";
23686
+ const commands2 = (_a3 = searchExtension.packageJSON.contributes) == null ? void 0 : _a3.commands;
23687
+ if (Array.isArray(commands2)) {
23688
+ if (commands2.find(({ command }) => command === commandId)) {
23689
+ const authHeaders = await getAuthHeaders(
23690
+ config.auth,
23691
+ new URL(config.auth.serverEndpoint)
23692
+ );
23693
+ commands$1.executeCommand(commandId, {
23694
+ instanceUrl: config.auth.serverEndpoint,
23695
+ headers: authHeaders
23696
+ });
23697
+ }
23698
+ }
23699
+ });
23700
+ return config.auth.serverEndpoint;
23701
+ }
23648
23702
  class ChatHistoryManager {
23649
23703
  constructor() {
23650
23704
  __publicField2(this, "disposables", []);
@@ -23725,15 +23779,34 @@ function getEditor() {
23725
23779
  };
23726
23780
  return get2();
23727
23781
  }
23728
- async function showCodyIgnoreNotification(feature2, type) {
23729
- window$1.showErrorMessage(
23730
- `${feature2 === "autocomplete" ? "Failed to generate autocomplete" : feature2 === "edit" ? "Edit failed to run" : feature2 === "test" ? "Failed to generate test" : "Command failed to run"}: file is ignored (due to cody.contextFilters Enterprise configuration setting)`
23731
- );
23782
+ function ignoreReason(isIgnore) {
23783
+ if (lodashExports.isError(isIgnore)) {
23784
+ return isIgnore.message;
23785
+ }
23786
+ switch (isIgnore) {
23787
+ case false:
23788
+ return null;
23789
+ case "non-file-uri":
23790
+ return "This current file is ignored as it does not have a valid file URI.";
23791
+ case "no-repo-found":
23792
+ return "This current file is ignored as it is not in known git repository.";
23793
+ case "has-ignore-everything-filters":
23794
+ return "Your administrator has disabled Cody for this file.";
23795
+ default:
23796
+ if (isIgnore.startsWith("repo:")) {
23797
+ return `Your administrator has disabled Cody for '${isIgnore.replace("repo:", "")}'.`;
23798
+ }
23799
+ return "The current file is ignored by Cody.";
23800
+ }
23801
+ }
23802
+ async function showCodyIgnoreNotification(feature2, isIgnored) {
23803
+ const prefix = feature2 === "autocomplete" ? "Failed to generate autocomplete" : feature2 === "edit" ? "Edit failed to run" : feature2 === "test" ? "Failed to generate test" : "Command failed to run";
23804
+ window$1.showErrorMessage(`${prefix}: ${ignoreReason(isIgnored)}`);
23732
23805
  }
23733
23806
  async function isUriIgnoredByContextFilterWithNotification(uri, feature2) {
23734
23807
  const isIgnored = await contextFiltersProvider.isUriIgnored(uri);
23735
23808
  if (isIgnored) {
23736
- showCodyIgnoreNotification(feature2);
23809
+ showCodyIgnoreNotification(feature2, isIgnored);
23737
23810
  }
23738
23811
  return isIgnored;
23739
23812
  }
@@ -42553,6 +42626,10 @@ class Agent extends MessageHandler {
42553
42626
  contextFiltersProvider.setTestingContextFilters(contextFilters);
42554
42627
  return null;
42555
42628
  });
42629
+ this.registerAuthenticatedRequest("internal/getAuthHeaders", async (url) => {
42630
+ const config = await firstResultFromOperation(resolvedConfig);
42631
+ return await getAuthHeaders(config.auth, new URL(url));
42632
+ });
42556
42633
  }
42557
42634
  pushPendingPromise(pendingPromise) {
42558
42635
  if (isIntegrationTesting) {
@@ -42862,8 +42939,7 @@ const CodyCommandMenuItems = [
42862
42939
  description: "Generate Commit Message (Experimental)",
42863
42940
  icon: "git-commit",
42864
42941
  command: { command: "cody.command.generate-commit" },
42865
- keybinding: "",
42866
- requires: { setting: "cody.experimental.commitMessage" }
42942
+ keybinding: ""
42867
42943
  },
42868
42944
  {
42869
42945
  key: "custom",
@@ -43929,7 +44005,7 @@ class CommandsProvider {
43929
44005
  if (!isFileURI(uri)) {
43930
44006
  throw new Error("history only supported on local file paths");
43931
44007
  }
43932
- const { getContextFileFromGitLog } = await import("./git-log-CZLl35Ua.mjs");
44008
+ const { getContextFileFromGitLog } = await import("./git-log-lMMNBgcI.mjs");
43933
44009
  return getContextFileFromGitLog(uri, options);
43934
44010
  }
43935
44011
  dispose() {
@@ -148076,7 +148152,7 @@ class DefaultCodeCompletionsClient {
148076
148152
  ...providerOptions == null ? void 0 : providerOptions.customHeaders,
148077
148153
  ...getClientIdentificationHeaders()
148078
148154
  });
148079
- headers.set("Content-Type", "application/json; charset=utf-8");
148155
+ setJSONAcceptContentTypeHeaders(headers);
148080
148156
  addCodyClientIdentificationHeaders(headers);
148081
148157
  if (tracingFlagEnabled) {
148082
148158
  headers.set("X-Sourcegraph-Should-Trace", "1");
@@ -148126,7 +148202,7 @@ class DefaultCodeCompletionsClient {
148126
148202
  if (!response.ok) {
148127
148203
  throw recordErrorToSpan(
148128
148204
  span2,
148129
- new NetworkError(response, await response.text(), traceId)
148205
+ isCustomAuthChallengeResponse(response) ? new NeedsAuthChallengeError() : new NetworkError(response, await response.text(), traceId)
148130
148206
  );
148131
148207
  }
148132
148208
  if (response.body === null) {
@@ -148646,6 +148722,14 @@ function getDecorationStats({
148646
148722
  unchangedChars: charsStats.unchanged
148647
148723
  };
148648
148724
  }
148725
+ function isOnlyAddingTextForModifiedLines(modifiedLines) {
148726
+ for (const modifiedLine of modifiedLines) {
148727
+ if (modifiedLine.changes.some((change) => change.type === "delete")) {
148728
+ return false;
148729
+ }
148730
+ }
148731
+ return true;
148732
+ }
148649
148733
  class AutoeditSuggestionIdRegistry {
148650
148734
  constructor() {
148651
148735
  __publicField2(this, "suggestionIdCache", new LRUCache$1({ max: 50 }));
@@ -149708,7 +149792,7 @@ function getSymbolDecorationPadding(document2, insertionLine, symbolRange) {
149708
149792
  return Math.max(symbolAnchorCharacter2 - insertionEndCharacter2, 2);
149709
149793
  }
149710
149794
  const tabSize = getEditorTabSize$1(document2.uri, workspace, window$1);
149711
- const tabAsSpace = UNICODE_SPACE$2.repeat(tabSize);
149795
+ const tabAsSpace = UNICODE_SPACE$3.repeat(tabSize);
149712
149796
  const insertionEndCharacter = insertionLine.text.slice(0, insertionLine.range.end.character).replaceAll(/\t/g, tabAsSpace).length;
149713
149797
  const symbolAnchorPosition = symbolRange.start.character > insertionEndCharacter ? symbolRange.start.character : symbolRange.end.character;
149714
149798
  const symbolAnchorCharacter = document2.lineAt(symbolRange.start.line).text.slice(0, symbolAnchorPosition).replaceAll(/\t/g, tabAsSpace).length;
@@ -149725,7 +149809,7 @@ async function getGhostHintEnablement() {
149725
149809
  };
149726
149810
  }
149727
149811
  const GHOST_TEXT_COLOR$1 = new ThemeColor("editorGhostText.foreground");
149728
- const UNICODE_SPACE$2 = " ";
149812
+ const UNICODE_SPACE$3 = " ";
149729
149813
  const HINT_DECORATIONS = {
149730
149814
  EditOrChat: {
149731
149815
  text: `${EDIT_SHORTCUT_LABEL} to Edit, ${CHAT_SHORTCUT_LABEL} to Chat`,
@@ -149893,7 +149977,7 @@ class GhostHintDecorator {
149893
149977
  }
149894
149978
  this.fireThrottledDisplayEvent(variant);
149895
149979
  const decorationHint = HINT_DECORATIONS[variant];
149896
- const decorationText = UNICODE_SPACE$2.repeat(textPadding) + decorationHint.text;
149980
+ const decorationText = UNICODE_SPACE$3.repeat(textPadding) + decorationHint.text;
149897
149981
  this.activeDecorationRange = new Range(position, position);
149898
149982
  editor.setDecorations(HINT_DECORATIONS[variant].decoration, [
149899
149983
  {
@@ -155817,9 +155901,14 @@ var canvaskit = { exports: {} };
155817
155901
  })(canvaskit);
155818
155902
  var canvaskitExports = canvaskit.exports;
155819
155903
  const CanvasKitInit = /* @__PURE__ */ getDefaultExportFromCjs(canvaskitExports);
155820
- let canvasKit = null;
155821
155904
  let canvasKitInitPromise = null;
155905
+ let canvasKit = null;
155822
155906
  let fontCache = null;
155907
+ async function initFont() {
155908
+ const fontPath = path.join("/tmp/__dirname", "DejaVuSansMono.ttf");
155909
+ const buffer2 = await fs.readFile(fontPath);
155910
+ return new Uint8Array(buffer2).buffer;
155911
+ }
155823
155912
  async function initCanvas() {
155824
155913
  if (!fontCache) {
155825
155914
  fontCache = await initFont();
@@ -155831,13 +155920,73 @@ async function initCanvas() {
155831
155920
  }
155832
155921
  await canvasKitInitPromise;
155833
155922
  }
155834
- async function initFont() {
155835
- const fontPath = path.join("/tmp/__dirname", "DejaVuSansMono.ttf");
155836
- const buffer2 = await fs.readFile(fontPath);
155837
- return new Uint8Array(buffer2).buffer;
155923
+ const DEFAULT_HIGHLIGHT_COLORS = {
155924
+ dark: "#ffffff",
155925
+ light: "#000000"
155926
+ };
155927
+ const GOLDEN_LINE_HEIGHT_RATIO = isMacOS() ? 1.5 : 1.35;
155928
+ const DEFAULT_FONT_SIZE = isMacOS() ? 12 : 14;
155929
+ const DEFAULT_PIXEL_RATIO = 1.95;
155930
+ function getUserLineHeight(fontSize) {
155931
+ return Math.round(GOLDEN_LINE_HEIGHT_RATIO * fontSize);
155932
+ }
155933
+ function getUserFontSize() {
155934
+ const userFontSize = Number(workspace.getConfiguration("editor").get("fontSize"));
155935
+ if (Number.isNaN(userFontSize) || userFontSize <= 0) {
155936
+ return;
155937
+ }
155938
+ return userFontSize;
155939
+ }
155940
+ function getUserPixelRatio() {
155941
+ const devicePixelRatio = localStorage.getDevicePixelRatio();
155942
+ if (!devicePixelRatio) {
155943
+ return;
155944
+ }
155945
+ return Math.max(devicePixelRatio, 1);
155946
+ }
155947
+ const DEFAULT_DIFF_COLORS = {
155948
+ inserted: {
155949
+ line: "rgba(155, 185, 85, 0.1)",
155950
+ text: "rgba(155, 185, 85, 0.15)"
155951
+ },
155952
+ removed: {
155953
+ line: "rgba(255, 0, 0, 0.1)",
155954
+ text: "rgba(255, 0, 0, 0.15)"
155955
+ }
155956
+ };
155957
+ function getRenderConfig(userProvidedConfig) {
155958
+ const pixelRatio = (userProvidedConfig == null ? void 0 : userProvidedConfig.pixelRatio) || getUserPixelRatio() || DEFAULT_PIXEL_RATIO;
155959
+ const fontSize = (userProvidedConfig == null ? void 0 : userProvidedConfig.fontSize) || getUserFontSize() || DEFAULT_FONT_SIZE;
155960
+ const lineHeight = (userProvidedConfig == null ? void 0 : userProvidedConfig.lineHeight) || getUserLineHeight(fontSize);
155961
+ return {
155962
+ fontSize,
155963
+ lineHeight,
155964
+ padding: { x: 6, y: 2 },
155965
+ maxWidth: 1200,
155966
+ pixelRatio,
155967
+ diffColors: DEFAULT_DIFF_COLORS,
155968
+ backgroundColor: userProvidedConfig == null ? void 0 : userProvidedConfig.backgroundColor
155969
+ };
155970
+ }
155971
+ function getRangesToHighlight(line) {
155972
+ switch (line.type) {
155973
+ case "removed":
155974
+ return [[0, line.text.length]];
155975
+ case "added":
155976
+ return [[0, line.text.length]];
155977
+ case "modified-removed":
155978
+ return line.changes.filter((change) => change.type === "delete").map(({ originalRange }) => [originalRange.start.character, originalRange.end.character]);
155979
+ case "modified-added":
155980
+ return line.changes.filter((change) => change.type === "insert").map((change) => [
155981
+ change.modifiedRange.start.character,
155982
+ change.modifiedRange.end.character
155983
+ ]);
155984
+ default:
155985
+ return [];
155986
+ }
155838
155987
  }
155839
155988
  function createCanvas(options, context2) {
155840
- const { width, height, fontSize, scale } = options;
155989
+ const { width, height, fontSize, scale, backgroundColor } = options;
155841
155990
  const canvas = context2.CanvasKit.MakeCanvas(width, height);
155842
155991
  canvas.loadFont(context2.font, { family: "DejaVuSansMono" });
155843
155992
  const ctx = canvas.getContext("2d");
@@ -155848,48 +155997,50 @@ function createCanvas(options, context2) {
155848
155997
  if (scale) {
155849
155998
  ctx.scale(scale, scale);
155850
155999
  }
156000
+ if (backgroundColor) {
156001
+ ctx.fillStyle = backgroundColor;
156002
+ ctx.fillRect(0, 0, width, height);
156003
+ }
155851
156004
  return { canvas, ctx };
155852
156005
  }
155853
156006
  function drawText(ctx, line, position, mode, config) {
155854
- const syntaxRanges = line.highlightedRanges.filter(
155855
- (range) => range.type === "syntax-highlighted"
155856
- );
155857
- if (syntaxRanges.length === 0) {
155858
- ctx.fillStyle = mode === "dark" ? "#ffffff" : "#000000";
155859
- ctx.fillText(line.lineText, position.x, position.y + config.fontSize);
155860
- return ctx.measureText(line.lineText).width;
156007
+ const highlights = line.syntaxHighlights[mode];
156008
+ if (highlights.length === 0) {
156009
+ ctx.fillStyle = DEFAULT_HIGHLIGHT_COLORS[mode];
156010
+ ctx.fillText(line.text, position.x, position.y + config.fontSize);
156011
+ return ctx.measureText(line.text).width;
155861
156012
  }
155862
156013
  let xPos = position.x;
155863
- for (const token of syntaxRanges) {
155864
- const content = line.lineText.substring(token.range[0], token.range[1]);
155865
- ctx.fillStyle = token.color;
156014
+ for (const { range, color } of highlights) {
156015
+ const [start2, end] = range;
156016
+ const content = line.text.substring(start2, end);
156017
+ ctx.fillStyle = color;
155866
156018
  ctx.fillText(content, xPos, position.y + config.fontSize);
155867
156019
  xPos += ctx.measureText(content).width;
155868
156020
  }
155869
156021
  return xPos;
155870
156022
  }
155871
- function drawDiffColors(ctx, line, position, config) {
155872
- const addedRanges = line.highlightedRanges.filter(
155873
- (range) => range.type === "diff-added"
155874
- );
155875
- if (addedRanges.length === 0) {
156023
+ function drawDiffColors(ctx, line, position, mode, config) {
156024
+ const isRemoval = line.type === "removed" || line.type === "modified-removed";
156025
+ const diffColors = isRemoval ? config.diffColors.removed : config.diffColors.inserted;
156026
+ if (mode === "unified" && line.type !== "unchanged") {
156027
+ const endOfLine = ctx.measureText(line.text).width;
156028
+ ctx.fillStyle = diffColors.line;
156029
+ ctx.fillRect(position.x, position.y, endOfLine, config.lineHeight);
156030
+ }
156031
+ const ranges2 = getRangesToHighlight(line);
156032
+ if (ranges2.length === 0) {
155876
156033
  return;
155877
156034
  }
155878
- ctx.fillStyle = config.diffHighlightColor;
155879
- for (const range of addedRanges) {
155880
- const preHighlightWidth = ctx.measureText(line.lineText.slice(0, range.range[0])).width;
155881
- const highlightWidth = ctx.measureText(line.lineText.slice(range.range[0], range.range[1])).width;
156035
+ ctx.fillStyle = diffColors.text;
156036
+ for (const [start2, end] of ranges2) {
156037
+ const preHighlightWidth = ctx.measureText(line.text.slice(0, start2)).width;
156038
+ const highlightWidth = ctx.measureText(line.text.slice(start2, end)).width;
155882
156039
  ctx.fillRect(position.x + preHighlightWidth, position.y, highlightWidth, config.lineHeight);
155883
156040
  }
155884
156041
  }
155885
- function drawDecorationsToCanvas(decorations2, mode, renderConfig = {
155886
- fontSize: 12,
155887
- lineHeight: 14,
155888
- padding: { x: 6, y: 2 },
155889
- maxWidth: 600,
155890
- pixelRatio: 2,
155891
- diffHighlightColor: "rgba(35, 134, 54, 0.2)"
155892
- }) {
156042
+ function drawDecorationsToCanvas(diff2, theme, mode, userConfig) {
156043
+ var _a3;
155893
156044
  if (!canvasKit || !fontCache) {
155894
156045
  throw new Error("Canvas not initialized");
155895
156046
  }
@@ -155897,33 +156048,37 @@ function drawDecorationsToCanvas(decorations2, mode, renderConfig = {
155897
156048
  CanvasKit: canvasKit,
155898
156049
  font: fontCache
155899
156050
  };
155900
- const { ctx: tempCtx } = createCanvas({ height: 10, width: 10, fontSize: 12 }, context2);
155901
- let tempYPos = renderConfig.padding.y;
156051
+ const config = getRenderConfig(userConfig);
156052
+ const { ctx: tempCtx } = createCanvas({ height: 10, width: 10, fontSize: config.fontSize }, context2);
156053
+ let tempYPos = config.padding.y;
155902
156054
  let requiredWidth = 0;
155903
- for (const { lineText } of decorations2) {
155904
- const measure = tempCtx.measureText(lineText);
155905
- requiredWidth = Math.max(requiredWidth, renderConfig.padding.x + measure.width);
155906
- tempYPos += renderConfig.lineHeight;
155907
- }
155908
- const canvasWidth = Math.min(requiredWidth + renderConfig.padding.x, renderConfig.maxWidth);
155909
- const canvasHeight = tempYPos + renderConfig.padding.y;
156055
+ for (const line of diff2.lines) {
156056
+ const measure = tempCtx.measureText(line.text);
156057
+ requiredWidth = Math.max(requiredWidth, config.padding.x + measure.width);
156058
+ tempYPos += config.lineHeight;
156059
+ }
156060
+ const canvasWidth = Math.min(requiredWidth + config.padding.x, config.maxWidth);
156061
+ const canvasHeight = tempYPos + config.padding.y;
156062
+ const height = Math.round(canvasHeight * config.pixelRatio);
156063
+ const width = Math.round(canvasWidth * config.pixelRatio);
155910
156064
  const { canvas, ctx } = createCanvas(
155911
156065
  {
155912
- height: canvasHeight * renderConfig.pixelRatio,
155913
- width: canvasWidth * renderConfig.pixelRatio,
155914
- fontSize: renderConfig.fontSize,
156066
+ height,
156067
+ width,
156068
+ fontSize: config.fontSize,
155915
156069
  // We upscale the canvas to improve resolution, this will be brought back to the intended size
155916
156070
  // using the `scale` CSS property when the decoration is rendered.
155917
- scale: renderConfig.pixelRatio
156071
+ scale: config.pixelRatio,
156072
+ backgroundColor: (_a3 = config.backgroundColor) == null ? void 0 : _a3[theme]
155918
156073
  },
155919
156074
  context2
155920
156075
  );
155921
- let yPos = renderConfig.padding.y;
155922
- for (const line of decorations2) {
155923
- const position = { x: renderConfig.padding.x, y: yPos };
155924
- drawDiffColors(ctx, line, position, renderConfig);
155925
- drawText(ctx, line, position, mode, renderConfig);
155926
- yPos += renderConfig.lineHeight;
156076
+ let yPos = config.padding.y;
156077
+ for (const line of diff2.lines) {
156078
+ const position = { x: config.padding.x, y: yPos };
156079
+ drawDiffColors(ctx, line, position, mode, config);
156080
+ drawText(ctx, line, position, theme, config);
156081
+ yPos += config.lineHeight;
155927
156082
  }
155928
156083
  return canvas;
155929
156084
  }
@@ -162190,56 +162345,100 @@ async function initSyntaxHighlighter() {
162190
162345
  syntaxHighlighter = await getShiki();
162191
162346
  }
162192
162347
  }
162193
- function syntaxHighlightDecorations(decorations2, lang, mode) {
162348
+ function getLines(diff2, type) {
162349
+ if (type === "original") {
162350
+ return diff2.lines.filter(
162351
+ (line) => ["removed", "modified-removed", "unchanged"].includes(line.type)
162352
+ );
162353
+ }
162354
+ return diff2.lines.filter(
162355
+ (line) => ["added", "modified-added", "unchanged"].includes(line.type)
162356
+ );
162357
+ }
162358
+ function getCodeBlock(diff2, type) {
162359
+ if (type === "original") {
162360
+ const relevantLines2 = getLines(diff2, "original");
162361
+ if (relevantLines2.length === 0) {
162362
+ return null;
162363
+ }
162364
+ const code22 = relevantLines2.map((line) => line.text).join("\n");
162365
+ return { code: code22, startLine: relevantLines2[0].originalLineNumber };
162366
+ }
162367
+ const relevantLines = getLines(diff2, "incoming");
162368
+ if (relevantLines.length === 0) {
162369
+ return null;
162370
+ }
162371
+ const code18 = relevantLines.map((line) => line.text).join("\n");
162372
+ return { code: code18, startLine: relevantLines[0].modifiedLineNumber };
162373
+ }
162374
+ function getHighlightTokens({
162375
+ diff: diff2,
162376
+ lang,
162377
+ theme,
162378
+ type
162379
+ }) {
162194
162380
  var _a3;
162195
162381
  if (!syntaxHighlighter) {
162196
162382
  throw new Error("Syntax highlighter not initialized");
162197
162383
  }
162198
162384
  const highlightLang = (_a3 = SYNTAX_HIGHLIGHTING_LANGUAGES[lang]) == null ? void 0 : _a3.name;
162199
162385
  if (!highlightLang) {
162200
- return decorations2;
162386
+ return /* @__PURE__ */ new Map();
162387
+ }
162388
+ const codeBlock = getCodeBlock(diff2, type);
162389
+ if (!codeBlock) {
162390
+ return /* @__PURE__ */ new Map();
162201
162391
  }
162202
- const code18 = decorations2.map(({ lineText }) => lineText).join("\n");
162203
- const { tokens } = syntaxHighlighter.codeToTokens(code18, {
162204
- theme: SYNTAX_HIGHLIGHTING_THEMES[mode].name,
162392
+ const { tokens } = syntaxHighlighter.codeToTokens(codeBlock.code, {
162393
+ theme: SYNTAX_HIGHLIGHTING_THEMES[theme].name,
162205
162394
  lang: highlightLang
162206
162395
  });
162207
- const defaultColour = mode === "dark" ? "#ffffff" : "#000000";
162208
- return decorations2.map((decoration, lineIndex) => {
162209
- const lineTokens = tokens[lineIndex] || [];
162210
- const newHighlightedRanges = [
162211
- ...decoration.highlightedRanges
162212
- ];
162213
- let currentPosition = 0;
162214
- for (const token of lineTokens) {
162215
- const tokenLength = token.content.length;
162216
- const startPos = currentPosition;
162217
- const endPos = currentPosition + tokenLength;
162218
- newHighlightedRanges.push({
162219
- type: "syntax-highlighted",
162220
- range: [startPos, endPos],
162221
- color: token.color || defaultColour
162222
- });
162223
- currentPosition += tokenLength;
162224
- }
162225
- newHighlightedRanges.sort((a, b) => a.range[0] - b.range[0]);
162226
- return {
162227
- ...decoration,
162228
- highlightedRanges: newHighlightedRanges
162229
- };
162230
- });
162396
+ const result = /* @__PURE__ */ new Map();
162397
+ for (let i2 = 0; i2 < tokens.length; i2++) {
162398
+ const lineTokens = tokens[i2];
162399
+ result.set(i2 + codeBlock.startLine, lineTokens);
162400
+ }
162401
+ return result;
162231
162402
  }
162232
- async function initImageSuggestionService() {
162233
- return Promise.all([initSyntaxHighlighter(), initCanvas()]);
162403
+ function getHighlightsForLine(lineTokens, theme) {
162404
+ const syntaxHighlights = [];
162405
+ let currentPosition = 0;
162406
+ for (const token of lineTokens) {
162407
+ const tokenLength = token.content.length;
162408
+ const startPos = currentPosition;
162409
+ const endPos = currentPosition + tokenLength;
162410
+ syntaxHighlights.push({
162411
+ range: [startPos, endPos],
162412
+ color: token.color || DEFAULT_HIGHLIGHT_COLORS[theme]
162413
+ });
162414
+ currentPosition += tokenLength;
162415
+ }
162416
+ return syntaxHighlights;
162234
162417
  }
162235
- function generateSuggestionAsImage(options) {
162236
- const { decorations: decorations2, lang } = options;
162237
- const darkDecorations = syntaxHighlightDecorations(decorations2, lang, "dark");
162238
- const lightDecorations = syntaxHighlightDecorations(decorations2, lang, "light");
162239
- return {
162240
- dark: drawDecorationsToCanvas(darkDecorations, "dark").toDataURL("image/png"),
162241
- light: drawDecorationsToCanvas(lightDecorations, "light").toDataURL("image/png")
162242
- };
162418
+ function syntaxHighlightDecorations(diff2, lang, theme) {
162419
+ const incomingHighlights = getHighlightTokens({
162420
+ diff: diff2,
162421
+ lang,
162422
+ theme,
162423
+ type: "incoming"
162424
+ });
162425
+ let originalHighlights;
162426
+ if (diff2.mode === "unified") {
162427
+ originalHighlights = getHighlightTokens({
162428
+ diff: diff2,
162429
+ lang,
162430
+ theme,
162431
+ type: "original"
162432
+ });
162433
+ }
162434
+ const lines2 = diff2.lines.map((line) => {
162435
+ const lineTokens = line.type === "removed" || line.type === "modified-removed" ? originalHighlights == null ? void 0 : originalHighlights.get(line.originalLineNumber) : incomingHighlights.get(line.modifiedLineNumber);
162436
+ if (lineTokens) {
162437
+ line.syntaxHighlights[theme] = getHighlightsForLine(lineTokens, theme);
162438
+ }
162439
+ return line;
162440
+ });
162441
+ return { mode: diff2.mode, lines: lines2 };
162243
162442
  }
162244
162443
  const INDENT_REGEX = /^(?:( )+|\t+)/;
162245
162444
  const INDENT_TYPE_SPACE = "space";
@@ -162336,6 +162535,264 @@ function detectIndent(string2) {
162336
162535
  indent
162337
162536
  };
162338
162537
  }
162538
+ const UNICODE_SPACE$2 = " ";
162539
+ function blockify$1(diff2, document2) {
162540
+ const spaceAdjusted = convertToSpaceIndentation$1(document2, diff2);
162541
+ const leadingRemoved = removeLeadingWhitespaceBlock$1(spaceAdjusted);
162542
+ const paddingAdded = padTrailingWhitespaceBlock$1(leadingRemoved);
162543
+ return paddingAdded;
162544
+ }
162545
+ const transformToUnicodeSpace = (text2) => text2.replace(/^\s+/, (match2) => UNICODE_SPACE$2.repeat(match2.length));
162546
+ const transformTabsToSpaces = (text2, tabSize) => text2.replace(/^(\t+)/, (match2) => UNICODE_SPACE$2.repeat(match2.length * tabSize));
162547
+ const countLeadingTabs = (text2) => (text2.match(/\t/g) || []).length;
162548
+ function convertToSpaceIndentation$1(document2, diff2) {
162549
+ const codeBlock = getCodeBlock(diff2, "incoming");
162550
+ if (!codeBlock) {
162551
+ return diff2;
162552
+ }
162553
+ const incomingIndentation = detectIndent(codeBlock.code).type;
162554
+ if (incomingIndentation === "space") {
162555
+ const lines22 = diff2.lines.map((line) => {
162556
+ return {
162557
+ ...line,
162558
+ text: transformToUnicodeSpace(line.text)
162559
+ };
162560
+ });
162561
+ return { ...diff2, lines: lines22 };
162562
+ }
162563
+ const tabSize = getEditorTabSize$1(document2.uri, workspace, window$1);
162564
+ const lines2 = diff2.lines.map((line) => {
162565
+ const leadingTabs = countLeadingTabs(line.text);
162566
+ return {
162567
+ ...line,
162568
+ changes: "changes" in line ? shiftChanges(line.changes, leadingTabs * (tabSize - 1)) : [],
162569
+ highlights: shiftHighlights(line.syntaxHighlights, leadingTabs * (tabSize - 1)),
162570
+ text: transformTabsToSpaces(line.text, tabSize)
162571
+ };
162572
+ });
162573
+ return { ...diff2, lines: lines2 };
162574
+ }
162575
+ function removeLeadingWhitespaceBlock$1(diff2) {
162576
+ let leastCommonWhitespacePrefix = void 0;
162577
+ for (const line of diff2.lines) {
162578
+ if (line.type === "modified-removed" || line.type === "removed") {
162579
+ continue;
162580
+ }
162581
+ const leadingWhitespaceMatch = line.text.match(/^\s*/);
162582
+ if (leadingWhitespaceMatch === null) {
162583
+ leastCommonWhitespacePrefix = "";
162584
+ break;
162585
+ }
162586
+ const leadingWhitespace = leadingWhitespaceMatch[0];
162587
+ if (leastCommonWhitespacePrefix === void 0) {
162588
+ leastCommonWhitespacePrefix = leadingWhitespace;
162589
+ continue;
162590
+ }
162591
+ leastCommonWhitespacePrefix = getCommonPrefix$1(leastCommonWhitespacePrefix, leadingWhitespace);
162592
+ }
162593
+ if (!leastCommonWhitespacePrefix) {
162594
+ return diff2;
162595
+ }
162596
+ const lines2 = diff2.lines.map((line) => {
162597
+ return {
162598
+ ...line,
162599
+ changes: "changes" in line ? shiftChanges(line.changes, -leastCommonWhitespacePrefix.length) : [],
162600
+ highlights: shiftHighlights(line.syntaxHighlights, -leastCommonWhitespacePrefix.length),
162601
+ text: line.text.substring(leastCommonWhitespacePrefix.length)
162602
+ };
162603
+ });
162604
+ return { ...diff2, lines: lines2 };
162605
+ }
162606
+ function padTrailingWhitespaceBlock$1(diff2) {
162607
+ let maxLineWidth = 0;
162608
+ for (const line of diff2.lines) {
162609
+ maxLineWidth = Math.max(maxLineWidth, line.text.length);
162610
+ }
162611
+ const lines2 = diff2.lines.map((line) => {
162612
+ return {
162613
+ ...line,
162614
+ text: line.text.padEnd(maxLineWidth, UNICODE_SPACE$2)
162615
+ };
162616
+ });
162617
+ return { ...diff2, lines: lines2 };
162618
+ }
162619
+ function shiftHighlights(highlights, offset2) {
162620
+ return {
162621
+ light: highlights.light.map(({ range: [start2, end], ...rest }) => {
162622
+ return {
162623
+ ...rest,
162624
+ range: [start2 + offset2, end + offset2]
162625
+ };
162626
+ }),
162627
+ dark: highlights.dark.map(({ range: [start2, end], ...rest }) => {
162628
+ return {
162629
+ ...rest,
162630
+ range: [start2 + offset2, end + offset2]
162631
+ };
162632
+ })
162633
+ };
162634
+ }
162635
+ function shiftChanges(changes, offset2) {
162636
+ return changes.map((change) => {
162637
+ return {
162638
+ ...change,
162639
+ originalRange: new Range(
162640
+ change.originalRange.start.line,
162641
+ Math.max(0, change.originalRange.start.character + offset2),
162642
+ change.originalRange.end.line,
162643
+ Math.max(0, change.originalRange.end.character + offset2)
162644
+ ),
162645
+ modifiedRange: new Range(
162646
+ change.modifiedRange.start.line,
162647
+ Math.max(0, change.modifiedRange.start.character + offset2),
162648
+ change.modifiedRange.end.line,
162649
+ Math.max(0, change.modifiedRange.end.character + offset2)
162650
+ )
162651
+ };
162652
+ });
162653
+ }
162654
+ function getCommonPrefix$1(s1, s2) {
162655
+ const minLength = Math.min(s1.length, s2.length);
162656
+ let commonPrefix = "";
162657
+ for (let i2 = 0; i2 < minLength; i2++) {
162658
+ if (s1[i2] === s2[i2]) {
162659
+ commonPrefix += s1[i2];
162660
+ } else {
162661
+ break;
162662
+ }
162663
+ }
162664
+ return commonPrefix;
162665
+ }
162666
+ function makeDecoratedDiff(decorationInfo, lang, mode, document2) {
162667
+ const visualDiff = makeVisualDiff(decorationInfo, mode);
162668
+ const blockifiedDiff = blockify$1(visualDiff, document2);
162669
+ return {
162670
+ dark: syntaxHighlightDecorations(blockifiedDiff, lang, "dark"),
162671
+ light: syntaxHighlightDecorations(blockifiedDiff, lang, "light")
162672
+ };
162673
+ }
162674
+ function makeVisualDiff(decorationInfo, mode) {
162675
+ const sortedDiff = [
162676
+ ...decorationInfo.addedLines,
162677
+ ...decorationInfo.modifiedLines,
162678
+ ...decorationInfo.unchangedLines,
162679
+ ...decorationInfo.removedLines
162680
+ ].sort((a, b) => {
162681
+ const aLine = a.type === "removed" ? a.originalLineNumber : a.modifiedLineNumber;
162682
+ const bLine = b.type === "removed" ? b.originalLineNumber : b.modifiedLineNumber;
162683
+ return aLine - bLine;
162684
+ });
162685
+ const firstRelevantLine = sortedDiff.findIndex((line) => line.type !== "unchanged");
162686
+ const lastRelevantLine = sortedDiff.findLastIndex((line) => line.type !== "unchanged");
162687
+ const relevantDiff = sortedDiff.slice(firstRelevantLine, lastRelevantLine + 1);
162688
+ if (relevantDiff.length === 0 || relevantDiff.every((line) => line.type === "unchanged")) {
162689
+ return { mode, lines: [] };
162690
+ }
162691
+ if (mode === "additions") {
162692
+ const lines22 = relevantDiff.filter((line) => ["added", "modified", "unchanged"].includes(line.type)).map((line) => {
162693
+ if (line.type === "modified") {
162694
+ return {
162695
+ type: "modified-added",
162696
+ text: line.newText,
162697
+ changes: line.changes,
162698
+ originalLineNumber: line.originalLineNumber,
162699
+ modifiedLineNumber: line.modifiedLineNumber,
162700
+ syntaxHighlights: {
162701
+ dark: [],
162702
+ light: []
162703
+ }
162704
+ };
162705
+ }
162706
+ return {
162707
+ ...line,
162708
+ syntaxHighlights: {
162709
+ dark: [],
162710
+ light: []
162711
+ }
162712
+ };
162713
+ });
162714
+ return { mode, lines: lines22 };
162715
+ }
162716
+ const lines2 = [];
162717
+ const deletions = [];
162718
+ const additions = [];
162719
+ for (let i2 = 0; i2 < relevantDiff.length; i2++) {
162720
+ const line = relevantDiff[i2];
162721
+ if (line.type === "modified") {
162722
+ const additionsOnly = isOnlyAddingTextForModifiedLines([line]);
162723
+ if (!additionsOnly) {
162724
+ deletions.push({
162725
+ type: "modified-removed",
162726
+ text: line.oldText,
162727
+ changes: line.changes,
162728
+ originalLineNumber: line.originalLineNumber,
162729
+ modifiedLineNumber: line.modifiedLineNumber,
162730
+ syntaxHighlights: {
162731
+ dark: [],
162732
+ light: []
162733
+ }
162734
+ });
162735
+ }
162736
+ additions.push({
162737
+ type: "modified-added",
162738
+ text: line.newText,
162739
+ changes: line.changes,
162740
+ originalLineNumber: line.originalLineNumber,
162741
+ modifiedLineNumber: line.modifiedLineNumber,
162742
+ syntaxHighlights: {
162743
+ dark: [],
162744
+ light: []
162745
+ }
162746
+ });
162747
+ } else if (line.type === "removed") {
162748
+ deletions.push({
162749
+ ...line,
162750
+ syntaxHighlights: {
162751
+ dark: [],
162752
+ light: []
162753
+ }
162754
+ });
162755
+ } else if (line.type === "added") {
162756
+ additions.push({
162757
+ ...line,
162758
+ syntaxHighlights: {
162759
+ dark: [],
162760
+ light: []
162761
+ }
162762
+ });
162763
+ } else {
162764
+ if (deletions.length > 0 || additions.length > 0) {
162765
+ lines2.push(...deletions, ...additions);
162766
+ deletions.length = 0;
162767
+ additions.length = 0;
162768
+ }
162769
+ lines2.push({
162770
+ ...line,
162771
+ syntaxHighlights: {
162772
+ dark: [],
162773
+ light: []
162774
+ }
162775
+ });
162776
+ }
162777
+ }
162778
+ if (deletions.length > 0 || additions.length > 0) {
162779
+ lines2.push(...deletions, ...additions);
162780
+ }
162781
+ return { mode, lines: lines2 };
162782
+ }
162783
+ async function initImageSuggestionService() {
162784
+ return Promise.all([initSyntaxHighlighter(), initCanvas()]);
162785
+ }
162786
+ function generateSuggestionAsImage(options) {
162787
+ const { decorations: decorations2, lang, config, mode, document: document2 } = options;
162788
+ const diff2 = makeDecoratedDiff(decorations2, lang, mode, document2);
162789
+ const renderConfig = getRenderConfig(config);
162790
+ return {
162791
+ dark: drawDecorationsToCanvas(diff2.dark, "dark", mode, renderConfig).toDataURL("image/png"),
162792
+ light: drawDecorationsToCanvas(diff2.light, "light", mode, renderConfig).toDataURL("image/png"),
162793
+ pixelRatio: renderConfig.pixelRatio
162794
+ };
162795
+ }
162339
162796
  const UNICODE_SPACE$1 = " ";
162340
162797
  function blockify(document2, addedLines) {
162341
162798
  const spaceAdjusted = convertToSpaceIndentation(document2, addedLines);
@@ -162527,7 +162984,7 @@ class DefaultDecorator {
162527
162984
  }
162528
162985
  if (this.options.shouldRenderImage) {
162529
162986
  this.renderAddedLinesImageDecorations(
162530
- addedLinesInfo.addedLinesDecorationInfo,
162987
+ decorationInfo,
162531
162988
  addedLinesInfo.startLine,
162532
162989
  addedLinesInfo.replacerCol
162533
162990
  );
@@ -162679,11 +163136,13 @@ class DefaultDecorator {
162679
163136
  ]);
162680
163137
  this.editor.setDecorations(this.addedLinesDecorationType, replacerDecorations);
162681
163138
  }
162682
- renderAddedLinesImageDecorations(addedLinesInfo, startLine, replacerCol) {
162683
- const blockifiedAddedLines = blockify(this.editor.document, addedLinesInfo);
162684
- const { dark, light: light2 } = generateSuggestionAsImage({
162685
- decorations: blockifiedAddedLines,
162686
- lang: this.editor.document.languageId
163139
+ renderAddedLinesImageDecorations(decorationInfo, startLine, replacerCol) {
163140
+ const diffMode = "additions";
163141
+ const { dark, light: light2, pixelRatio } = generateSuggestionAsImage({
163142
+ decorations: decorationInfo,
163143
+ lang: this.editor.document.languageId,
163144
+ mode: diffMode,
163145
+ document: this.editor.document
162687
163146
  });
162688
163147
  const startLineEndColumn = this.getEndColumn(this.editor.document.lineAt(startLine));
162689
163148
  const decorationPadding = 4;
@@ -162693,8 +163152,8 @@ class DefaultDecorator {
162693
163152
  position: "absolute",
162694
163153
  // Make sure the decoration is rendered on top of other decorations
162695
163154
  "z-index": "9999",
162696
- // Scale to decoration to the correct size (upscaled to boost resolution)
162697
- scale: "0.5",
163155
+ // Scale the decoration to the correct size (upscaled to boost resolution)
163156
+ scale: String(1 / pixelRatio),
162698
163157
  "transform-origin": "0px 0px",
162699
163158
  height: "auto",
162700
163159
  // The decoration will be entirely taken up by the image.
@@ -162753,14 +163212,6 @@ class DefaultDecorator {
162753
163212
  }
162754
163213
  }
162755
163214
  }
162756
- function isOnlyAddingTextForModifiedLines(modifiedLines) {
162757
- for (const modifiedLine of modifiedLines) {
162758
- if (modifiedLine.changes.some((change) => change.type === "delete")) {
162759
- return false;
162760
- }
162761
- }
162762
- return true;
162763
- }
162764
163215
  class InlineDiffDecorator {
162765
163216
  constructor(editor) {
162766
163217
  __publicField2(this, "addedTextDecorationType", window$1.createTextEditorDecorationType({}));
@@ -163521,10 +163972,11 @@ function shrinkPredictionUntilSuffix({
163521
163972
  }
163522
163973
  return predictionLines.join(newLineChar) + newLineChar;
163523
163974
  }
163524
- const AUTOEDITS_CONTEXT_STRATEGY = "auto-edit";
163525
- const INLINE_COMPLETION_DEFAULT_DEBOUNCE_INTERVAL_MS = 150;
163526
- const ON_SELECTION_CHANGE_DEFAULT_DEBOUNCE_INTERVAL_MS = 150;
163975
+ const AUTOEDIT_CONTEXT_STRATEGY = "auto-edit";
163976
+ const AUTOEDIT_TOTAL_DEBOUNCE_INTERVAL = 75;
163977
+ const AUTOEDIT_CONTEXT_FETCHING_DEBOUNCE_INTERVAL = 25;
163527
163978
  const RESET_SUGGESTION_ON_CURSOR_CHANGE_AFTER_INTERVAL_MS = 60 * 1e3;
163979
+ const ON_SELECTION_CHANGE_DEFAULT_DEBOUNCE_INTERVAL_MS = 15;
163528
163980
  class AutoeditsProvider {
163529
163981
  constructor(chatClient, fixupController, statusBar, options) {
163530
163982
  __publicField2(this, "disposables", []);
@@ -163541,7 +163993,7 @@ class AutoeditsProvider {
163541
163993
  __publicField2(this, "promptStrategy", new ShortTermPromptStrategy());
163542
163994
  __publicField2(this, "filterPrediction", new FilterPredictionBasedOnRecentEdits());
163543
163995
  __publicField2(this, "contextMixer", new ContextMixer({
163544
- strategyFactory: new DefaultContextStrategyFactory(Observable.of(AUTOEDITS_CONTEXT_STRATEGY)),
163996
+ strategyFactory: new DefaultContextStrategyFactory(Observable.of(AUTOEDIT_CONTEXT_STRATEGY)),
163545
163997
  contextRankingStrategy: ContextRankingStrategy.TimeBased,
163546
163998
  dataCollectionEnabled: false
163547
163999
  }));
@@ -163594,17 +164046,18 @@ class AutoeditsProvider {
163594
164046
  async provideInlineCompletionItems(document2, position, inlineCompletionContext, token) {
163595
164047
  let stopLoading;
163596
164048
  try {
163597
- const start2 = getTimeNowInMillis();
164049
+ const startedAt = getTimeNowInMillis();
163598
164050
  const controller2 = new AbortController();
163599
164051
  const abortSignal = controller2.signal;
163600
164052
  token == null ? void 0 : token.onCancellationRequested(() => controller2.abort());
163601
164053
  await new Promise(
163602
- (resolve) => setTimeout(resolve, INLINE_COMPLETION_DEFAULT_DEBOUNCE_INTERVAL_MS)
164054
+ (resolve) => setTimeout(resolve, AUTOEDIT_CONTEXT_FETCHING_DEBOUNCE_INTERVAL)
163603
164055
  );
164056
+ const remainingDebounceInterval = AUTOEDIT_TOTAL_DEBOUNCE_INTERVAL - AUTOEDIT_CONTEXT_FETCHING_DEBOUNCE_INTERVAL;
163604
164057
  if (abortSignal.aborted) {
163605
164058
  autoeditsOutputChannelLogger.logDebugIfVerbose(
163606
164059
  "provideInlineCompletionItems",
163607
- "debounce aborted before calculating getCurrentDocContext"
164060
+ "debounce aborted AUTOEDIT_CONTEXT_FETCHING_DEBOUNCE_INTERVAL"
163608
164061
  );
163609
164062
  return null;
163610
164063
  }
@@ -163628,13 +164081,9 @@ class AutoeditsProvider {
163628
164081
  position,
163629
164082
  tokenBudget: autoeditsProviderConfig.tokenLimit
163630
164083
  });
163631
- autoeditsOutputChannelLogger.logDebugIfVerbose(
163632
- "provideInlineCompletionItems",
163633
- "Calculating context from contextMixer..."
163634
- );
163635
164084
  const { codeToRewrite } = codeToReplaceData;
163636
164085
  const requestId = autoeditAnalyticsLogger.createRequest({
163637
- startedAt: performance.now(),
164086
+ startedAt,
163638
164087
  codeToReplaceData,
163639
164088
  position,
163640
164089
  docContext,
@@ -163646,25 +164095,30 @@ class AutoeditsProvider {
163646
164095
  triggerKind: autoeditTriggerKind.automatic
163647
164096
  }
163648
164097
  });
163649
- const { context: context2, contextSummary } = await this.contextMixer.getContext({
163650
- document: document2,
163651
- position,
163652
- docContext,
163653
- maxChars: 32e3
163654
- });
163655
- autoeditAnalyticsLogger.markAsContextLoaded({
163656
- requestId,
163657
- payload: {
163658
- contextSummary
163659
- }
163660
- });
164098
+ autoeditsOutputChannelLogger.logDebugIfVerbose(
164099
+ "provideInlineCompletionItems",
164100
+ "Calculating context from contextMixer..."
164101
+ );
164102
+ const [{ context: context2, contextSummary }] = await Promise.all([
164103
+ this.contextMixer.getContext({
164104
+ document: document2,
164105
+ position,
164106
+ docContext,
164107
+ maxChars: 32e3
164108
+ }),
164109
+ new Promise((resolve) => setTimeout(resolve, remainingDebounceInterval))
164110
+ ]);
163661
164111
  if (abortSignal.aborted) {
163662
164112
  autoeditsOutputChannelLogger.logDebugIfVerbose(
163663
164113
  "provideInlineCompletionItems",
163664
- "aborted in getContext"
164114
+ "aborted during context fetch debounce"
163665
164115
  );
163666
164116
  return null;
163667
164117
  }
164118
+ autoeditAnalyticsLogger.markAsContextLoaded({
164119
+ requestId,
164120
+ payload: { contextSummary }
164121
+ });
163668
164122
  autoeditsOutputChannelLogger.logDebugIfVerbose(
163669
164123
  "provideInlineCompletionItems",
163670
164124
  "Calculating prompt from promptStrategy..."
@@ -163722,7 +164176,7 @@ class AutoeditsProvider {
163722
164176
  "provideInlineCompletionItems",
163723
164177
  `"${requestId}" ============= Response:
163724
164178
  ${initialPrediction}
163725
- ============= Time Taken: ${getTimeNowInMillis() - start2}ms`
164179
+ ============= Time Taken: ${getTimeNowInMillis() - startedAt}ms`
163726
164180
  );
163727
164181
  const prediction = shrinkPredictionUntilSuffix({
163728
164182
  prediction: initialPrediction,
@@ -164002,13 +164456,10 @@ async function getContextFileFromUri(file, range) {
164002
164456
  }
164003
164457
  const doc2 = await workspace.openTextDocument(file);
164004
164458
  range = (range == null ? void 0 : range.isEmpty) ? void 0 : range;
164005
- const fullRange = new Range(
164006
- 0,
164007
- 0,
164008
- doc2.lineCount,
164009
- doc2.lineAt(doc2.lineCount - 1).text.length
164459
+ const fullRange = doc2.validateRange(
164460
+ new Range(doc2.positionAt(0), doc2.positionAt(doc2.getText().length - 1))
164010
164461
  );
164011
- if (range == null ? void 0 : range.contains(fullRange)) {
164462
+ if (range == null ? void 0 : range.isEqual(fullRange)) {
164012
164463
  range = void 0;
164013
164464
  }
164014
164465
  const content = doc2.getText(range);
@@ -166047,6 +166498,7 @@ function getChatPanelTitle(lastHumanText, truncateTitle = true) {
166047
166498
  }
166048
166499
  return text2.length > 25 ? `${text2.slice(0, 25).trim()}...` : text2;
166049
166500
  }
166501
+ const isAgentTesting = false === "true";
166050
166502
  const _ChatBuilder = class _ChatBuilder {
166051
166503
  constructor(selectedModel, sessionID = new Date(Date.now()).toUTCString(), messages = [], customChatTitle) {
166052
166504
  __publicField2(this, "changeNotifications", new MulticastSubject());
@@ -166254,6 +166706,13 @@ const _ChatBuilder = class _ChatBuilder {
166254
166706
  const lastHumanMessage = this.getLastHumanMessage();
166255
166707
  return getChatPanelTitle(((_a3 = lastHumanMessage == null ? void 0 : lastHumanMessage.text) == null ? void 0 : _a3.toString()) ?? "");
166256
166708
  }
166709
+ setChatTitle(title) {
166710
+ const firstHumanMessage = this.messages[0];
166711
+ if ((firstHumanMessage == null ? void 0 : firstHumanMessage.speaker) === "human" && this.messages.length === 1) {
166712
+ this.customChatTitle = title;
166713
+ this.changeNotifications.next();
166714
+ }
166715
+ }
166257
166716
  /**
166258
166717
  * Serializes to the transcript JSON format.
166259
166718
  */
@@ -166271,7 +166730,7 @@ const _ChatBuilder = class _ChatBuilder {
166271
166730
  }
166272
166731
  const result = {
166273
166732
  id: this.sessionID,
166274
- chatTitle: void 0,
166733
+ chatTitle: this.customChatTitle ?? void 0,
166275
166734
  lastInteractionTimestamp: this.sessionID,
166276
166735
  interactions
166277
166736
  };
@@ -167502,7 +167961,6 @@ function getCurrentFileOrSelection({
167502
167961
  const items = [];
167503
167962
  const contextFile = selectionOrFileContext2[0];
167504
167963
  if (contextFile) {
167505
- const range = contextFile.range ? expandToLineRange(contextFile.range) : void 0;
167506
167964
  items.push({
167507
167965
  ...contextFile,
167508
167966
  type: "file",
@@ -167513,17 +167971,20 @@ function getCurrentFileOrSelection({
167513
167971
  source: ContextItemSource.Initial,
167514
167972
  icon: "file"
167515
167973
  });
167974
+ const range = contextFile.range ? expandToLineRange(contextFile.range) : void 0;
167516
167975
  if (range) {
167517
167976
  items.push({
167518
167977
  ...contextFile,
167519
- type: "file",
167978
+ type: "current-selection",
167520
167979
  title: "Current Selection",
167521
167980
  description: `${displayPathBasename(contextFile.uri)}:${displayLineRange(
167522
167981
  range
167523
167982
  )}`,
167524
167983
  range,
167525
167984
  isTooLarge: userContextSize !== void 0 && contextFile.size !== void 0 && contextFile.size > userContextSize,
167526
- source: ContextItemSource.Initial,
167985
+ // NOTE: Do not set source to initial, this is used for
167986
+ // picking the correct prompt template for selection during prompt building.
167987
+ source: ContextItemSource.Selection,
167527
167988
  icon: "list-selection"
167528
167989
  });
167529
167990
  }
@@ -167835,6 +168296,13 @@ class PromptBuilder {
167835
168296
  * A list of context items that are used to build context messages.
167836
168297
  */
167837
168298
  __publicField2(this, "contextItems", []);
168299
+ __publicField2(this, "hasCacheFeatureFlag", storeLastValue(
168300
+ featureFlagProvider.evaluatedFeatureFlag(FeatureFlag.CodyPromptCachingOnMessages)
168301
+ ));
168302
+ __publicField2(this, "_isCacheEnabled", {
168303
+ featureFlag: false,
168304
+ isEnrolled: false
168305
+ });
167838
168306
  this.tokenCounter = tokenCounter;
167839
168307
  }
167840
168308
  /**
@@ -167843,13 +168311,49 @@ class PromptBuilder {
167843
168311
  static async create(contextWindow) {
167844
168312
  return new PromptBuilder(await TokenCounter.create(contextWindow));
167845
168313
  }
168314
+ get isCacheEnabled() {
168315
+ var _a3, _b2;
168316
+ const isFlagEnabled = Boolean(((_b2 = (_a3 = this.hasCacheFeatureFlag) == null ? void 0 : _a3.value) == null ? void 0 : _b2.last) ?? false);
168317
+ if (!this._isCacheEnabled.isEnrolled) {
168318
+ this._isCacheEnabled.isEnrolled = logFirstEnrollmentEvent(
168319
+ FeatureFlag.CodyPromptCachingOnMessages,
168320
+ isFlagEnabled
168321
+ );
168322
+ }
168323
+ return isFlagEnabled;
168324
+ }
167846
168325
  build() {
167847
168326
  if (this.contextItems.length > 0) {
167848
168327
  this.buildContextMessages();
167849
168328
  }
167850
168329
  return this.prefixMessages.concat([...this.reverseMessages].reverse());
167851
168330
  }
168331
+ /**
168332
+ * Create context messages for each context item, where
168333
+ * assistant messages come first because the transcript is in reversed order.
168334
+ */
167852
168335
  buildContextMessages() {
168336
+ if (this.isCacheEnabled) {
168337
+ const messages = [];
168338
+ for (const item of this.contextItems) {
168339
+ const contextMessage = renderContextItem(item);
168340
+ if (contextMessage) {
168341
+ messages.push(contextMessage);
168342
+ }
168343
+ }
168344
+ const groupedText = PromptString.join(
168345
+ messages.map((m) => m.text),
168346
+ ps`\n\n`
168347
+ );
168348
+ const groupedContextMessage = {
168349
+ speaker: "human",
168350
+ text: groupedText,
168351
+ cacheEnabled: true
168352
+ };
168353
+ const messagePair = [ASSISTANT_MESSAGE, groupedContextMessage];
168354
+ messagePair && this.reverseMessages.push(...messagePair);
168355
+ return;
168356
+ }
167853
168357
  for (const item of this.contextItems) {
167854
168358
  const contextMessage = renderContextItem(item);
167855
168359
  const messagePair = contextMessage && [ASSISTANT_MESSAGE, contextMessage];
@@ -168990,6 +169494,7 @@ const _CodyToolProvider = class _CodyToolProvider {
168990
169494
  }
168991
169495
  static initialize(contextRetriever) {
168992
169496
  _CodyToolProvider.instance = new _CodyToolProvider(contextRetriever);
169497
+ _CodyToolProvider.setupOpenCtxProviderListener();
168993
169498
  }
168994
169499
  static getTools() {
168995
169500
  var _a3;
@@ -169086,7 +169591,7 @@ async function getContextFileFromTabs() {
169086
169591
  try {
169087
169592
  const tabGroups2 = window$1.tabGroups.all;
169088
169593
  const openTabs = tabGroups2.flatMap(
169089
- (group) => group.tabs.map((tab2) => tab2.input)
169594
+ (group) => group.tabs.map((tab2) => tab2.input).filter(Boolean)
169090
169595
  );
169091
169596
  return (await Promise.all(
169092
169597
  openTabs.map(async (tab2) => {
@@ -169952,8 +170457,9 @@ class ChatHandler {
169952
170457
  const { explicitMentions, implicitMentions } = getCategorizedMentions(corpusContext);
169953
170458
  const prompter2 = new DefaultPrompter(explicitMentions, implicitMentions, false);
169954
170459
  const versions = await currentSiteVersion();
169955
- if (versions instanceof Error) {
169956
- throw new Error("unable to determine site version");
170460
+ if (lodashExports.isError(versions)) {
170461
+ delegate.postError(versions, "transcript");
170462
+ return;
169957
170463
  }
169958
170464
  const { prompt } = await this.buildPrompt(prompter2, chatBuilder, signal2, versions.codyAPIVersion);
169959
170465
  recorder2.recordChatQuestionExecuted(corpusContext, { addMetadata: true, current: span2 });
@@ -170958,6 +171464,9 @@ class ChatController {
170958
171464
  __publicField2(this, "clientBroadcast", new MulticastSubject());
170959
171465
  __publicField2(this, "initDoer", new InitDoer());
170960
171466
  __publicField2(this, "submitOrEditOperation");
171467
+ __publicField2(this, "isAutoChatTitleEnabled", storeLastValue(
171468
+ featureFlagProvider.evaluatedFeatureFlag(FeatureFlag.ChatTitleAutoGeneration)
171469
+ ));
170961
171470
  // #endregion
170962
171471
  // =======================================================================
170963
171472
  // #region webview container management
@@ -171082,7 +171591,9 @@ class ChatController {
171082
171591
  await commands$1.executeCommand("cody.fixup.codelens.undo", message.id);
171083
171592
  break;
171084
171593
  case "openURI":
171085
- commands$1.executeCommand("vscode.open", message.uri);
171594
+ commands$1.executeCommand("vscode.open", message.uri, {
171595
+ selection: message.range
171596
+ });
171086
171597
  break;
171087
171598
  case "links": {
171088
171599
  void openExternalLinks(message.value);
@@ -171143,6 +171654,10 @@ class ChatController {
171143
171654
  );
171144
171655
  break;
171145
171656
  case "auth": {
171657
+ if (message.authKind === "refresh") {
171658
+ authProvider.refresh();
171659
+ break;
171660
+ }
171146
171661
  if (message.authKind === "simplified-onboarding") {
171147
171662
  const endpoint = DOTCOM_URL.href;
171148
171663
  let tokenReceiverUrl = void 0;
@@ -171248,6 +171763,10 @@ class ChatController {
171248
171763
  logger2(message.filterLabel, message.message);
171249
171764
  break;
171250
171765
  }
171766
+ case "devicePixelRatio": {
171767
+ localStorage.setDevicePixelRatio(message.devicePixelRatio);
171768
+ break;
171769
+ }
171251
171770
  }
171252
171771
  }
171253
171772
  isSmartApplyEnabled() {
@@ -171261,6 +171780,9 @@ class ChatController {
171261
171780
  async getConfigForWebview() {
171262
171781
  var _a3, _b2, _c2;
171263
171782
  const { configuration, auth } = await currentResolvedConfig();
171783
+ const experimentalPromptEditorEnabled = await firstValueFrom$1(
171784
+ featureFlagProvider.evaluatedFeatureFlag(FeatureFlag.CodyExperimentalPromptEditor)
171785
+ );
171264
171786
  const sidebarViewOnly = ((_b2 = (_a3 = this.extensionClient.capabilities) == null ? void 0 : _a3.webviewNativeConfig) == null ? void 0 : _b2.view) === "single";
171265
171787
  const isEditorViewType = ((_c2 = this.webviewPanelOrView) == null ? void 0 : _c2.viewType) === "cody.editorPanel";
171266
171788
  const webviewType = isEditorViewType && !sidebarViewOnly ? "editor" : "sidebar";
@@ -171276,7 +171798,8 @@ class ChatController {
171276
171798
  webviewType,
171277
171799
  multipleWebviewsEnabled: !sidebarViewOnly,
171278
171800
  internalDebugContext: configuration.internalDebugContext,
171279
- allowEndpointChange: configuration.overrideServerEndpoint === void 0
171801
+ allowEndpointChange: configuration.overrideServerEndpoint === void 0,
171802
+ experimentalPromptEditorEnabled
171280
171803
  };
171281
171804
  }
171282
171805
  // =======================================================================
@@ -171369,6 +171892,7 @@ class ChatController {
171369
171892
  intent: manuallySelectedIntent,
171370
171893
  agent: selectedAgent
171371
171894
  });
171895
+ this.setCustomChatTitle(requestID, inputText, signal2, model2);
171372
171896
  this.postViewTranscript({ speaker: "assistant" });
171373
171897
  await this.saveSession();
171374
171898
  signal2.throwIfAborted();
@@ -171724,8 +172248,8 @@ class ChatController {
171724
172248
  });
171725
172249
  }
171726
172250
  async handleGetUserEditorContext(uri) {
171727
- var _a3;
171728
- const selection = (_a3 = window$1.activeTextEditor) == null ? void 0 : _a3.selection;
172251
+ var _a3, _b2;
172252
+ const selection = (_b2 = (_a3 = getEditor()) == null ? void 0 : _a3.active) == null ? void 0 : _b2.selection;
171729
172253
  const contextItem = uri ? await getContextFileFromUri(uri, selection) : await getContextFileFromCursor();
171730
172254
  const { input, context: context2 } = await firstResultFromOperation(
171731
172255
  ChatBuilder.contextWindowForChat(this.chatBuilder)
@@ -171740,7 +172264,7 @@ class ChatController {
171740
172264
  // Remove content to avoid sending large data to the webview
171741
172265
  content: void 0,
171742
172266
  isTooLarge: contextItem.size ? contextItem.size > userContextSize : void 0,
171743
- source: ContextItemSource.User,
172267
+ source: ContextItemSource.Selection,
171744
172268
  range: contextItem.range
171745
172269
  }
171746
172270
  ] : []
@@ -171821,6 +172345,58 @@ class ChatController {
171821
172345
  this._webviewPanelOrView.title = this.chatBuilder.getChatTitle();
171822
172346
  }
171823
172347
  }
172348
+ /**
172349
+ * Sets the custom chat title based on the first message in the interaction.
172350
+ */
172351
+ async setCustomChatTitle(requestID, inputText, signal2, chatModel) {
172352
+ return tracer.startActiveSpan("chat.setCustomChatTitle", async (span2) => {
172353
+ var _a3;
172354
+ const speeds = modelsService.getModelsByTag(ModelTag.Speed);
172355
+ const model2 = ((_a3 = speeds.find((m) => m.id.includes("flash")) || (speeds == null ? void 0 : speeds[0])) == null ? void 0 : _a3.id) ?? chatModel;
172356
+ const messages = this.chatBuilder.getMessages();
172357
+ if (messages.length > 1 || !this.isAutoChatTitleEnabled || !model2 || isAgentTesting) {
172358
+ return;
172359
+ }
172360
+ const prompt = ps`${getDefaultSystemPrompt()} Your task is to generate a concise title (in about 10 words without quotation) for <codyUserInput>${inputText}</codyUserInput>.
172361
+ RULE: Your response should only contain the concise title and nothing else.`;
172362
+ let title = "";
172363
+ try {
172364
+ const stream = await this.chatClient.chat(
172365
+ [{ speaker: "human", text: prompt }],
172366
+ { model: model2, maxTokensToSample: 100 },
172367
+ signal2,
172368
+ requestID
172369
+ );
172370
+ for await (const message of stream) {
172371
+ if (message.type === "change") {
172372
+ title = message.text;
172373
+ } else if (message.type === "complete") {
172374
+ if (title) {
172375
+ this.chatBuilder.setChatTitle(title);
172376
+ await this.saveSession();
172377
+ }
172378
+ break;
172379
+ }
172380
+ }
172381
+ } catch (error) {
172382
+ logDebug("ChatController", "setCustomChatTitle", { verbose: error });
172383
+ }
172384
+ telemetryRecorder.recordEvent("cody.chat.customTitle", "generated", {
172385
+ privateMetadata: {
172386
+ requestID,
172387
+ model: model2,
172388
+ traceId: span2.spanContext().traceId
172389
+ },
172390
+ metadata: {
172391
+ length: title.length
172392
+ },
172393
+ billingMetadata: {
172394
+ product: "cody",
172395
+ category: "billable"
172396
+ }
172397
+ });
172398
+ });
172399
+ }
171824
172400
  /**
171825
172401
  * Display error message in webview as part of the chat transcript, or as a system banner alongside the chat.
171826
172402
  */
@@ -172306,33 +172882,7 @@ class ChatsController {
172306
172882
  return commands$1.executeCommand("cody.chat.newPanel", args2);
172307
172883
  }
172308
172884
  }),
172309
- commands$1.registerCommand(
172310
- "cody.chat.toggle",
172311
- async (ops) => {
172312
- var _a3;
172313
- const modality = getNewChatLocation();
172314
- if (ops.editorFocus) {
172315
- if (modality === "sidebar") {
172316
- await commands$1.executeCommand("cody.chat.focus");
172317
- } else {
172318
- const editorView = (_a3 = this.activeEditor) == null ? void 0 : _a3.webviewPanelOrView;
172319
- if (editorView) {
172320
- revealWebviewViewOrPanel(editorView);
172321
- } else {
172322
- commands$1.executeCommand("cody.chat.newEditorPanel");
172323
- }
172324
- }
172325
- } else {
172326
- if (modality === "sidebar") {
172327
- await commands$1.executeCommand(
172328
- "workbench.action.focusActiveEditorGroup"
172329
- );
172330
- } else {
172331
- await commands$1.executeCommand("workbench.action.navigateEditorGroups");
172332
- }
172333
- }
172334
- }
172335
- ),
172885
+ commands$1.registerCommand("cody.chat.toggle", async () => this.toggleChatPanel()),
172336
172886
  commands$1.registerCommand("cody.chat.history.export", () => this.exportHistory()),
172337
172887
  commands$1.registerCommand("cody.chat.history.clear", (arg) => this.clearHistory(arg)),
172338
172888
  commands$1.registerCommand("cody.chat.history.delete", (item) => this.clearHistory(item)),
@@ -172617,6 +173167,22 @@ class ChatsController {
172617
173167
  this.panel.clearAndRestartSession();
172618
173168
  }
172619
173169
  }
173170
+ async toggleChatPanel() {
173171
+ var _a3;
173172
+ if (this.activeEditor) {
173173
+ const isVisible = (_a3 = this.activeEditor.webviewPanelOrView) == null ? void 0 : _a3.visible;
173174
+ const sessionID = this.activeEditor.sessionID;
173175
+ if (isVisible && sessionID) {
173176
+ this.disposeChat(sessionID, true);
173177
+ } else {
173178
+ await this.getOrCreateEditorChatController(sessionID);
173179
+ }
173180
+ } else {
173181
+ await commands$1.executeCommand(
173182
+ this.panel.isVisible() ? "workbench.action.toggleSidebarVisibility" : "cody.chat.focus"
173183
+ );
173184
+ }
173185
+ }
172620
173186
  // Dispose all open chat panels
172621
173187
  disposeAllChats() {
172622
173188
  this.activeEditor = void 0;
@@ -173244,7 +173810,7 @@ class CodySourceControl {
173244
173810
  commands$1.registerCommand("cody.command.abort-commit", () => this.statusUpdate()),
173245
173811
  subscriptionDisposable(
173246
173812
  modelsService.getModels(ModelUsage.Chat).pipe(skipPendingOperation()).subscribe((models) => {
173247
- const preferredModel = models.find((p2) => p2.id.includes("claude-3-haiku"));
173813
+ const preferredModel = models.find((p2) => p2.id.includes("gemini-2.0-flash-lite"));
173248
173814
  this.model = preferredModel ?? models.at(0);
173249
173815
  })
173250
173816
  )
@@ -173618,8 +174184,8 @@ function parseMentionURI(uri) {
173618
174184
  }
173619
174185
  }
173620
174186
  async function execFileAsync(program2, args2, { cwd }) {
173621
- const { promisify } = await import("./util-Bt98Paeh.mjs").then((n) => n.u);
173622
- const { execFile } = await import("./vscode-shim-DuhCkl0x.mjs").then((n) => n.gT);
174187
+ const { promisify } = await import("./util-DVisVv7-.mjs").then((n) => n.u);
174188
+ const { execFile } = await import("./vscode-shim-BMQfq1RF.mjs").then((n) => n.h5);
173623
174189
  return promisify(execFile)(program2, args2, { cwd });
173624
174190
  }
173625
174191
  var __create = Object.create;
@@ -176048,7 +176614,6 @@ function observeOpenCtxController(context2, createOpenCtxController) {
176048
176614
  ),
176049
176615
  mergeConfiguration
176050
176616
  });
176051
- CodyToolProvider.setupOpenCtxProviderListener();
176052
176617
  return controller2;
176053
176618
  } catch (error) {
176054
176619
  logDebug("openctx", `Failed to load OpenCtx client: ${error}`);
@@ -176933,11 +177498,18 @@ const MARKDOWN_CODE_BLOCK_REGEX = new RegExp(
176933
177498
  );
176934
177499
  const LEADING_SPACES_AND_NEW_LINES = /^\s*\n/;
176935
177500
  const LEADING_SPACES = /^[ ]+/;
176936
- function responseTransformer(text2, task, isMessageInProgress) {
176937
- const strippedText = text2.replaceAll(PROMPT_TOPIC_REGEX, "").replaceAll(
177501
+ function stripText(text2, task) {
177502
+ const strippedText = text2.replaceAll(PROMPT_TOPIC_REGEX, "");
177503
+ if (task.document.languageId === "markdown") {
177504
+ return strippedText;
177505
+ }
177506
+ return strippedText.replaceAll(
176938
177507
  MARKDOWN_CODE_BLOCK_REGEX,
176939
177508
  (block) => block.replace(MARKDOWN_CODE_BLOCK_START, "").replace(MARKDOWN_CODE_BLOCK_END, "")
176940
177509
  );
177510
+ }
177511
+ function responseTransformer(text2, task, isMessageInProgress) {
177512
+ const strippedText = stripText(text2, task);
176941
177513
  const trimmedText = task.intent === "add" ? strippedText.replace(LEADING_SPACES, "") : strippedText.replace(LEADING_SPACES_AND_NEW_LINES, "");
176942
177514
  const decodedText = heExports.decode(trimmedText);
176943
177515
  if (!isMessageInProgress) {
@@ -177416,8 +177988,9 @@ class EditProvider {
177416
177988
  const model2 = this.config.task.model;
177417
177989
  const contextWindow = modelsService.getContextWindowByID(model2);
177418
177990
  const versions = await currentSiteVersion();
177419
- if (versions instanceof Error) {
177420
- throw new Error("unable to determine site version");
177991
+ if (lodashExports.isError(versions)) {
177992
+ this.handleError(versions);
177993
+ return;
177421
177994
  }
177422
177995
  const {
177423
177996
  messages,
@@ -177910,8 +178483,8 @@ class EditManager {
177910
178483
  editor.setDecorations(SMART_APPLY_FILE_DECORATION, [documentRange]);
177911
178484
  const replacementCode = PromptString.unsafe_fromLLMResponse(configuration.replacement);
177912
178485
  const versions = await currentSiteVersion();
177913
- if (versions instanceof Error) {
177914
- throw new Error("unable to determine site version");
178486
+ if (lodashExports.isError(versions)) {
178487
+ throw new Error("Unable to determine site version", versions);
177915
178488
  }
177916
178489
  const contextloggerRequestId = await this.smartApplyContextLogger.createSmartApplyLoggingRequest({
177917
178490
  model: model2,
@@ -178245,15 +178818,16 @@ class VSCodeEditor {
178245
178818
  return this.createActiveTextEditorSelection(activeEditor, selection);
178246
178819
  }
178247
178820
  async getTextEditorContentForFile(fileUri, selectionRange) {
178248
- var _a3, _b2;
178821
+ var _a3, _b2, _c2;
178249
178822
  let range;
178250
178823
  if (selectionRange) {
178251
178824
  const startLine = (_a3 = selectionRange == null ? void 0 : selectionRange.start) == null ? void 0 : _a3.line;
178252
178825
  let endLine = (_b2 = selectionRange == null ? void 0 : selectionRange.end) == null ? void 0 : _b2.line;
178826
+ const endChar = (_c2 = selectionRange == null ? void 0 : selectionRange.end) == null ? void 0 : _c2.character;
178253
178827
  if (startLine === endLine) {
178254
178828
  endLine++;
178255
178829
  }
178256
- range = new Range(startLine, 0, endLine, 0);
178830
+ range = new Range(startLine, 0, endLine, endChar);
178257
178831
  }
178258
178832
  const doc2 = await workspace.openTextDocument(fileUri);
178259
178833
  return doc2.getText(range);
@@ -182188,6 +182762,9 @@ const _CodyStatusBar = class _CodyStatusBar {
182188
182762
  _CodyStatusBar.singleton = new _CodyStatusBar();
182189
182763
  return _CodyStatusBar.singleton;
182190
182764
  }
182765
+ clearErrors() {
182766
+ this.errors.mutate((draft) => /* @__PURE__ */ new Set());
182767
+ }
182191
182768
  addError(args2) {
182192
182769
  const now = Date.now();
182193
182770
  const ttl = args2.timeout !== void 0 ? Math.min(ONE_HOUR, args2.timeout) : ONE_HOUR;
@@ -182309,7 +182886,6 @@ const _CodyStatusBar = class _CodyStatusBar {
182309
182886
  }
182310
182887
  }
182311
182888
  buildState(authStatus2, config, errors, loaders, ignoreStatus, autoeditsFeatureFlagEnabled, userProductSubscription2) {
182312
- var _a3, _b2;
182313
182889
  const tags = /* @__PURE__ */ new Set();
182314
182890
  if (authStatus2.authenticated) {
182315
182891
  tags.add(InvisibleStatusBarTag.IsAuthenticated);
@@ -182334,15 +182910,6 @@ const _CodyStatusBar = class _CodyStatusBar {
182334
182910
  interact: interactAuth
182335
182911
  };
182336
182912
  }
182337
- if (!authStatus2.authenticated && ((_a3 = authStatus2.error) == null ? void 0 : _a3.type) === "invalid-access-token") {
182338
- return {
182339
- icon: "disabled",
182340
- tooltip: "Your authentication has expired.\nSign in again to continue using Cody.",
182341
- style: "warning",
182342
- tags,
182343
- interact: interactAuth
182344
- };
182345
- }
182346
182913
  if (errors.size > 0) {
182347
182914
  const [firstError, ...otherErrors] = [...errors.values()];
182348
182915
  const hasDisabilitatingError = [...errors.values()].some(
@@ -182368,16 +182935,16 @@ const _CodyStatusBar = class _CodyStatusBar {
182368
182935
  })
182369
182936
  };
182370
182937
  }
182371
- if (!authStatus2.authenticated && ((_b2 = authStatus2.error) == null ? void 0 : _b2.type) === "network-error") {
182372
- return {
182373
- icon: "disabled",
182374
- tooltip: "Network issues prevented Cody from signing in.",
182375
- style: "error",
182376
- tags,
182377
- interact: interactNetworkIssues
182378
- };
182379
- }
182380
182938
  if (!authStatus2.authenticated) {
182939
+ if (isAvailabilityError(authStatus2.error)) {
182940
+ return {
182941
+ icon: "disabled",
182942
+ tooltip: authStatus2.error.message,
182943
+ style: authStatus2.error instanceof InvalidAccessTokenError ? "error" : "warning",
182944
+ tags,
182945
+ interact: isAvailabilityError(authStatus2.error) ? interactNetworkIssues : interactAuth
182946
+ };
182947
+ }
182381
182948
  return {
182382
182949
  text: "Sign In",
182383
182950
  tooltip: "Sign in to get started with Cody.",
@@ -182710,23 +183277,6 @@ async function getCurrentCodySuggestionMode(workspaceConfig) {
182710
183277
  function getCodySuggestionModeKey() {
182711
183278
  return "cody.suggestions.mode";
182712
183279
  }
182713
- function ignoreReason(isIgnore) {
182714
- switch (isIgnore) {
182715
- case false:
182716
- return null;
182717
- case "non-file-uri":
182718
- return "This current file is ignored as it does not have a valid file URI.";
182719
- case "no-repo-found":
182720
- return "This current file is ignored as it is not in known git repository.";
182721
- case "has-ignore-everything-filters":
182722
- return "Your administrator has disabled Cody for this file.";
182723
- default:
182724
- if (isIgnore.startsWith("repo:")) {
182725
- return `Your administrator has disabled Cody for '${isIgnore.replace("repo:", "")}'.`;
182726
- }
182727
- return "The current file is ignored by Cody.";
182728
- }
182729
- }
182730
183280
  function openCodyIssueReporter() {
182731
183281
  void commands$1.executeCommand("workbench.action.openIssueReporter", {
182732
183282
  extensionId: `${packageJson.publisher}.${packageJson.name}`,
@@ -183581,7 +184131,7 @@ async function registerOtherCommands(disposables) {
183581
184131
  modal: true,
183582
184132
  detail: `${userMessage}
183583
184133
 
183584
- Upgrade to Cody Pro for unlimited autocomplete suggestions, chat messages and commands.
184134
+ Upgrade to Cody Pro for unlimited autocomplete suggestions, and increased limits for chat messages and commands.
183585
184135
 
183586
184136
  ${retryMessage}`
183587
184137
  },
@@ -183780,7 +184330,11 @@ function registerAuthCommands(disposables) {
183780
184330
  commands$1.registerCommand("cody.auth.signin", () => showSignInMenu()),
183781
184331
  commands$1.registerCommand("cody.auth.signout", () => showSignOutMenu()),
183782
184332
  commands$1.registerCommand("cody.auth.account", () => showAccountMenu()),
183783
- commands$1.registerCommand("cody.auth.support", () => showFeedbackSupportQuickPick())
184333
+ commands$1.registerCommand("cody.auth.support", () => showFeedbackSupportQuickPick()),
184334
+ commands$1.registerCommand(
184335
+ "cody.auth.requestEndpointSettings",
184336
+ async () => await requestEndpointSettingsDeliveryToSearchPlugin()
184337
+ )
183784
184338
  );
183785
184339
  }
183786
184340
  function registerUpgradeHandlers(disposables) {
@@ -183854,7 +184408,7 @@ async function registerDebugCommands(context2, disposables) {
183854
184408
  }
183855
184409
  async function tryRegisterTutorial(context2, disposables) {
183856
184410
  if (!isRunningInsideAgent()) {
183857
- const { registerInteractiveTutorial } = await import("./index-CFWvzD4D.mjs");
184411
+ const { registerInteractiveTutorial } = await import("./index-CvHu3t7y.mjs");
183858
184412
  registerInteractiveTutorial(context2).then((disposable) => disposables.push(...disposable));
183859
184413
  }
183860
184414
  }