
import { __decorate, __param } from '../../../../../../external/tslib/tslib.es6.js';
import { coalesce } from '../../../base/common/arrays.js';
import { CancellationToken, CancellationTokenSource } from '../../../base/common/cancellation.js';
import { CancellationError } from '../../../base/common/errors.js';
import { Emitter } from '../../../base/common/event.js';
import { Disposable, DisposableStore, toDisposable } from '../../../base/common/lifecycle.js';
import { ResourceSet, ResourceMap } from '../../../base/common/map.js';
import { MarshalledId } from '../../../base/common/marshallingIds.js';
import { equals } from '../../../base/common/objects.js';
import { URI } from '../../../base/common/uri.js';
import { SymbolKind, SymbolKinds } from '../../../editor/common/languages.js';
import { ILogService } from '../../../platform/log/common/log.service.js';
import { IDiagnosticVariableEntryFilterData, PromptFileVariableKind, toPromptFileVariableEntry } from '../../contrib/chat/common/attachments/chatVariableEntries.js';
import { ChatAgentLocation } from '../../contrib/chat/common/constants.js';
import { MainContext } from './extHost.protocol.js';
import { ChatAgentResponseStream } from './extHostChatAgents2.js';
import { IExtHostRpcService } from './extHostRpcService.js';
import { ChatSessionItem, ChatAgentRequest, Location, Diagnostic, ChatResponsePart } from './extHostTypeConverters.js';
import { Disposable as Disposable$1, ChatRequestTurn, ChatReferenceDiagnostic } from './extHostTypes.js';
import { Location as Location$1 } from './extHostTypes/location.js';

class ChatSessionItemImpl {
    #label;
    #iconPath;
    #description;
    #badge;
    #status;
    #archived;
    #tooltip;
    #timing;
    #changes;
    #metadata;
    #onChanged;
    constructor(resource, label, onChanged) {
        this.resource = resource;
        this.#label = label;
        this.#onChanged = onChanged;
    }
    get label() {
        return this.#label;
    }
    set label(value) {
        if (this.#label !== value) {
            this.#label = value;
            this.#onChanged();
        }
    }
    get iconPath() {
        return this.#iconPath;
    }
    set iconPath(value) {
        if (this.#iconPath !== value) {
            this.#iconPath = value;
            this.#onChanged();
        }
    }
    get description() {
        return this.#description;
    }
    set description(value) {
        if (this.#description !== value) {
            this.#description = value;
            this.#onChanged();
        }
    }
    get badge() {
        return this.#badge;
    }
    set badge(value) {
        if (this.#badge !== value) {
            this.#badge = value;
            this.#onChanged();
        }
    }
    get status() {
        return this.#status;
    }
    set status(value) {
        if (this.#status !== value) {
            this.#status = value;
            this.#onChanged();
        }
    }
    get archived() {
        return this.#archived;
    }
    set archived(value) {
        if (this.#archived !== value) {
            this.#archived = value;
            this.#onChanged();
        }
    }
    get tooltip() {
        return this.#tooltip;
    }
    set tooltip(value) {
        if (this.#tooltip !== value) {
            this.#tooltip = value;
            this.#onChanged();
        }
    }
    get timing() {
        return this.#timing;
    }
    set timing(value) {
        if (this.#timing !== value) {
            this.#timing = value;
            this.#onChanged();
        }
    }
    get changes() {
        return this.#changes;
    }
    set changes(value) {
        if (this.#changes !== value) {
            this.#changes = value;
            this.#onChanged();
        }
    }
    get metadata() {
        return this.#metadata;
    }
    set metadata(value) {
        if (value !== undefined) {
            try {
                JSON.stringify(value);
            } catch {
                throw ( new Error("metadata must be JSON-serializable"));
            }
        }
        if (!equals(this.#metadata, value)) {
            this.#metadata = value;
            this.#onChanged();
        }
    }
}
function computeItemsDelta(oldItems, newItems) {
    const delta = {
        addedOrUpdated: ( new ResourceMap()),
        removed: ( new ResourceSet())
    };
    for (const [newResource, newItem] of newItems) {
        const oldItem = oldItems.get(newResource);
        if (oldItem !== newItem) {
            delta.addedOrUpdated.set(newResource, newItem);
        }
    }
    for (const oldResource of ( oldItems.keys())) {
        if (!( newItems.has(oldResource))) {
            delta.removed.add(oldResource);
        }
    }
    return delta;
}
function convertChatSessionDeltaToDto(delta) {
    return {
        addedOrUpdated: delta.addedOrUpdated ? Array.from(( delta.addedOrUpdated.values()), ChatSessionItem.from) : [],
        removed: delta.removed ? Array.from(( delta.removed.keys())) : []
    };
}
class ChatSessionItemCollectionImpl {
    #items = ( new ResourceMap());
    #proxy;
    #controllerHandle;
    constructor(controllerHandle, proxy) {
        this.#proxy = proxy;
        this.#controllerHandle = controllerHandle;
    }
    get size() {
        return this.#items.size;
    }
    replace(newItems) {
        if (!newItems.length && !this.#items.size) {
            return;
        }
        const newItemsMap = ( new ResourceMap(( newItems.map(item => [item.resource, item]))));
        const delta = computeItemsDelta(this.#items, newItemsMap);
        if (!delta.addedOrUpdated?.size && !delta.removed?.size) {
            return;
        }
        this.#items = newItemsMap;
        void this.#proxy.$updateChatSessionItems(this.#controllerHandle, convertChatSessionDeltaToDto(delta));
    }
    forEach(callback, thisArg) {
        for (const [_, item] of this.#items) {
            callback.call(thisArg, item, this);
        }
    }
    add(item) {
        const existing = this.#items.get(item.resource);
        if (existing && existing === item) {
            return;
        }
        this.#items.set(item.resource, item);
        void this.#proxy.$addOrUpdateChatSessionItem(this.#controllerHandle, ChatSessionItem.from(item));
    }
    delete(resource) {
        if (this.#items.delete(resource)) {
            void this.#proxy.$updateChatSessionItems(this.#controllerHandle, {
                addedOrUpdated: [],
                removed: [resource]
            });
        }
    }
    get(resource) {
        return this.#items.get(resource);
    }
    [Symbol.iterator]() {
        return this.#items.entries();
    }
}
class ExtHostChatSession {
    constructor(session, extension, request, proxy, commandsConverter, sessionDisposables) {
        this.session = session;
        this.extension = extension;
        this.proxy = proxy;
        this.commandsConverter = commandsConverter;
        this.sessionDisposables = sessionDisposables;
        this._pendingCarouselResolvers = ( new Map());
        this._stream = ( new ChatAgentResponseStream(
            extension,
            request,
            proxy,
            commandsConverter,
            sessionDisposables,
            this._pendingCarouselResolvers,
            CancellationToken.None
        ));
    }
    get activeResponseStream() {
        return this._stream;
    }
    getActiveRequestStream(request) {
        return ( new ChatAgentResponseStream(
            this.extension,
            request,
            this.proxy,
            this.commandsConverter,
            this.sessionDisposables,
            this._pendingCarouselResolvers,
            CancellationToken.None
        ));
    }
}
let ExtHostChatSessions = class ExtHostChatSessions extends Disposable {
    constructor(commands, _languageModels, _extHostRpc, _logService) {
        super();
        this.commands = commands;
        this._languageModels = _languageModels;
        this._extHostRpc = _extHostRpc;
        this._logService = _logService;
        this._itemControllerHandlePool = 0;
        this._chatSessionItemControllers = ( new Map());
        this._contentProviderHandlePool = 0;
        this._chatSessionContentProviders = ( new Map());
        this._extHostChatSessions = ( new ResourceMap());
        this._providerOptionGroups = ( new Map());
        this._proxy = ( this._extHostRpc.getProxy(MainContext.MainThreadChatSessions));
        commands.registerArgumentProcessor({
            processArgument: arg => {
                if (arg && arg.$mid === MarshalledId.AgentSessionContext) {
                    const resource = arg.session.resource;
                    for (const {
                        controller
                    } of ( this._chatSessionItemControllers.values())) {
                        const item = controller.items.get(resource);
                        if (item) {
                            return item;
                        }
                    }
                    this._logService.warn(`No chat session found with uri: ${resource}`);
                    return arg;
                }
                return arg;
            }
        });
    }
    registerChatSessionItemProvider(extension, chatSessionType, provider) {
        const controllerHandle = this._itemControllerHandlePool++;
        const disposables = ( new DisposableStore());
        const onDidChangeChatSessionItemStateEmitter = disposables.add(( new Emitter()));
        const collection = ( new ChatSessionItemCollectionImpl(controllerHandle, this._proxy));
        const controller = {
            id: chatSessionType,
            items: collection,
            createChatSessionItem: (_resource, _label) => {
                throw ( new Error("Not implemented for providers"));
            },
            onDidChangeChatSessionItemState: onDidChangeChatSessionItemStateEmitter.event,
            newChatSessionItemHandler: undefined,
            dispose: () => {
                disposables.dispose();
            },
            refreshHandler: async token => {
                const items = (await provider.provideChatSessionItems(token)) ?? [];
                collection.replace(items);
            }
        };
        this._chatSessionItemControllers.set(controllerHandle, {
            chatSessionType: chatSessionType,
            controller,
            extension,
            disposable: disposables,
            onDidChangeChatSessionItemStateEmitter
        });
        this._proxy.$registerChatSessionItemController(controllerHandle, chatSessionType);
        if (provider.onDidChangeChatSessionItems) {
            disposables.add(provider.onDidChangeChatSessionItems(() => {
                this._logService.trace(`ExtHostChatSessions. Provider items changed for ${chatSessionType}`);
                controller.refreshHandler(CancellationToken.None);
            }));
        }
        if (provider.onDidCommitChatSessionItem) {
            disposables.add(provider.onDidCommitChatSessionItem(e => {
                const {
                    original,
                    modified
                } = e;
                this._proxy.$onDidCommitChatSessionItem(controllerHandle, original.resource, modified.resource);
            }));
        }
        return {
            dispose: () => {
                this._chatSessionItemControllers.delete(controllerHandle);
                disposables.dispose();
                this._proxy.$unregisterChatSessionItemController(controllerHandle);
            }
        };
    }
    createChatSessionItemController(extension, id, refreshHandler) {
        const controllerHandle = this._itemControllerHandlePool++;
        const disposables = ( new DisposableStore());
        let isDisposed = false;
        let newChatSessionItemHandler;
        let forkHandler;
        const onDidChangeChatSessionItemStateEmitter = disposables.add(( new Emitter()));
        const collection = ( new ChatSessionItemCollectionImpl(controllerHandle, this._proxy));
        const controller = ( Object.freeze({
            id,
            refreshHandler: async refreshToken => {
                if (isDisposed) {
                    throw ( new Error("ChatSessionItemController has been disposed"));
                }
                this._logService.trace(`ExtHostChatSessions. Controller(${id}).refresh()`);
                await refreshHandler(refreshToken);
            },
            items: collection,
            onDidChangeChatSessionItemState: onDidChangeChatSessionItemStateEmitter.event,
            createChatSessionItem: (resource, label) => {
                if (isDisposed) {
                    throw ( new Error("ChatSessionItemController has been disposed"));
                }
                const item = ( new ChatSessionItemImpl(resource, label, () => {
                    if (collection.get(resource) === item) {
                        void this._proxy.$addOrUpdateChatSessionItem(controllerHandle, ChatSessionItem.from(item));
                    }
                }));
                return item;
            },
            get newChatSessionItemHandler() {
                return newChatSessionItemHandler;
            },
            set newChatSessionItemHandler(handler) {
                newChatSessionItemHandler = handler;
            },
            get forkHandler() {
                return forkHandler;
            },
            set forkHandler(handler) {
                forkHandler = handler;
            },
            dispose: () => {
                isDisposed = true;
                disposables.dispose();
            }
        }));
        this._chatSessionItemControllers.set(controllerHandle, {
            controller,
            extension,
            disposable: disposables,
            chatSessionType: id,
            onDidChangeChatSessionItemStateEmitter
        });
        this._proxy.$registerChatSessionItemController(controllerHandle, id);
        disposables.add(toDisposable(() => {
            this._chatSessionItemControllers.delete(controllerHandle);
            this._proxy.$unregisterChatSessionItemController(controllerHandle);
        }));
        return controller;
    }
    registerChatSessionContentProvider(extension, chatSessionScheme, chatParticipant, provider, capabilities) {
        const handle = this._contentProviderHandlePool++;
        const disposables = ( new DisposableStore());
        this._chatSessionContentProviders.set(handle, {
            provider,
            extension,
            capabilities,
            disposable: disposables
        });
        this._proxy.$registerChatSessionContentProvider(handle, chatSessionScheme);
        if (provider.onDidChangeChatSessionOptions) {
            disposables.add(provider.onDidChangeChatSessionOptions(evt => {
                const updates = Object.create(null);
                for (const update of evt.updates) {
                    updates[update.optionId] = update.value;
                }
                this._proxy.$onDidChangeChatSessionOptions(handle, evt.resource, updates);
            }));
        }
        if (provider.onDidChangeChatSessionProviderOptions) {
            disposables.add(provider.onDidChangeChatSessionProviderOptions(() => {
                this._proxy.$onDidChangeChatSessionProviderOptions(handle);
            }));
        }
        return new Disposable$1(() => {
            this._chatSessionContentProviders.delete(handle);
            disposables.dispose();
            this._proxy.$unregisterChatSessionContentProvider(handle);
        });
    }
    async $provideChatSessionContent(handle, sessionResourceComponents, context, token) {
        const provider = this._chatSessionContentProviders.get(handle);
        if (!provider) {
            throw ( new Error(`No provider for handle ${handle}`));
        }
        const sessionResource = URI.revive(sessionResourceComponents);
        const session = await provider.provider.provideChatSessionContent(sessionResource, token, {
            sessionOptions: context?.initialSessionOptions ?? []
        });
        if (token.isCancellationRequested) {
            throw ( new CancellationError());
        }
        const controllerData = this.getChatSessionItemController(sessionResource.scheme);
        const sessionDisposables = ( new DisposableStore());
        const id = ( sessionResource.toString());
        const chatSession = ( new ExtHostChatSession(session, provider.extension, {
            sessionResource,
            requestId: "ongoing",
            agentId: id,
            message: "",
            variables: {
                variables: []
            },
            location: ChatAgentLocation.Chat
        }, {
            $handleProgressChunk: (requestId, chunks) => {
                return this._proxy.$handleProgressChunk(handle, sessionResource, requestId, chunks);
            },
            $handleAnchorResolve: (requestId, requestHandle, anchor) => {
                this._proxy.$handleAnchorResolve(handle, sessionResource, requestId, requestHandle, anchor);
            }
        }, this.commands.converter, sessionDisposables));
        const disposeCts = sessionDisposables.add(( new CancellationTokenSource()));
        this._extHostChatSessions.set(sessionResource, {
            sessionObj: chatSession,
            disposeCts
        });
        if (session.activeResponseCallback) {
            Promise.resolve(
                session.activeResponseCallback(chatSession.activeResponseStream.apiObject, disposeCts.token)
            ).finally(() => {
                this._proxy.$handleProgressComplete(handle, sessionResource, "ongoing");
            });
        }
        const {
            capabilities
        } = provider;
        return {
            resource: URI.revive(sessionResource),
            title: session.title,
            hasActiveResponseCallback: !!session.activeResponseCallback,
            hasRequestHandler: !!session.requestHandler,
            hasForkHandler: !!controllerData?.controller.forkHandler || !!session.forkHandler,
            supportsInterruption: !!capabilities?.supportsInterruptions,
            options: session.options,
            history: ( session.history.map(turn => {
                if (turn instanceof ChatRequestTurn) {
                    return this.convertRequestTurn(turn);
                } else {
                    return this.convertResponseTurn(turn, sessionDisposables);
                }
            }))
        };
    }
    async $provideHandleOptionsChange(handle, sessionResourceComponents, updates, token) {
        const sessionResource = URI.revive(sessionResourceComponents);
        const provider = this._chatSessionContentProviders.get(handle);
        if (!provider) {
            this._logService.warn(`No provider for handle ${handle}`);
            return;
        }
        if (!provider.provider.provideHandleOptionsChange) {
            this._logService.debug(
                `Provider for handle ${handle} does not implement provideHandleOptionsChange`
            );
            return;
        }
        try {
            const updatesToSend = ( Object.entries(updates).map(([optionId, value]) => ({
                optionId,
                value: value === undefined ? undefined : (typeof value === "string" ? value : value.id)
            })));
            provider.provider.provideHandleOptionsChange(sessionResource, updatesToSend, token);
        } catch (error) {
            this._logService.error(
                `Error calling provideHandleOptionsChange for handle ${handle}, sessionResource ${sessionResource}:`,
                error
            );
        }
    }
    async $provideChatSessionProviderOptions(handle, token) {
        const entry = this._chatSessionContentProviders.get(handle);
        if (!entry) {
            this._logService.warn(`No provider for handle ${handle} when requesting chat session options`);
            return;
        }
        const provider = entry.provider;
        if (!provider.provideChatSessionProviderOptions) {
            return;
        }
        try {
            const result = await provider.provideChatSessionProviderOptions(token);
            if (!result) {
                return;
            }
            const {
                optionGroups,
                newSessionOptions
            } = result;
            if (optionGroups) {
                this._providerOptionGroups.set(handle, optionGroups);
            }
            return {
                optionGroups,
                newSessionOptions
            };
        } catch (error) {
            this._logService.error(
                `Error calling provideChatSessionProviderOptions for handle ${handle}:`,
                error
            );
            return;
        }
    }
    async $interruptChatSessionActiveResponse(providerHandle, sessionResource, requestId) {
        const entry = this._extHostChatSessions.get(URI.revive(sessionResource));
        entry?.disposeCts.cancel();
    }
    async $disposeChatSessionContent(providerHandle, sessionResource) {
        const entry = this._extHostChatSessions.get(URI.revive(sessionResource));
        if (!entry) {
            this._logService.warn(`No chat session found for resource: ${sessionResource}`);
            return;
        }
        entry.disposeCts.cancel();
        entry.sessionObj.sessionDisposables.dispose();
        this._extHostChatSessions.delete(URI.revive(sessionResource));
    }
    async $invokeChatSessionRequestHandler(handle, sessionResource, request, history, token) {
        const entry = this._extHostChatSessions.get(URI.revive(sessionResource));
        if (!entry || !entry.sessionObj.session.requestHandler) {
            return {};
        }
        const chatRequest = ChatAgentRequest.to(
            request,
            undefined,
            await this.getModelForRequest(request, entry.sessionObj.extension),
            request.modelConfiguration,
            [],
            ( new Map()),
            entry.sessionObj.extension,
            this._logService
        );
        const stream = entry.sessionObj.getActiveRequestStream(request);
        await entry.sessionObj.session.requestHandler(chatRequest, {
            history,
            yieldRequested: false
        }, stream.apiObject, token);
        return {};
    }
    async $forkChatSession(handle, sessionResourceComponents, request, token) {
        const sessionResource = URI.revive(sessionResourceComponents);
        const entry = this._extHostChatSessions.get(sessionResource);
        if (!entry) {
            throw ( new Error(`No chat session found for resource ${( sessionResource.toString())}`));
        }
        const requestTurn = this.convertRequestDtoToRequestTurn(request);
        const controllerData = this.getChatSessionItemController(sessionResource.scheme);
        if (controllerData?.controller.forkHandler) {
            const item = await controllerData.controller.forkHandler(sessionResource, requestTurn, token);
            return ChatSessionItem.from(item);
        }
        if (!entry.sessionObj.session.forkHandler) {
            throw ( new Error(`No fork handler for session ${( sessionResource.toString())}`));
        }
        const item = await entry.sessionObj.session.forkHandler(sessionResource, requestTurn, token);
        return ChatSessionItem.from(item);
    }
    convertRequestDtoToRequestTurn(request) {
        if (!request) {
            return undefined;
        }
        return new ChatRequestTurn(
            request.prompt,
            request.command,
            [],
            request.participant,
            [],
            undefined,
            request.id,
            request.modelId
        );
    }
    getChatSessionItemController(chatSessionType) {
        for (const controllerData of ( this._chatSessionItemControllers.values())) {
            if (controllerData.chatSessionType === chatSessionType) {
                return controllerData;
            }
        }
        return undefined;
    }
    async getModelForRequest(request, extension) {
        let model;
        if (request.userSelectedModelId) {
            model = await this._languageModels.getLanguageModelByIdentifier(extension, request.userSelectedModelId);
        }
        if (!model) {
            model = await this._languageModels.getDefaultLanguageModel(extension);
            if (!model) {
                throw ( new Error("Language model unavailable"));
            }
        }
        return model;
    }
    convertRequestTurn(turn) {
        const variables = ( turn.references.map(ref => this.convertReferenceToVariable(ref)));
        return {
            type: "request",
            id: turn.id,
            prompt: turn.prompt,
            participant: turn.participant,
            command: turn.command,
            variableData: variables.length > 0 ? {
                variables
            } : undefined,
            modelId: turn.modelId
        };
    }
    convertReferenceToVariable(ref) {
        const value = ref.value && typeof ref.value === "object" && "uri" in ref.value && "range" in ref.value ? Location.from(ref.value) : ref.value;
        const range = ref.range ? {
            start: ref.range[0],
            endExclusive: ref.range[1]
        } : undefined;
        if (value && value instanceof ChatReferenceDiagnostic && Array.isArray(value.diagnostics) && value.diagnostics.length && value.diagnostics[0][1].length) {
            const marker = Diagnostic.from(value.diagnostics[0][1][0]);
            const refValue = {
                filterRange: {
                    startLineNumber: marker.startLineNumber,
                    startColumn: marker.startColumn,
                    endLineNumber: marker.endLineNumber,
                    endColumn: marker.endColumn
                },
                filterSeverity: marker.severity,
                filterUri: value.diagnostics[0][0],
                problemMessage: value.diagnostics[0][1][0].message
            };
            return IDiagnosticVariableEntryFilterData.toEntry(refValue);
        }
        if (Location$1.isLocation(ref.value) && ref.name.startsWith(`sym:`)) {
            const loc = Location.from(ref.value);
            return {
                id: ref.id,
                name: ref.name,
                fullName: ref.name.substring(4),
                value: {
                    uri: ref.value.uri,
                    range: loc.range
                },
                symbolKind: SymbolKind.Property,
                icon: SymbolKinds.toIcon(SymbolKind.Property),
                kind: "symbol",
                range
            };
        }
        if (URI.isUri(value) && ref.name.startsWith(`prompt:`)) {
            if (ref.id.startsWith(PromptFileVariableKind.Instruction)) {
                return toPromptFileVariableEntry(value, PromptFileVariableKind.Instruction);
            }
            if (ref.id.startsWith(PromptFileVariableKind.InstructionReference)) {
                return toPromptFileVariableEntry(value, PromptFileVariableKind.InstructionReference);
            }
            if (ref.id.startsWith(PromptFileVariableKind.PromptFile)) {
                return toPromptFileVariableEntry(value, PromptFileVariableKind.PromptFile);
            }
        }
        const isFile = URI.isUri(value) || (value && typeof value === "object" && "uri" in value);
        const isFolder = isFile && URI.isUri(value) && value.path.endsWith("/");
        return {
            id: ref.id,
            name: ref.name,
            value,
            modelDescription: ref.modelDescription,
            range,
            kind: isFolder ? "directory" : isFile ? "file" : "generic"
        };
    }
    convertResponseTurn(turn, sessionDisposables) {
        const parts = coalesce(( turn.response.map(
            r => ChatResponsePart.from(r, this.commands.converter, sessionDisposables)
        )));
        return {
            type: "response",
            parts,
            participant: turn.participant
        };
    }
    async $invokeOptionGroupSearch(providerHandle, optionGroupId, query, token) {
        const optionGroups = this._providerOptionGroups.get(providerHandle);
        if (!optionGroups) {
            this._logService.warn(`No option groups found for provider handle ${providerHandle}`);
            return [];
        }
        const group = optionGroups.find(g => g.id === optionGroupId);
        if (!group || !group.onSearch) {
            this._logService.warn(`No onSearch callback found for option group ${optionGroupId}`);
            return [];
        }
        try {
            const results = await group.onSearch(query, token);
            return results ?? [];
        } catch (error) {
            this._logService.error(`Error calling onSearch for option group ${optionGroupId}:`, error);
            return [];
        }
    }
    async $refreshChatSessionItems(handle, token) {
        const controllerData = this._chatSessionItemControllers.get(handle);
        if (!controllerData) {
            this._logService.warn(`No controller found for handle ${handle}`);
            return;
        }
        await controllerData.controller.refreshHandler(token);
    }
    async $newChatSessionItem(handle, request, token) {
        const controllerData = this._chatSessionItemControllers.get(handle);
        if (!controllerData) {
            this._logService.warn(`No controller found for handle ${handle}`);
            return undefined;
        }
        const handler = controllerData.controller.newChatSessionItemHandler;
        if (!handler) {
            return undefined;
        }
        const item = await handler({
            request: {
                prompt: request.prompt,
                command: request.command
            },
            sessionOptions: request.initialSessionOptions ?? []
        }, token);
        if (!item) {
            return undefined;
        }
        return ChatSessionItem.from(item);
    }
    $onDidChangeChatSessionItemState(controllerHandle, sessionResourceComponents, archived) {
        const controllerData = this._chatSessionItemControllers.get(controllerHandle);
        if (!controllerData) {
            this._logService.warn(`No controller found for handle ${controllerHandle}`);
            return;
        }
        const sessionResource = URI.revive(sessionResourceComponents);
        const item = controllerData.controller.items.get(sessionResource);
        if (!item) {
            this._logService.warn(`No item found for session resource ${( sessionResource.toString())}`);
            return;
        }
        item.archived = archived;
        controllerData.onDidChangeChatSessionItemStateEmitter.fire(item);
    }
};
ExtHostChatSessions = ( __decorate([( __param(2, IExtHostRpcService)), ( __param(3, ILogService))], ExtHostChatSessions));

export { ExtHostChatSessions };
