"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleExperimentationService = exports.LogLevel = exports.ILanguageContextProviderService = exports.IIgnoreService = exports.IExperimentationService = exports.IEndpointProvider = exports.ICAPIClientService = exports.IAuthenticationService = void 0;
exports.createNESProvider = createNESProvider;
exports.createInlineCompletionsProvider = createInlineCompletionsProvider;
const ghostTextContext_1 = require("./_internal/extension/completions-core/common/ghostTextContext");
const completionsTelemetryServiceBridge_1 = require("./_internal/extension/completions-core/vscode-node/bridge/src/completionsTelemetryServiceBridge");
const extensionStatus_1 = require("./_internal/extension/completions-core/vscode-node/extension/src/extensionStatus");
const copilotTokenManager_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/auth/copilotTokenManager");
const citationManager_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/citationManager");
const completionNotifier_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/completionNotifier");
const completionsObservableWorkspace_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/completionsObservableWorkspace");
const config_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/config");
const userErrorNotifier_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/error/userErrorNotifier");
const features_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/experiments/features");
const featuresService_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/experiments/featuresService");
const fileReader_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/fileReader");
const fileSystem_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/fileSystem");
const asyncCompletions_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/ghostText/asyncCompletions");
const completionsCache_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/ghostText/completionsCache");
const configBlockMode_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/ghostText/configBlockMode");
const current_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/ghostText/current");
const last_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/ghostText/last");
const speculativeRequestCache_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/ghostText/speculativeRequestCache");
const inlineCompletion_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/inlineCompletion");
const localFileSystem_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/localFileSystem");
const logger_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/logger");
const networking_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/networking");
const notificationSender_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/notificationSender");
const fetch_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/openai/fetch");
const model_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/openai/model");
const progress_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/progress");
const completionsPromptFactory_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/prompt/completionsPromptFactory/completionsPromptFactory");
const contextProviderBridge_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/prompt/components/contextProviderBridge");
const contextProviderRegistry_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/prompt/contextProviderRegistry");
const contextProviderStatistics_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/prompt/contextProviderStatistics");
const recentEditsProvider_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/prompt/recentEdits/recentEditsProvider");
const compositeRelatedFilesProvider_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/prompt/similarFiles/compositeRelatedFilesProvider");
const relatedFiles_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/prompt/similarFiles/relatedFiles");
const userConfig_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/telemetry/userConfig");
const textDocumentManager_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/textDocumentManager");
const promiseQueue_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/util/promiseQueue");
const runtimeMode_1 = require("./_internal/extension/completions-core/vscode-node/lib/src/util/runtimeMode");
const debugRecorder_1 = require("./_internal/extension/inlineEdits/node/debugRecorder");
const nextEditProvider_1 = require("./_internal/extension/inlineEdits/node/nextEditProvider");
const nextEditProviderTelemetry_1 = require("./_internal/extension/inlineEdits/node/nextEditProviderTelemetry");
const powerService_1 = require("./_internal/extension/power/common/powerService");
const chatMLFetcher_1 = require("./_internal/extension/prompt/node/chatMLFetcher");
const similarFilesContextService_1 = require("./_internal/extension/xtab/common/similarFilesContextService");
const xtabProvider_1 = require("./_internal/extension/xtab/node/xtabProvider");
const authentication_1 = require("./_internal/platform/authentication/common/authentication");
Object.defineProperty(exports, "IAuthenticationService", { enumerable: true, get: function () { return authentication_1.IAuthenticationService; } });
const copilotTokenManager_2 = require("./_internal/platform/authentication/common/copilotTokenManager");
const copilotTokenStore_1 = require("./_internal/platform/authentication/common/copilotTokenStore");
const staticGitHubAuthenticationService_1 = require("./_internal/platform/authentication/common/staticGitHubAuthenticationService");
const copilotTokenManager_3 = require("./_internal/platform/authentication/node/copilotTokenManager");
const chatMLFetcher_2 = require("./_internal/platform/chat/common/chatMLFetcher");
const chatQuotaService_1 = require("./_internal/platform/chat/common/chatQuotaService");
const chatQuotaServiceImpl_1 = require("./_internal/platform/chat/common/chatQuotaServiceImpl");
const conversationOptions_1 = require("./_internal/platform/chat/common/conversationOptions");
const interactionService_1 = require("./_internal/platform/chat/common/interactionService");
const configurationService_1 = require("./_internal/platform/configuration/common/configurationService");
const defaultsOnlyConfigurationService_1 = require("./_internal/platform/configuration/common/defaultsOnlyConfigurationService");
const diffService_1 = require("./_internal/platform/diff/common/diffService");
const diffServiceImpl_1 = require("./_internal/platform/diff/node/diffServiceImpl");
const capiClient_1 = require("./_internal/platform/endpoint/common/capiClient");
Object.defineProperty(exports, "ICAPIClientService", { enumerable: true, get: function () { return capiClient_1.ICAPIClientService; } });
const domainService_1 = require("./_internal/platform/endpoint/common/domainService");
const endpointProvider_1 = require("./_internal/platform/endpoint/common/endpointProvider");
Object.defineProperty(exports, "IEndpointProvider", { enumerable: true, get: function () { return endpointProvider_1.IEndpointProvider; } });
const capiClientImpl_1 = require("./_internal/platform/endpoint/node/capiClientImpl");
const domainServiceImpl_1 = require("./_internal/platform/endpoint/node/domainServiceImpl");
const envService_1 = require("./_internal/platform/env/common/envService");
const nullEnvService_1 = require("./_internal/platform/env/common/nullEnvService");
const gitExtensionService_1 = require("./_internal/platform/git/common/gitExtensionService");
const nullGitExtensionService_1 = require("./_internal/platform/git/common/nullGitExtensionService");
const ignoreService_1 = require("./_internal/platform/ignore/common/ignoreService");
Object.defineProperty(exports, "IIgnoreService", { enumerable: true, get: function () { return ignoreService_1.IIgnoreService; } });
const documentId_1 = require("./_internal/platform/inlineEdits/common/dataTypes/documentId");
const inlineEditLogContext_1 = require("./_internal/platform/inlineEdits/common/inlineEditLogContext");
const inlineEditsModelService_1 = require("./_internal/platform/inlineEdits/common/inlineEditsModelService");
const observableGit_1 = require("./_internal/platform/inlineEdits/common/observableGit");
const nesHistoryContextProvider_1 = require("./_internal/platform/inlineEdits/common/workspaceEditTracker/nesHistoryContextProvider");
const nesXtabHistoryTracker_1 = require("./_internal/platform/inlineEdits/common/workspaceEditTracker/nesXtabHistoryTracker");
const inlineEditsModelService_2 = require("./_internal/platform/inlineEdits/node/inlineEditsModelService");
const languageContextProviderService_1 = require("./_internal/platform/languageContextProvider/common/languageContextProviderService");
Object.defineProperty(exports, "ILanguageContextProviderService", { enumerable: true, get: function () { return languageContextProviderService_1.ILanguageContextProviderService; } });
const nullLanguageContextProviderService_1 = require("./_internal/platform/languageContextProvider/common/nullLanguageContextProviderService");
const languageDiagnosticsService_1 = require("./_internal/platform/languages/common/languageDiagnosticsService");
const testLanguageDiagnosticsService_1 = require("./_internal/platform/languages/common/testLanguageDiagnosticsService");
const logService_1 = require("./_internal/platform/log/common/logService");
const completionsFetchService_1 = require("./_internal/platform/nesFetch/common/completionsFetchService");
const completionsFetchServiceImpl_1 = require("./_internal/platform/nesFetch/node/completionsFetchServiceImpl");
const fetcherService_1 = require("./_internal/platform/networking/common/fetcherService");
const chatWebSocketManager_1 = require("./_internal/platform/networking/node/chatWebSocketManager");
const noopOtelService_1 = require("./_internal/platform/otel/common/noopOtelService");
const otelConfig_1 = require("./_internal/platform/otel/common/otelConfig");
const otelService_1 = require("./_internal/platform/otel/common/otelService");
const proxyModelsService_1 = require("./_internal/platform/proxyModels/common/proxyModelsService");
const proxyModelsService_2 = require("./_internal/platform/proxyModels/node/proxyModelsService");
const requestLogger_1 = require("./_internal/platform/requestLogger/common/requestLogger");
const nullRequestLogger_1 = require("./_internal/platform/requestLogger/node/nullRequestLogger");
const simulationTestContext_1 = require("./_internal/platform/simulationTestContext/common/simulationTestContext");
const snippyService_1 = require("./_internal/platform/snippy/common/snippyService");
const nullExperimentationService_1 = require("./_internal/platform/telemetry/common/nullExperimentationService");
Object.defineProperty(exports, "IExperimentationService", { enumerable: true, get: function () { return nullExperimentationService_1.IExperimentationService; } });
const telemetry_1 = require("./_internal/platform/telemetry/common/telemetry");
const telemetryData_1 = require("./_internal/platform/telemetry/common/telemetryData");
const azureInsightsReporter_1 = require("./_internal/platform/telemetry/node/azureInsightsReporter");
const terminalService_1 = require("./_internal/platform/terminal/common/terminalService");
const tokenizer_1 = require("./_internal/platform/tokenizer/node/tokenizer");
const workspaceService_1 = require("./_internal/platform/workspace/common/workspaceService");
const services_1 = require("./_internal/util/common/services");
const cancellation_1 = require("./_internal/util/vs/base/common/cancellation");
const event_1 = require("./_internal/util/vs/base/common/event");
const lifecycle_1 = require("./_internal/util/vs/base/common/lifecycle");
const uuid_1 = require("./_internal/util/vs/base/common/uuid");
const descriptors_1 = require("./_internal/util/vs/platform/instantiation/common/descriptors");
const instantiation_1 = require("./_internal/util/vs/platform/instantiation/common/instantiation");
/**
 * Log levels (taken from vscode.d.ts)
 */
var LogLevel;
(function (LogLevel) {
    /**
     * No messages are logged with this level.
     */
    LogLevel[LogLevel["Off"] = 0] = "Off";
    /**
     * All messages are logged with this level.
     */
    LogLevel[LogLevel["Trace"] = 1] = "Trace";
    /**
     * Messages with debug and higher log level are logged with this level.
     */
    LogLevel[LogLevel["Debug"] = 2] = "Debug";
    /**
     * Messages with info and higher log level are logged with this level.
     */
    LogLevel[LogLevel["Info"] = 3] = "Info";
    /**
     * Messages with warning and higher log level are logged with this level.
     */
    LogLevel[LogLevel["Warning"] = 4] = "Warning";
    /**
     * Only error messages are logged with this level.
     */
    LogLevel[LogLevel["Error"] = 5] = "Error";
})(LogLevel || (exports.LogLevel = LogLevel = {}));
function createNESProvider(options) {
    const instantiationService = setupServices(options);
    return instantiationService.createInstance(NESProvider, options);
}
let NESProvider = class NESProvider extends lifecycle_1.Disposable {
    constructor(_options, instantiationService, _expService, _configurationService, _workspaceService) {
        super();
        this._options = _options;
        this._expService = _expService;
        this._configurationService = _configurationService;
        this._workspaceService = _workspaceService;
        const statelessNextEditProvider = instantiationService.createInstance(xtabProvider_1.XtabProvider);
        const git = instantiationService.createInstance(observableGit_1.ObservableGit);
        const historyContextProvider = new nesHistoryContextProvider_1.NesHistoryContextProvider(this._options.workspace, git);
        const xtabDiffNEntries = this._configurationService.getExperimentBasedConfig(configurationService_1.ConfigKey.TeamInternal.InlineEditsXtabDiffNEntries, this._expService);
        const xtabHistoryTracker = new nesXtabHistoryTracker_1.NesXtabHistoryTracker(this._options.workspace, xtabDiffNEntries, _configurationService, _expService);
        this._debugRecorder = this._register(new debugRecorder_1.DebugRecorder(this._options.workspace));
        this._nextEditProvider = instantiationService.createInstance(nextEditProvider_1.NextEditProvider, this._options.workspace, statelessNextEditProvider, historyContextProvider, xtabHistoryTracker, this._debugRecorder);
        this._telemetrySender = this._register(instantiationService.createInstance(nextEditProviderTelemetry_1.TelemetrySender, this._options.workspace));
    }
    getId() {
        return this._nextEditProvider.ID;
    }
    handleShown(result) {
        result.telemetryBuilder.setAsShown();
        this._nextEditProvider.handleShown(result.internalResult);
    }
    handleAcceptance(result) {
        result.telemetryBuilder.setAcceptance('accepted');
        result.telemetryBuilder.setStatus('accepted');
        this._nextEditProvider.handleAcceptance(result.docId, result.internalResult);
        this.handleEndOfLifetime(result);
    }
    handleRejection(result) {
        result.telemetryBuilder.setAcceptance('rejected');
        result.telemetryBuilder.setStatus('rejected');
        this._nextEditProvider.handleRejection(result.docId, result.internalResult);
        this.handleEndOfLifetime(result);
    }
    handleIgnored(result, supersededByRequestUuid) {
        if (supersededByRequestUuid) {
            result.telemetryBuilder.setSupersededBy(supersededByRequestUuid.requestUuid);
        }
        this._nextEditProvider.handleIgnored(result.docId, result.internalResult, supersededByRequestUuid?.internalResult);
        this.handleEndOfLifetime(result);
    }
    handleEndOfLifetime(result) {
        try {
            this._telemetrySender.sendTelemetryForBuilder(result.telemetryBuilder);
        }
        finally {
            result.telemetryBuilder.dispose();
        }
    }
    async getNextEdit(documentUri, cancellationToken) {
        const docId = documentId_1.DocumentId.create(documentUri.toString());
        // Create minimal required context objects
        const context = {
            triggerKind: 1, // Invoke
            selectedCompletionInfo: undefined,
            requestUuid: (0, uuid_1.generateUuid)(),
            requestIssuedDateTime: Date.now(),
            earliestShownDateTime: Date.now() + 200,
            enforceCacheDelay: true,
        };
        // Create log context
        const logContext = new inlineEditLogContext_1.InlineEditRequestLogContext(documentUri.toString(), 1, context);
        const document = this._options.workspace.getDocument(docId);
        if (!document) {
            throw new Error('DocumentNotFound');
        }
        // Create telemetry builder - we'll need to pass null/undefined for services we don't have
        const telemetryBuilder = new nextEditProviderTelemetry_1.NextEditProviderTelemetryBuilder(new nullGitExtensionService_1.NullGitExtensionService(), undefined, // INotebookService
        this._workspaceService, this._nextEditProvider.ID, document, this._debugRecorder, logContext.recordingBookmark);
        telemetryBuilder.setOpportunityId(context.requestUuid);
        try {
            const internalResult = await this._nextEditProvider.getNextEdit(docId, context, logContext, cancellationToken, telemetryBuilder.nesBuilder);
            const result = {
                result: internalResult.result?.edit ? {
                    newText: internalResult.result.edit.newText,
                    range: internalResult.result.edit.replaceRange,
                } : undefined,
                docId,
                requestUuid: context.requestUuid,
                internalResult,
                telemetryBuilder,
            };
            return result;
        }
        catch (e) {
            try {
                this._telemetrySender.sendTelemetryForBuilder(telemetryBuilder);
            }
            finally {
                telemetryBuilder.dispose();
            }
            throw e;
        }
    }
    updateTreatmentVariables(variables) {
        if (this._expService instanceof SimpleExperimentationService) {
            this._expService.updateTreatmentVariables(variables);
        }
    }
    async setConfigs(overrides) {
        for (const [key, value] of overrides) {
            const config = configurationService_1.globalConfigRegistry.configs.get(`${configurationService_1.CopilotConfigPrefix}.${key}`);
            if (config) {
                await this._configurationService.setConfig(config, value);
            }
        }
    }
};
NESProvider = __decorate([
    __param(1, instantiation_1.IInstantiationService),
    __param(2, nullExperimentationService_1.IExperimentationService),
    __param(3, configurationService_1.IConfigurationService),
    __param(4, workspaceService_1.IWorkspaceService)
], NESProvider);
function setupServices(options) {
    const { fetcher, copilotTokenManager, telemetrySender, logTarget } = options;
    const builder = new services_1.InstantiationServiceBuilder();
    builder.define(configurationService_1.IConfigurationService, new descriptors_1.SyncDescriptor(OverridableConfigurationService, [options.configOverrides ?? new Map()]));
    builder.define(nullExperimentationService_1.IExperimentationService, new descriptors_1.SyncDescriptor(SimpleExperimentationService, [options.waitForTreatmentVariables]));
    builder.define(simulationTestContext_1.ISimulationTestContext, new descriptors_1.SyncDescriptor(simulationTestContext_1.NulSimulationTestContext));
    builder.define(workspaceService_1.IWorkspaceService, new descriptors_1.SyncDescriptor(workspaceService_1.NullWorkspaceService));
    builder.define(diffService_1.IDiffService, new descriptors_1.SyncDescriptor(diffServiceImpl_1.DiffServiceImpl, [false]));
    builder.define(logService_1.ILogService, new descriptors_1.SyncDescriptor(logService_1.LogServiceImpl, [[logTarget || new logService_1.ConsoleLog(undefined, logService_1.LogLevel.Trace)]]));
    builder.define(gitExtensionService_1.IGitExtensionService, new descriptors_1.SyncDescriptor(nullGitExtensionService_1.NullGitExtensionService));
    builder.define(languageContextProviderService_1.ILanguageContextProviderService, new descriptors_1.SyncDescriptor(nullLanguageContextProviderService_1.NullLanguageContextProviderService));
    builder.define(languageDiagnosticsService_1.ILanguageDiagnosticsService, new descriptors_1.SyncDescriptor(testLanguageDiagnosticsService_1.TestLanguageDiagnosticsService));
    builder.define(ignoreService_1.IIgnoreService, new descriptors_1.SyncDescriptor(ignoreService_1.NullIgnoreService));
    builder.define(snippyService_1.ISnippyService, new descriptors_1.SyncDescriptor(snippyService_1.NullSnippyService));
    builder.define(domainService_1.IDomainService, new descriptors_1.SyncDescriptor(domainServiceImpl_1.DomainService));
    builder.define(capiClient_1.ICAPIClientService, new descriptors_1.SyncDescriptor(capiClientImpl_1.CAPIClientImpl));
    builder.define(copilotTokenStore_1.ICopilotTokenStore, new descriptors_1.SyncDescriptor(copilotTokenStore_1.CopilotTokenStore));
    builder.define(envService_1.IEnvService, new descriptors_1.SyncDescriptor(nullEnvService_1.NullEnvService));
    builder.define(fetcherService_1.IFetcherService, new descriptors_1.SyncDescriptor(SingleFetcherService, [fetcher]));
    builder.define(telemetry_1.ITelemetryService, new descriptors_1.SyncDescriptor(SimpleTelemetryService, [telemetrySender]));
    builder.define(authentication_1.IAuthenticationService, new descriptors_1.SyncDescriptor(staticGitHubAuthenticationService_1.StaticGitHubAuthenticationService, [(0, copilotTokenManager_3.createStaticGitHubTokenProvider)()]));
    builder.define(copilotTokenManager_2.ICopilotTokenManager, copilotTokenManager);
    builder.define(powerService_1.IPowerService, new descriptors_1.SyncDescriptor(powerService_1.NullPowerService));
    builder.define(chatMLFetcher_2.IChatMLFetcher, new descriptors_1.SyncDescriptor(chatMLFetcher_1.ChatMLFetcherImpl));
    builder.define(chatWebSocketManager_1.IChatWebSocketManager, new descriptors_1.SyncDescriptor(chatWebSocketManager_1.NullChatWebSocketManager));
    builder.define(otelService_1.IOTelService, new noopOtelService_1.NoopOTelService((0, otelConfig_1.resolveOTelConfig)({ env: {}, extensionVersion: '0.0.0', sessionId: 'chatlib' })));
    builder.define(chatQuotaService_1.IChatQuotaService, new descriptors_1.SyncDescriptor(chatQuotaServiceImpl_1.ChatQuotaService));
    builder.define(interactionService_1.IInteractionService, new descriptors_1.SyncDescriptor(interactionService_1.InteractionService));
    builder.define(requestLogger_1.IRequestLogger, new descriptors_1.SyncDescriptor(nullRequestLogger_1.NullRequestLogger));
    builder.define(tokenizer_1.ITokenizerProvider, new descriptors_1.SyncDescriptor(tokenizer_1.TokenizerProvider, [false]));
    builder.define(conversationOptions_1.IConversationOptions, {
        _serviceBrand: undefined,
        maxResponseTokens: undefined,
        temperature: 0.1,
        topP: 1,
        rejectionMessage: 'Sorry, but I can only assist with programming related questions.',
    });
    builder.define(proxyModelsService_1.IProxyModelsService, new descriptors_1.SyncDescriptor(proxyModelsService_2.ProxyModelsService));
    builder.define(inlineEditsModelService_1.IInlineEditsModelService, new descriptors_1.SyncDescriptor(inlineEditsModelService_2.InlineEditsModelService));
    builder.define(inlineEditsModelService_1.IUndesiredModelsManager, options.undesiredModelsManager || new descriptors_1.SyncDescriptor(inlineEditsModelService_1.NullUndesiredModelsManager));
    builder.define(terminalService_1.ITerminalService, options.terminalService || new descriptors_1.SyncDescriptor(terminalService_1.NullTerminalService));
    builder.define(similarFilesContextService_1.ISimilarFilesContextService, new descriptors_1.SyncDescriptor(similarFilesContextService_1.NullSimilarFilesContextService));
    builder.define(endpointProvider_1.IEndpointProvider, new NullEndpointProvider());
    const configProvider = new config_1.InMemoryConfigProvider(new config_1.DefaultsOnlyConfigProvider());
    if (options.configOverrides) {
        configProvider.setOverrides(options.configOverrides);
    }
    builder.define(config_1.ICompletionsConfigProvider, configProvider);
    return builder.seal();
}
class OverridableConfigurationService extends defaultsOnlyConfigurationService_1.DefaultsOnlyConfigurationService {
    constructor(overrides) {
        super();
        this._overrides = overrides;
    }
    async setConfig(key, value, _target) {
        const existing = this._overrides.get(key.id);
        if (existing === value) {
            return;
        }
        if (value === undefined) {
            this._overrides.delete(key.id);
        }
        else {
            this._overrides.set(key.id, value);
        }
        const fullyQualifiedKey = key.fullyQualifiedId;
        this._onDidChangeConfiguration.fire({
            affectsConfiguration: (section) => {
                return fullyQualifiedKey === section || fullyQualifiedKey.startsWith(section + '.') || section.startsWith(fullyQualifiedKey + '.');
            }
        });
        return;
    }
    getConfig(key) {
        if (this._overrides.has(key.id)) {
            const overriddenValue = this._overrides.get(key.id);
            if (key.validator) {
                const result = key.validator.validate(overriddenValue);
                if (result.error) {
                    return super.getConfig(key);
                }
                return result.content;
            }
            return overriddenValue;
        }
        return super.getConfig(key);
    }
    getExperimentBasedConfig(key, experimentationService) {
        if (this._overrides.has(key.id)) {
            const overriddenValue = this._overrides.get(key.id);
            if (key.validator) {
                const result = key.validator.validate(overriddenValue);
                if (result.error) {
                    return super.getExperimentBasedConfig(key, experimentationService);
                }
                return result.content;
            }
            return overriddenValue;
        }
        return super.getExperimentBasedConfig(key, experimentationService);
    }
    inspectConfig(key) {
        if (this._overrides.has(key.id)) {
            const overriddenValue = this._overrides.get(key.id);
            if (key.validator) {
                const result = key.validator.validate(overriddenValue);
                if (result.error) {
                    return super.inspectConfig(key);
                }
                return { defaultValue: result.content };
            }
            return { defaultValue: overriddenValue };
        }
        return super.inspectConfig(key);
    }
}
class NullEndpointProvider {
    constructor() {
        this.onDidModelsRefresh = event_1.Event.None;
    }
    async getAllCompletionModels() { return []; }
    async getAllChatEndpoints() { return []; }
    async getChatEndpoint() { throw new Error('not implemented'); }
    async getEmbeddingsEndpoint() { throw new Error('not implemented'); }
}
let SimpleExperimentationService = class SimpleExperimentationService extends lifecycle_1.Disposable {
    constructor(waitForTreatmentVariables, _configurationService) {
        super();
        this._configurationService = _configurationService;
        this.variables = {};
        this._onDidTreatmentsChange = this._register(new event_1.Emitter());
        this.onDidTreatmentsChange = this._onDidTreatmentsChange.event;
        if (waitForTreatmentVariables) {
            let resolveWaitFor;
            this.waitFor = new Promise(resolve => {
                resolveWaitFor = resolve;
            });
            this.resolveWaitFor = resolveWaitFor;
        }
        else {
            this.waitFor = Promise.resolve();
            this.resolveWaitFor = () => { };
        }
    }
    async hasTreatments() {
        return this.waitFor;
    }
    getTreatmentVariable(name) {
        return this.variables[name];
    }
    async setCompletionsFilters(_filters) { }
    updateTreatmentVariables(variables) {
        const changedVariables = [];
        for (const [key, value] of Object.entries(variables)) {
            const existing = this.variables[key];
            if (existing !== value) {
                this.variables[key] = value;
                changedVariables.push(key);
            }
        }
        for (const key of Object.keys(this.variables)) {
            if (!Object.hasOwn(variables, key)) {
                delete this.variables[key];
                changedVariables.push(key);
            }
        }
        if (changedVariables.length > 0) {
            this._onDidTreatmentsChange.fire({ affectedTreatmentVariables: changedVariables });
            this._configurationService.updateExperimentBasedConfiguration(changedVariables);
        }
        this.resolveWaitFor();
    }
};
exports.SimpleExperimentationService = SimpleExperimentationService;
exports.SimpleExperimentationService = SimpleExperimentationService = __decorate([
    __param(1, configurationService_1.IConfigurationService)
], SimpleExperimentationService);
class SingleFetcherService {
    constructor(_fetcher) {
        this._fetcher = _fetcher;
        this.onDidFetch = event_1.Event.None;
        this.onDidCompleteFetch = event_1.Event.None;
    }
    fetchWithPagination(baseUrl, options) {
        return this._fetcher.fetchWithPagination(baseUrl, options);
    }
    getUserAgentLibrary() {
        return this._fetcher.getUserAgentLibrary();
    }
    fetch(url, options) {
        return this._fetcher.fetch(url, options);
    }
    createWebSocket(url, options) {
        return { webSocket: new WebSocket(url, options), responseHeaders: new fetcherService_1.HeadersImpl({}), responseStatusCode: undefined, responseStatusText: undefined, networkError: undefined };
    }
    disconnectAll() {
        return this._fetcher.disconnectAll();
    }
    makeAbortController() {
        return this._fetcher.makeAbortController();
    }
    isAbortError(e) {
        return this._fetcher.isAbortError(e);
    }
    isInternetDisconnectedError(e) {
        return this._fetcher.isInternetDisconnectedError(e);
    }
    isFetcherError(e) {
        return this._fetcher.isFetcherError(e);
    }
    isNetworkProcessCrashedError(e) {
        return this._fetcher.isNetworkProcessCrashedError(e);
    }
    getUserMessageForFetcherError(err) {
        return this._fetcher.getUserMessageForFetcherError(err);
    }
}
class SimpleTelemetryService {
    constructor(_telemetrySender) {
        this._telemetrySender = _telemetrySender;
    }
    dispose() {
        return;
    }
    sendInternalMSFTTelemetryEvent(eventName, properties, measurements) {
        return;
    }
    sendMSFTTelemetryEvent(eventName, properties, measurements) {
        return;
    }
    sendMSFTTelemetryErrorEvent(eventName, properties, measurements) {
        return;
    }
    sendGHTelemetryEvent(eventName, properties, measurements) {
        this._telemetrySender.sendTelemetryEvent(eventName, (0, telemetryData_1.eventPropertiesToSimpleObject)(properties), measurements);
    }
    sendGHTelemetryErrorEvent(eventName, properties, measurements) {
        return;
    }
    sendGHTelemetryException(maybeError, origin) {
        return;
    }
    sendTelemetryEvent(eventName, destination, properties, measurements) {
        return;
    }
    sendTelemetryErrorEvent(eventName, destination, properties, measurements) {
        return;
    }
    setSharedProperty(name, value) {
        return;
    }
    setAdditionalExpAssignments(expAssignments) {
        return;
    }
    postEvent(eventName, props) {
        return;
    }
    sendEnhancedGHTelemetryEvent(eventName, properties, measurements) {
        if (this._telemetrySender.sendEnhancedTelemetryEvent) {
            this._telemetrySender.sendEnhancedTelemetryEvent(eventName, (0, telemetryData_1.eventPropertiesToSimpleObject)(properties), measurements);
        }
    }
    sendEnhancedGHTelemetryErrorEvent(eventName, properties, measurements) {
        return;
    }
}
function createInlineCompletionsProvider(options) {
    const svc = setupCompletionServices(options);
    return svc.createInstance(InlineCompletionsProvider);
}
let InlineCompletionsProvider = class InlineCompletionsProvider extends lifecycle_1.Disposable {
    constructor(_insta, _expService, _speculativeRequestCache, _logService, _configurationService, _completionsConfigProvider) {
        super();
        this._insta = _insta;
        this._expService = _expService;
        this._speculativeRequestCache = _speculativeRequestCache;
        this._logService = _logService;
        this._configurationService = _configurationService;
        this._completionsConfigProvider = _completionsConfigProvider;
        this._register(_insta);
        this.ghostText = this._insta.createInstance(inlineCompletion_1.GhostText);
    }
    updateTreatmentVariables(variables) {
        if (this._expService instanceof SimpleExperimentationService) {
            this._expService.updateTreatmentVariables(variables);
        }
    }
    async setConfigs(overrides) {
        for (const [key, value] of overrides) {
            const config = configurationService_1.globalConfigRegistry.configs.get(`${configurationService_1.CopilotConfigPrefix}.${key}`);
            if (config) {
                await this._configurationService.setConfig(config, value);
            }
        }
        if (this._completionsConfigProvider instanceof config_1.InMemoryConfigProvider) {
            this._completionsConfigProvider.setCopilotSettings(Object.fromEntries(overrides));
        }
    }
    async getInlineCompletions(textDocument, position, token, options) {
        const telemetryBuilder = new nextEditProviderTelemetry_1.LlmNESTelemetryBuilder(undefined, undefined, undefined, 'ghostText', undefined);
        return await this.ghostText.getInlineCompletions(textDocument, position, token ?? cancellation_1.CancellationToken.None, options, new ghostTextContext_1.GhostTextLogContext(textDocument.uri, textDocument.version, undefined), telemetryBuilder, this._logService);
    }
    async inlineCompletionShown(completionId) {
        return await this._speculativeRequestCache.request(completionId);
    }
};
InlineCompletionsProvider = __decorate([
    __param(0, instantiation_1.IInstantiationService),
    __param(1, nullExperimentationService_1.IExperimentationService),
    __param(2, speculativeRequestCache_1.ICompletionsSpeculativeRequestCache),
    __param(3, logService_1.ILogService),
    __param(4, configurationService_1.IConfigurationService),
    __param(5, config_1.ICompletionsConfigProvider)
], InlineCompletionsProvider);
class UnwrappingTelemetrySender {
    constructor(sender) {
        this.sender = sender;
    }
    sendTelemetryEvent(eventName, properties, measurements) {
        this.sender.sendTelemetryEvent(this.normalizeEventName(eventName), properties, measurements);
    }
    sendEnhancedTelemetryEvent(eventName, properties, measurements) {
        if (this.sender.sendEnhancedTelemetryEvent) {
            this.sender.sendEnhancedTelemetryEvent(this.normalizeEventName(eventName), properties, measurements);
        }
    }
    normalizeEventName(eventName) {
        const unwrapped = (0, azureInsightsReporter_1.unwrapEventNameFromPrefix)(eventName);
        const withoutPrefix = unwrapped.match(/^[^/]+\/(.*)/);
        return withoutPrefix ? withoutPrefix[1] : unwrapped;
    }
}
function setupCompletionServices(options) {
    const { fetcher, authService, statusHandler, documentManager, workspace, telemetrySender, urlOpener, editorSession } = options;
    const logTarget = options.logTarget || new logService_1.ConsoleLog(undefined, logService_1.LogLevel.Trace);
    const builder = new services_1.InstantiationServiceBuilder();
    builder.define(logger_1.ICompletionsLogTargetService, new class {
        logIt(level, category, ...extra) {
            logTarget.logIt(this.toExternalLogLevel(level), category, ...extra);
        }
        toExternalLogLevel(level) {
            switch (level) {
                case logger_1.LogLevel.DEBUG: return LogLevel.Debug;
                case logger_1.LogLevel.INFO: return LogLevel.Info;
                case logger_1.LogLevel.WARN: return LogLevel.Warning;
                case logger_1.LogLevel.ERROR: return LogLevel.Error;
                default: return LogLevel.Info;
            }
        }
    });
    builder.define(authentication_1.IAuthenticationService, authService);
    builder.define(logService_1.ILogService, new descriptors_1.SyncDescriptor(logService_1.LogServiceImpl, [[logTarget || new logService_1.ConsoleLog(undefined, logService_1.LogLevel.Trace)]]));
    builder.define(ignoreService_1.IIgnoreService, options.ignoreService || new ignoreService_1.NullIgnoreService());
    builder.define(telemetry_1.ITelemetryService, new descriptors_1.SyncDescriptor(SimpleTelemetryService, [new UnwrappingTelemetrySender(telemetrySender)]));
    builder.define(configurationService_1.IConfigurationService, new descriptors_1.SyncDescriptor(OverridableConfigurationService, [options.configOverrides ?? new Map()]));
    builder.define(nullExperimentationService_1.IExperimentationService, new descriptors_1.SyncDescriptor(SimpleExperimentationService, [options.waitForTreatmentVariables]));
    builder.define(endpointProvider_1.IEndpointProvider, options.endpointProvider);
    builder.define(capiClient_1.ICAPIClientService, options.capiClientService || new descriptors_1.SyncDescriptor(capiClientImpl_1.CAPIClientImpl));
    builder.define(fetcherService_1.IFetcherService, new descriptors_1.SyncDescriptor(SingleFetcherService, [fetcher]));
    builder.define(completionsTelemetryServiceBridge_1.ICompletionsTelemetryService, new descriptors_1.SyncDescriptor(completionsTelemetryServiceBridge_1.CompletionsTelemetryServiceBridge));
    builder.define(runtimeMode_1.ICompletionsRuntimeModeService, runtimeMode_1.RuntimeMode.fromEnvironment(options.isRunningInTest ?? false));
    builder.define(completionsCache_1.ICompletionsCacheService, new completionsCache_1.CompletionsCache());
    const configProvider = new config_1.InMemoryConfigProvider(new config_1.DefaultsOnlyConfigProvider());
    if (options.configOverrides) {
        configProvider.setOverrides(options.configOverrides);
    }
    builder.define(config_1.ICompletionsConfigProvider, configProvider);
    builder.define(last_1.ICompletionsLastGhostText, new last_1.LastGhostText());
    builder.define(current_1.ICompletionsCurrentGhostText, new current_1.CurrentGhostText());
    builder.define(speculativeRequestCache_1.ICompletionsSpeculativeRequestCache, new speculativeRequestCache_1.SpeculativeRequestCache());
    builder.define(notificationSender_1.ICompletionsNotificationSender, new class {
        async showWarningMessage(message, ...actions) {
            return await options.notificationSender.showWarningMessage(message, ...actions);
        }
    });
    builder.define(config_1.ICompletionsEditorAndPluginInfo, new class {
        getEditorInfo() {
            return options.editorInfo;
        }
        getEditorPluginInfo() {
            return options.editorPluginInfo;
        }
        getRelatedPluginInfo() {
            return options.relatedPluginInfo;
        }
    });
    builder.define(extensionStatus_1.ICompletionsExtensionStatus, new extensionStatus_1.CopilotExtensionStatus());
    builder.define(featuresService_1.ICompletionsFeaturesService, new descriptors_1.SyncDescriptor(features_1.Features));
    builder.define(completionsObservableWorkspace_1.ICompletionsObservableWorkspace, new class {
        get openDocuments() {
            return workspace.openDocuments;
        }
        getWorkspaceRoot(documentId) {
            return workspace.getWorkspaceRoot(documentId);
        }
        getFirstOpenDocument() {
            return workspace.getFirstOpenDocument();
        }
        getDocument(documentId) {
            return workspace.getDocument(documentId);
        }
    });
    builder.define(progress_1.ICompletionsStatusReporter, new class extends progress_1.StatusReporter {
        didChange(event) {
            statusHandler.didChange(event);
        }
    });
    builder.define(copilotTokenManager_1.ICompletionsCopilotTokenManager, new descriptors_1.SyncDescriptor(copilotTokenManager_1.CopilotTokenManagerImpl, [false]));
    builder.define(textDocumentManager_1.ICompletionsTextDocumentManagerService, new descriptors_1.SyncDescriptor(class extends textDocumentManager_1.TextDocumentManager {
        constructor() {
            super(...arguments);
            this.onDidChangeTextDocument = documentManager.onDidChangeTextDocument;
            this.onDidOpenTextDocument = documentManager.onDidOpenTextDocument;
            this.onDidCloseTextDocument = documentManager.onDidCloseTextDocument;
            this.onDidFocusTextDocument = documentManager.onDidFocusTextDocument;
            this.onDidChangeWorkspaceFolders = documentManager.onDidChangeWorkspaceFolders;
        }
        getTextDocumentsUnsafe() {
            return documentManager.getTextDocumentsUnsafe();
        }
        findNotebook(doc) {
            return documentManager.findNotebook(doc);
        }
        getWorkspaceFolders() {
            return documentManager.getWorkspaceFolders();
        }
    }));
    builder.define(fileReader_1.ICompletionsFileReaderService, new descriptors_1.SyncDescriptor(fileReader_1.FileReader));
    builder.define(configBlockMode_1.ICompletionsBlockModeConfig, new descriptors_1.SyncDescriptor(configBlockMode_1.ConfigBlockModeConfig));
    builder.define(userConfig_1.ICompletionsTelemetryUserConfigService, new descriptors_1.SyncDescriptor(userConfig_1.TelemetryUserConfig));
    builder.define(recentEditsProvider_1.ICompletionsRecentEditsProviderService, new descriptors_1.SyncDescriptor(recentEditsProvider_1.FullRecentEditsProvider, [undefined]));
    builder.define(completionNotifier_1.ICompletionsNotifierService, new descriptors_1.SyncDescriptor(completionNotifier_1.CompletionNotifier));
    builder.define(fetch_1.ICompletionsOpenAIFetcherService, new descriptors_1.SyncDescriptor(fetch_1.LiveOpenAIFetcher));
    builder.define(completionsFetchService_1.ICompletionsFetchService, new descriptors_1.SyncDescriptor(completionsFetchServiceImpl_1.CompletionsFetchService));
    builder.define(model_1.ICompletionsModelManagerService, new descriptors_1.SyncDescriptor(model_1.AvailableModelsManager, [true]));
    builder.define(asyncCompletions_1.ICompletionsAsyncManagerService, new descriptors_1.SyncDescriptor(asyncCompletions_1.AsyncCompletionManager));
    builder.define(contextProviderBridge_1.ICompletionsContextProviderBridgeService, new descriptors_1.SyncDescriptor(contextProviderBridge_1.ContextProviderBridge));
    builder.define(userErrorNotifier_1.ICompletionsUserErrorNotifierService, new descriptors_1.SyncDescriptor(userErrorNotifier_1.UserErrorNotifier));
    builder.define(relatedFiles_1.ICompletionsRelatedFilesProviderService, new descriptors_1.SyncDescriptor(compositeRelatedFilesProvider_1.CompositeRelatedFilesProvider));
    builder.define(fileSystem_1.ICompletionsFileSystemService, new localFileSystem_1.LocalFileSystem());
    builder.define(contextProviderRegistry_1.ICompletionsContextProviderRegistryService, new descriptors_1.SyncDescriptor(contextProviderRegistry_1.CachedContextProviderRegistry, [contextProviderRegistry_1.CoreContextProviderRegistry, (_, sel, docCtx) => options.contextProviderMatch(sel, docCtx)]));
    builder.define(promiseQueue_1.ICompletionsPromiseQueueService, new promiseQueue_1.PromiseQueue());
    builder.define(citationManager_1.ICompletionsCitationManager, new class {
        register() { return lifecycle_1.Disposable.None; }
        async handleIPCodeCitation(citation) {
            if (options.citationHandler) {
                return await options.citationHandler.handleIPCodeCitation(citation);
            }
        }
    });
    builder.define(contextProviderStatistics_1.ICompletionsContextProviderService, new contextProviderStatistics_1.ContextProviderStatistics());
    builder.define(completionsPromptFactory_1.ICompletionsPromptFactoryService, new descriptors_1.SyncDescriptor(completionsPromptFactory_1.CompletionsPromptFactory));
    builder.define(networking_1.ICompletionsFetcherService, new class {
        getImplementation() {
            return this;
        }
        fetch(url, options) {
            return fetcher.fetch(url, options);
        }
        disconnectAll() {
            return fetcher.disconnectAll();
        }
    });
    builder.define(contextProviderRegistry_1.ICompletionsDefaultContextProviders, new contextProviderRegistry_1.DefaultContextProvidersContainer());
    builder.define(envService_1.IEnvService, new class {
        constructor() {
            this.language = undefined;
            this.sessionId = editorSession.sessionId;
            this.machineId = editorSession.machineId;
            this.devDeviceId = editorSession.machineId;
            this.vscodeVersion = options.editorInfo.version;
            this.isActive = true;
            this.onDidChangeWindowState = event_1.Event.None;
            this.remoteName = editorSession.remoteName;
            this.uiKind = editorSession.uiKind === 'web' ? 'web' : 'desktop';
            this.OS = process.platform === 'darwin' ? envService_1.OperatingSystem.Macintosh : process.platform === 'win32' ? envService_1.OperatingSystem.Windows : envService_1.OperatingSystem.Linux;
            this.uriScheme = '';
            this.extensionId = options.editorPluginInfo.name;
            this.appRoot = options.editorInfo.root ?? '';
            this.shell = '';
        }
        isProduction() { return config_1.BuildInfo.isProduction(); }
        isPreRelease() { return config_1.BuildInfo.isPreRelease(); }
        isSimulation() { return options.isRunningInTest === true; }
        getBuildType() {
            const t = config_1.BuildInfo.getBuildType();
            return t === config_1.BuildType.DEV ? 'dev' : 'prod';
        }
        getVersion() { return config_1.BuildInfo.getVersion(); }
        getBuild() { return config_1.BuildInfo.getBuild(); }
        getName() { return options.editorInfo.name; }
        getEditorInfo() { return new envService_1.NameAndVersion(options.editorInfo.name, options.editorInfo.version); }
        getEditorPluginInfo() { return new envService_1.NameAndVersion(options.editorPluginInfo.name, options.editorPluginInfo.version); }
        async openExternal(target) {
            await urlOpener.open(target.toString());
            return true;
        }
    });
    builder.define(languageContextProviderService_1.ILanguageContextProviderService, options.languageContextProvider ?? new nullLanguageContextProviderService_1.NullLanguageContextProviderService());
    builder.define(languageDiagnosticsService_1.ILanguageDiagnosticsService, new descriptors_1.SyncDescriptor(testLanguageDiagnosticsService_1.TestLanguageDiagnosticsService));
    builder.define(requestLogger_1.IRequestLogger, new descriptors_1.SyncDescriptor(nullRequestLogger_1.NullRequestLogger));
    return builder.seal();
}
//# sourceMappingURL=main.js.map