
import { __decorate, __param } from '../../../../../../../external/tslib/tslib.es6.js';
import { equals as equals$1 } from '../../../../base/common/arrays.js';
import { assertNever } from '../../../../base/common/assert.js';
import { encodeHex, VSBuffer, decodeHex } from '../../../../base/common/buffer.js';
import { Disposable } from '../../../../base/common/lifecycle.js';
import { equals } from '../../../../base/common/objects.js';
import '../../../../base/common/observableInternal/index.js';
import { URI } from '../../../../base/common/uri.js';
import { localize } from '../../../../nls.js';
import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js';
import { ExtensionIdentifier } from '../../../../platform/extensions/common/extensions.js';
import { McpGalleryManifestStatus } from '../../../../platform/mcp/common/mcpGalleryManifest.js';
import { IMcpWorkbenchService } from './mcpTypes.service.js';
import { MCP } from '../../../../platform/mcp/common/modelContextProtocol.js';
import { ObservableMap } from '../../../../base/common/observableInternal/map.js';

const extensionMcpCollectionPrefix = "ext.";
function extensionPrefixedIdentifier(identifier, id) {
    return ExtensionIdentifier.toKey(identifier) + "/" + id;
}
var McpCollectionSortOrder;
(function(McpCollectionSortOrder) {
    McpCollectionSortOrder[McpCollectionSortOrder["WorkspaceFolder"] = 0] = "WorkspaceFolder";
    McpCollectionSortOrder[McpCollectionSortOrder["Workspace"] = 100] = "Workspace";
    McpCollectionSortOrder[McpCollectionSortOrder["User"] = 200] = "User";
    McpCollectionSortOrder[McpCollectionSortOrder["Extension"] = 300] = "Extension";
    McpCollectionSortOrder[McpCollectionSortOrder["Plugin"] = 350] = "Plugin";
    McpCollectionSortOrder[McpCollectionSortOrder["Filesystem"] = 400] = "Filesystem";
    McpCollectionSortOrder[McpCollectionSortOrder["RemoteBoost"] = -50] = "RemoteBoost";
})(McpCollectionSortOrder || (McpCollectionSortOrder = {}));
var McpCollectionDefinition;
(function(McpCollectionDefinition) {
    function equals$1(a, b) {
        return a.id === b.id && a.remoteAuthority === b.remoteAuthority && a.label === b.label && a.trustBehavior === b.trustBehavior && equals(a.sandbox, b.sandbox);
    }
    McpCollectionDefinition.equals = equals$1;
})(McpCollectionDefinition || (McpCollectionDefinition = {}));
var McpServerStaticToolAvailability;
(function(McpServerStaticToolAvailability) {
    McpServerStaticToolAvailability[McpServerStaticToolAvailability["Initial"] = 0] = "Initial";
    McpServerStaticToolAvailability[McpServerStaticToolAvailability["Dynamic"] = 1] = "Dynamic";
})(McpServerStaticToolAvailability || (McpServerStaticToolAvailability = {}));
var McpServerDefinition;
(function(McpServerDefinition) {
    function toSerialized(def) {
        return def;
    }
    McpServerDefinition.toSerialized = toSerialized;
    function fromSerialized(def) {
        return {
            id: def.id,
            label: def.label,
            cacheNonce: def.cacheNonce,
            staticMetadata: def.staticMetadata,
            launch: McpServerLaunch.fromSerialized(def.launch),
            sandboxEnabled: def.sandboxEnabled,
            variableReplacement: def.variableReplacement ? McpServerDefinitionVariableReplacement.fromSerialized(def.variableReplacement) : undefined
        };
    }
    McpServerDefinition.fromSerialized = fromSerialized;
    function equals$2(a, b) {
        return a.id === b.id && a.label === b.label && a.cacheNonce === b.cacheNonce && equals$1(a.roots, b.roots, (a, b) => ( a.toString()) === ( b.toString())) && equals(a.launch, b.launch) && equals(a.presentation, b.presentation) && equals(a.variableReplacement, b.variableReplacement) && equals(a.devMode, b.devMode) && a.sandboxEnabled === b.sandboxEnabled;
    }
    McpServerDefinition.equals = equals$2;
})(McpServerDefinition || (McpServerDefinition = {}));
var McpServerDefinitionVariableReplacement;
(function(McpServerDefinitionVariableReplacement) {
    function toSerialized(def) {
        return def;
    }
    McpServerDefinitionVariableReplacement.toSerialized = toSerialized;
    function fromSerialized(def) {
        return {
            section: def.section,
            folder: def.folder ? {
                ...def.folder,
                uri: URI.revive(def.folder.uri)
            } : undefined,
            target: def.target
        };
    }
    McpServerDefinitionVariableReplacement.fromSerialized = fromSerialized;
})(
    McpServerDefinitionVariableReplacement || (McpServerDefinitionVariableReplacement = {})
);
var IAutostartResult;
(function(IAutostartResult) {
    IAutostartResult.Empty = {
        working: false,
        starting: [],
        serversRequiringInteraction: []
    };
})(IAutostartResult || (IAutostartResult = {}));
var LazyCollectionState;
(function(LazyCollectionState) {
    LazyCollectionState[LazyCollectionState["HasUnknown"] = 0] = "HasUnknown";
    LazyCollectionState[LazyCollectionState["LoadingUnknown"] = 1] = "LoadingUnknown";
    LazyCollectionState[LazyCollectionState["AllKnown"] = 2] = "AllKnown";
})(LazyCollectionState || (LazyCollectionState = {}));
class McpStartServerInteraction {
    constructor() {
        this.participants = ( new ObservableMap());
    }
}
var McpServerTrust;
(function(McpServerTrust) {
    (function(Kind) {
        Kind[Kind["Trusted"] = 0] = "Trusted";
        Kind[Kind["TrustedOnNonce"] = 1] = "TrustedOnNonce";
        Kind[Kind["Untrusted"] = 2] = "Untrusted";
        Kind[Kind["Unknown"] = 3] = "Unknown";
    })(McpServerTrust.Kind || (McpServerTrust.Kind = {}));
})(McpServerTrust || (McpServerTrust = {}));
const isMcpResourceTemplate = obj => {
    return obj.template !== undefined;
};
var McpServerCacheState;
(function(McpServerCacheState) {
    McpServerCacheState[McpServerCacheState["Unknown"] = 0] = "Unknown";
    McpServerCacheState[McpServerCacheState["Cached"] = 1] = "Cached";
    McpServerCacheState[McpServerCacheState["Outdated"] = 2] = "Outdated";
    McpServerCacheState[McpServerCacheState["RefreshingFromUnknown"] = 3] = "RefreshingFromUnknown";
    McpServerCacheState[McpServerCacheState["RefreshingFromCached"] = 4] = "RefreshingFromCached";
    McpServerCacheState[McpServerCacheState["Live"] = 5] = "Live";
})(McpServerCacheState || (McpServerCacheState = {}));
const mcpPromptReplaceSpecialChars = s => s.replace(/[^a-z0-9_.-]/gi, "_");
const mcpPromptPrefix = definition => `/mcp.` + mcpPromptReplaceSpecialChars(definition.label);
var McpToolVisibility;
(function(McpToolVisibility) {
    McpToolVisibility[McpToolVisibility["Model"] = 1] = "Model";
    McpToolVisibility[McpToolVisibility["App"] = 2] = "App";
})(McpToolVisibility || (McpToolVisibility = {}));
var McpServerTransportType;
(function(McpServerTransportType) {
    McpServerTransportType[McpServerTransportType["Stdio"] = 1] = "Stdio";
    McpServerTransportType[McpServerTransportType["HTTP"] = 2] = "HTTP";
})(McpServerTransportType || (McpServerTransportType = {}));
var McpServerLaunch;
(function(McpServerLaunch) {
    function toSerialized(launch) {
        return launch;
    }
    McpServerLaunch.toSerialized = toSerialized;
    function fromSerialized(launch) {
        switch (launch.type) {
        case McpServerTransportType.HTTP:
            return {
                type: launch.type,
                uri: URI.revive(launch.uri),
                headers: launch.headers,
                authentication: launch.authentication
            };
        case McpServerTransportType.Stdio:
            return {
                type: launch.type,
                cwd: launch.cwd,
                command: launch.command,
                args: launch.args,
                env: launch.env,
                envFile: launch.envFile,
                sandbox: launch.sandbox
            };
        }
    }
    McpServerLaunch.fromSerialized = fromSerialized;
    async function hash(launch) {
        const nonce = await crypto.subtle.digest("SHA-256", ( new TextEncoder()).encode(JSON.stringify(launch)));
        return encodeHex(VSBuffer.wrap(( new Uint8Array(nonce))));
    }
    McpServerLaunch.hash = hash;
})(McpServerLaunch || (McpServerLaunch = {}));
var McpConnectionState;
(function(McpConnectionState) {
    let Kind;
    (function(Kind) {
        Kind[Kind["Stopped"] = 0] = "Stopped";
        Kind[Kind["Starting"] = 1] = "Starting";
        Kind[Kind["Running"] = 2] = "Running";
        Kind[Kind["Error"] = 3] = "Error";
    })(Kind = McpConnectionState.Kind || (McpConnectionState.Kind = {}));
    McpConnectionState.toString = s => {
        switch (s.state) {
        case Kind.Stopped:
            return localize(10723, "Stopped");
        case Kind.Starting:
            return localize(10724, "Starting");
        case Kind.Running:
            return localize(10725, "Running");
        case Kind.Error:
            return localize(10726, "Error {0}", s.message);
        default:
            assertNever();
        }
    };
    McpConnectionState.toKindString = s => {
        switch (s) {
        case Kind.Stopped:
            return "stopped";
        case Kind.Starting:
            return "starting";
        case Kind.Running:
            return "running";
        case Kind.Error:
            return "error";
        default:
            assertNever();
        }
    };
    McpConnectionState.canBeStarted = s => s === Kind.Error || s === Kind.Stopped;
    McpConnectionState.isRunning = s => !McpConnectionState.canBeStarted(s.state);
})(McpConnectionState || (McpConnectionState = {}));
class MpcResponseError extends Error {
    constructor(message, code, data) {
        super(`MPC ${code}: ${message}`);
        this.code = code;
        this.data = data;
    }
}
class McpConnectionFailedError extends Error {}
class UserInteractionRequiredError extends Error {
    static {
        this.prefix = "User interaction required: ";
    }
    static is(error) {
        return error.message.startsWith(this.prefix);
    }
    constructor(reason) {
        super(`${UserInteractionRequiredError.prefix}${reason}`);
        this.reason = reason;
    }
}
var McpServerEnablementState;
(function(McpServerEnablementState) {
    McpServerEnablementState[McpServerEnablementState["Disabled"] = 0] = "Disabled";
    McpServerEnablementState[McpServerEnablementState["DisabledByAccess"] = 1] = "DisabledByAccess";
    McpServerEnablementState[McpServerEnablementState["DisabledProfile"] = 2] = "DisabledProfile";
    McpServerEnablementState[McpServerEnablementState["DisabledWorkspace"] = 3] = "DisabledWorkspace";
    McpServerEnablementState[McpServerEnablementState["Enabled"] = 4] = "Enabled";
})(McpServerEnablementState || (McpServerEnablementState = {}));
var McpServerInstallState;
(function(McpServerInstallState) {
    McpServerInstallState[McpServerInstallState["Installing"] = 0] = "Installing";
    McpServerInstallState[McpServerInstallState["Installed"] = 1] = "Installed";
    McpServerInstallState[McpServerInstallState["Uninstalling"] = 2] = "Uninstalling";
    McpServerInstallState[McpServerInstallState["Uninstalled"] = 3] = "Uninstalled";
})(McpServerInstallState || (McpServerInstallState = {}));
var McpServerEditorTab;
(function(McpServerEditorTab) {
    McpServerEditorTab["Readme"] = "readme";
    McpServerEditorTab["Manifest"] = "manifest";
    McpServerEditorTab["Configuration"] = "configuration";
})(McpServerEditorTab || (McpServerEditorTab = {}));
let McpServerContainers = class McpServerContainers extends Disposable {
    constructor(containers, mcpWorkbenchService) {
        super();
        this.containers = containers;
        this._register(mcpWorkbenchService.onChange(this.update, this));
    }
    set mcpServer(extension) {
        this.containers.forEach(c => c.mcpServer = extension);
    }
    update(server) {
        for (const container of this.containers) {
            if (server && container.mcpServer) {
                if (server.id === container.mcpServer.id) {
                    container.mcpServer = server;
                }
            } else {
                container.update();
            }
        }
    }
};
McpServerContainers = ( __decorate([( __param(1, IMcpWorkbenchService))], McpServerContainers));
const McpServersGalleryStatusContext = ( new RawContextKey("mcpServersGalleryStatus", McpGalleryManifestStatus.Unavailable));
const HasInstalledMcpServersContext = ( new RawContextKey("hasInstalledMcpServers", true));
const InstalledMcpServersViewId = "workbench.views.mcp.installed";
var McpResourceURI;
(function(McpResourceURI) {
    McpResourceURI.scheme = "mcp-resource";
    const emptyAuthorityPlaceholder = "dylo78gyp";
    function fromServer(def, resourceURI) {
        if (typeof resourceURI === "string") {
            resourceURI = ( URI.parse(resourceURI));
        }
        return resourceURI.with({
            scheme: McpResourceURI.scheme,
            authority: encodeHex(VSBuffer.fromString(def.id)),
            path: ["", resourceURI.scheme, resourceURI.authority || emptyAuthorityPlaceholder].join("/") + resourceURI.path
        });
    }
    McpResourceURI.fromServer = fromServer;
    function toServer(uri) {
        if (typeof uri === "string") {
            uri = ( URI.parse(uri));
        }
        if (uri.scheme !== McpResourceURI.scheme) {
            throw ( new Error(`Invalid MCP resource URI: ${( uri.toString())}`));
        }
        const parts = uri.path.split("/");
        if (parts.length < 3) {
            throw ( new Error(`Invalid MCP resource URI: ${( uri.toString())}`));
        }
        const [, serverScheme, authority, ...path] = parts;
        const url = ( new URL(
            `${serverScheme}://${authority.toLowerCase() === emptyAuthorityPlaceholder ? "" : authority}`
        ));
        url.pathname = path.length ? ("/" + path.join("/")) : "";
        url.search = uri.query;
        url.hash = uri.fragment;
        return {
            definitionId: ( decodeHex(uri.authority).toString()),
            resourceURL: url
        };
    }
    McpResourceURI.toServer = toServer;
})(McpResourceURI || (McpResourceURI = {}));
var McpCapability;
(function(McpCapability) {
    McpCapability[McpCapability["Logging"] = 1] = "Logging";
    McpCapability[McpCapability["Completions"] = 2] = "Completions";
    McpCapability[McpCapability["Prompts"] = 4] = "Prompts";
    McpCapability[McpCapability["PromptsListChanged"] = 8] = "PromptsListChanged";
    McpCapability[McpCapability["Resources"] = 16] = "Resources";
    McpCapability[McpCapability["ResourcesSubscribe"] = 32] = "ResourcesSubscribe";
    McpCapability[McpCapability["ResourcesListChanged"] = 64] = "ResourcesListChanged";
    McpCapability[McpCapability["Tools"] = 128] = "Tools";
    McpCapability[McpCapability["ToolsListChanged"] = 256] = "ToolsListChanged";
})(McpCapability || (McpCapability = {}));
class McpError extends Error {
    static methodNotFound(method) {
        return ( new McpError(MCP.METHOD_NOT_FOUND, `Method not found: ${method}`));
    }
    static notAllowed() {
        return ( new McpError(-32e3, "The user has denied permission to call this method."));
    }
    static unknown(e) {
        const mcpError = ( new McpError(MCP.INTERNAL_ERROR, `Unknown error: ${e.stack}`));
        mcpError.cause = e;
        return mcpError;
    }
    constructor(code, message, data) {
        super(message);
        this.code = code;
        this.data = data;
    }
}
var McpToolName;
(function(McpToolName) {
    McpToolName["Prefix"] = "mcp_";
    McpToolName[McpToolName["MaxPrefixLen"] = 18] = "MaxPrefixLen";
    McpToolName[McpToolName["MaxLength"] = 64] = "MaxLength";
})(McpToolName || (McpToolName = {}));
var ElicitationKind;
(function(ElicitationKind) {
    ElicitationKind[ElicitationKind["Form"] = 0] = "Form";
    ElicitationKind[ElicitationKind["URL"] = 1] = "URL";
})(ElicitationKind || (ElicitationKind = {}));
const McpToolResourceLinkMimeType = "application/vnd.code.resource-link";

export { ElicitationKind, HasInstalledMcpServersContext, IAutostartResult, InstalledMcpServersViewId, LazyCollectionState, McpCapability, McpCollectionDefinition, McpCollectionSortOrder, McpConnectionFailedError, McpConnectionState, McpError, McpResourceURI, McpServerCacheState, McpServerContainers, McpServerDefinition, McpServerDefinitionVariableReplacement, McpServerEditorTab, McpServerEnablementState, McpServerInstallState, McpServerLaunch, McpServerStaticToolAvailability, McpServerTransportType, McpServerTrust, McpServersGalleryStatusContext, McpStartServerInteraction, McpToolName, McpToolResourceLinkMimeType, McpToolVisibility, MpcResponseError, UserInteractionRequiredError, extensionMcpCollectionPrefix, extensionPrefixedIdentifier, isMcpResourceTemplate, mcpPromptPrefix, mcpPromptReplaceSpecialChars };
