/*!--------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*/
/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

export function __extends(d, b) {
    if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

export var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

export function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

export function __decorate(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;
}

export function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};

export function __runInitializers(thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};

export function __propKey(x) {
    return typeof x === "symbol" ? x : "".concat(x);
};

export function __setFunctionName(f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};

export function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

export function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

export function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

export var __createBinding = Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
});

export function __exportStar(m, o) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}

export function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

export function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

/** @deprecated */
export function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

/** @deprecated */
export function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
}

export function __spreadArray(to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
}

export function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

export function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

export function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}

export function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

export function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
};

export function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
}

export function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

export function __classPrivateFieldGet(receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

export function __classPrivateFieldSet(receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

export function __classPrivateFieldIn(state, receiver) {
    if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
    return typeof state === "function" ? receiver === state : state.has(receiver);
}

export function __addDisposableResource(env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;

}

var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

export function __disposeResources(env) {
    function fail(e) {
        env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
        env.hasError = true;
    }
    function next() {
        while (env.stack.length) {
            var rec = env.stack.pop();
            try {
                var result = rec.dispose && rec.dispose.call(rec.value);
                if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
            }
            catch (e) {
                fail(e);
            }
        }
        if (env.hasError) throw env.error;
    }
    return next();
}

export default {
    __extends: __extends,
    __assign: __assign,
    __rest: __rest,
    __decorate: __decorate,
    __param: __param,
    __metadata: __metadata,
    __awaiter: __awaiter,
    __generator: __generator,
    __createBinding: __createBinding,
    __exportStar: __exportStar,
    __values: __values,
    __read: __read,
    __spread: __spread,
    __spreadArrays: __spreadArrays,
    __spreadArray: __spreadArray,
    __await: __await,
    __asyncGenerator: __asyncGenerator,
    __asyncDelegator: __asyncDelegator,
    __asyncValues: __asyncValues,
    __makeTemplateObject: __makeTemplateObject,
    __importStar: __importStar,
    __importDefault: __importDefault,
    __classPrivateFieldGet: __classPrivateFieldGet,
    __classPrivateFieldSet: __classPrivateFieldSet,
    __classPrivateFieldIn: __classPrivateFieldIn,
    __addDisposableResource: __addDisposableResource,
    __disposeResources: __disposeResources,
};

var gg=Object.defineProperty;var mg=Object.getOwnPropertyDescriptor;var O=(i,t,e,n)=>{for(var r=n>1?void 0:n?mg(t,e):t,o=i.length-1,s;o>=0;o--)(s=i[o])&&(r=(n?s(t,e,r):s(r))||r);return n&&r&&gg(t,e,r),r},K=(i,t)=>(e,n)=>t(e,n,i);function hg(i,t,e=0,n=i.length){let r=e,o=n;for(;r<o;){let s=Math.floor((r+o)/2);t(i[s])?r=s+1:o=s}return r-1}var $c=class i{constructor(t){this._array=t;this._findLastMonotonousLastIdx=0}static{this.assertInvariants=!1}findLastMonotonous(t){if(i.assertInvariants){if(this._prevFindLastPredicate){for(let n of this._array)if(this._prevFindLastPredicate(n)&&!t(n))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=t}let e=hg(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=e+1,e===-1?void 0:this._array[e]}};var Sa=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(t){setTimeout(()=>{throw t.stack?vt.isErrorNoTelemetry(t)?new vt(t.message+`

`+t.stack):new Error(t.message+`

`+t.stack):t},0)}}addListener(t){return this.listeners.push(t),()=>{this._removeListener(t)}}emit(t){this.listeners.forEach(e=>{e(t)})}_removeListener(t){this.listeners.splice(this.listeners.indexOf(t),1)}setUnexpectedErrorHandler(t){this.unexpectedErrorHandler=t}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(t){this.unexpectedErrorHandler(t),this.emit(t)}onUnexpectedExternalError(t){this.unexpectedErrorHandler(t)}},qc=new Sa;function Jt(i){qc.onUnexpectedError(i)}function fe(i){vg(i)||qc.onUnexpectedError(i)}var Zi="Canceled";function vg(i){return i instanceof Ae?!0:i instanceof Error&&i.name===Zi&&i.message===Zi}var Ae=class extends Error{constructor(){super(Zi),this.name=this.message}},Vc=class i extends Error{static{this._name="PendingMigrationError"}static is(t){return t instanceof i||t instanceof Error&&t.name===i._name}constructor(t){super(t),this.name=i._name}};function eo(){let i=new Error(Zi);return i.name=i.message,i}function to(i){return i?new Error(`Illegal state: ${i}`):new Error("Illegal state")}var vt=class i extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof i)return t;let e=new i;return e.message=t.message,e.stack=t.stack,e}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},ae=class i extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,i.prototype)}};function Jr(i,t,e=(n,r)=>n===r){if(i===t)return!0;if(!i||!t||i.length!==t.length)return!1;for(let n=0,r=i.length;n<r;n++)if(!e(i[n],t[n]))return!1;return!0}function no(i){return i.filter(t=>!!t)}function Ta(i,t){return i.push(t),()=>bg(i,t)}function bg(i,t){let e=i.indexOf(t);if(e>-1)return i.splice(e,1),t}function xa(i,t){let e;if(typeof t=="number"){let n=t;e=()=>{let r=Math.sin(n++)*179426549;return r-Math.floor(r)}}else e=Math.random;for(let n=i.length-1;n>0;n-=1){let r=Math.floor(e()*(n+1)),o=i[n];i[n]=i[r],i[r]=o}}function jc(i){return i[Math.floor(Math.random()*i.length)]}var Hc;(a=>{function i(l){return l<0}a.isLessThan=i;function t(l){return l<=0}a.isLessThanOrEqual=t;function e(l){return l>0}a.isGreaterThan=e;function n(l){return l===0}a.isNeitherLessOrGreaterThan=n,a.greaterThan=1,a.lessThan=-1,a.neitherLessOrGreaterThan=0})(Hc||={});function Gc(i,t){return(e,n)=>t(i(e),i(n))}var Jc=(i,t)=>i-t;var zc=class i{constructor(t){this.iterate=t}static{this.empty=new i(t=>{})}forEach(t){this.iterate(e=>(t(e),!0))}toArray(){let t=[];return this.iterate(e=>(t.push(e),!0)),t}filter(t){return new i(e=>this.iterate(n=>t(n)?e(n):!0))}map(t){return new i(e=>this.iterate(n=>e(t(n))))}some(t){let e=!1;return this.iterate(n=>(e=t(n),!e)),e}findFirst(t){let e;return this.iterate(n=>t(n)?(e=n,!1):!0),e}findLast(t){let e;return this.iterate(n=>(t(n)&&(e=n),!0)),e}findLastMaxBy(t){let e,n=!0;return this.iterate(r=>((n||Hc.isGreaterThan(t(r,e)))&&(n=!1,e=r),!0)),e}};function ed(i,t){let e=Object.create(null);for(let n of i){let r=t(n),o=e[r];o||(o=e[r]=[]),o.push(n)}return e}var Xc,Zc,Yc=class{constructor(t,e){this.toKey=e;this._map=new Map;this[Xc]="SetWithKey";for(let n of t)this.add(n)}get size(){return this._map.size}add(t){let e=this.toKey(t);return this._map.set(e,t),this}delete(t){return this._map.delete(this.toKey(t))}has(t){return this._map.has(this.toKey(t))}*entries(){for(let t of this._map.values())yield[t,t]}keys(){return this.values()}*values(){for(let t of this._map.values())yield t}clear(){this._map.clear()}forEach(t,e){this._map.forEach(n=>t.call(e,n,n,this))}[(Zc=Symbol.iterator,Xc=Symbol.toStringTag,Zc)](){return this.values()}};function zn(i,t){let e=this,n=!1,r;return function(){if(n)return r;if(n=!0,t)try{r=i.apply(e,arguments)}finally{t()}else r=i.apply(e,arguments);return r}}var _a=class{constructor(t,e){this.uri=t;this.value=e}};function yg(i){return Array.isArray(i)}var nd,ut=class i{constructor(t,e){this[nd]="ResourceMap";if(t instanceof i)this.map=new Map(t.map),this.toKey=e??i.defaultToKey;else if(yg(t)){this.map=new Map,this.toKey=e??i.defaultToKey;for(let[n,r]of t)this.set(n,r)}else this.map=new Map,this.toKey=t??i.defaultToKey}static{this.defaultToKey=t=>t.toString()}set(t,e){return this.map.set(this.toKey(t),new _a(t,e)),this}get(t){return this.map.get(this.toKey(t))?.value}has(t){return this.map.has(this.toKey(t))}get size(){return this.map.size}clear(){this.map.clear()}delete(t){return this.map.delete(this.toKey(t))}forEach(t,e){typeof e<"u"&&(t=t.bind(e));for(let[n,r]of this.map)t(r.value,r.uri,this)}*values(){for(let t of this.map.values())yield t.value}*keys(){for(let t of this.map.values())yield t.uri}*entries(){for(let t of this.map.values())yield[t.uri,t.value]}*[(nd=Symbol.toStringTag,Symbol.iterator)](){for(let[,t]of this.map)yield[t.uri,t.value]}},rd,td=class{constructor(t,e){this[rd]="ResourceSet";!t||typeof t=="function"?this._map=new ut(t):(this._map=new ut(e),t.forEach(this.add,this))}get size(){return this._map.size}add(t){return this._map.set(t,t),this}clear(){this._map.clear()}delete(t){return this._map.delete(t)}forEach(t,e){this._map.forEach((n,r)=>t.call(e,r,r,this))}has(t){return this._map.has(t)}entries(){return this._map.entries()}keys(){return this._map.keys()}values(){return this._map.keys()}[(rd=Symbol.toStringTag,Symbol.iterator)](){return this.keys()}};var id,Ea=class{constructor(){this[id]="LinkedMap";this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(t){return this._map.has(t)}get(t,e=0){let n=this._map.get(t);if(n)return e!==0&&this.touch(n,e),n.value}set(t,e,n=0){let r=this._map.get(t);if(r)r.value=e,n!==0&&this.touch(r,n);else{switch(r={key:t,value:e,next:void 0,previous:void 0},n){case 0:this.addItemLast(r);break;case 1:this.addItemFirst(r);break;case 2:this.addItemLast(r);break;default:this.addItemLast(r);break}this._map.set(t,r),this._size++}return this}delete(t){return!!this.remove(t)}remove(t){let e=this._map.get(t);if(e)return this._map.delete(t),this.removeItem(e),this._size--,e.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let t=this._head;return this._map.delete(t.key),this.removeItem(t),this._size--,t.value}forEach(t,e){let n=this._state,r=this._head;for(;r;){if(e?t.bind(e)(r.value,r.key,this):t(r.value,r.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){let t=this,e=this._state,n=this._head,r={[Symbol.iterator](){return r},next(){if(t._state!==e)throw new Error("LinkedMap got modified during iteration.");if(n){let o={value:n.key,done:!1};return n=n.next,o}else return{value:void 0,done:!0}}};return r}values(){let t=this,e=this._state,n=this._head,r={[Symbol.iterator](){return r},next(){if(t._state!==e)throw new Error("LinkedMap got modified during iteration.");if(n){let o={value:n.value,done:!1};return n=n.next,o}else return{value:void 0,done:!0}}};return r}entries(){let t=this,e=this._state,n=this._head,r={[Symbol.iterator](){return r},next(){if(t._state!==e)throw new Error("LinkedMap got modified during iteration.");if(n){let o={value:[n.key,n.value],done:!1};return n=n.next,o}else return{value:void 0,done:!0}}};return r}[(id=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(t){if(t>=this.size)return;if(t===0){this.clear();return}let e=this._head,n=this.size;for(;e&&n>t;)this._map.delete(e.key),e=e.next,n--;this._head=e,this._size=n,e&&(e.previous=void 0),this._state++}trimNew(t){if(t>=this.size)return;if(t===0){this.clear();return}let e=this._tail,n=this.size;for(;e&&n>t;)this._map.delete(e.key),e=e.previous,n--;this._tail=e,this._size=n,e&&(e.next=void 0),this._state++}addItemFirst(t){if(!this._head&&!this._tail)this._tail=t;else if(this._head)t.next=this._head,this._head.previous=t;else throw new Error("Invalid list");this._head=t,this._state++}addItemLast(t){if(!this._head&&!this._tail)this._head=t;else if(this._tail)t.previous=this._tail,this._tail.next=t;else throw new Error("Invalid list");this._tail=t,this._state++}removeItem(t){if(t===this._head&&t===this._tail)this._head=void 0,this._tail=void 0;else if(t===this._head){if(!t.next)throw new Error("Invalid list");t.next.previous=void 0,this._head=t.next}else if(t===this._tail){if(!t.previous)throw new Error("Invalid list");t.previous.next=void 0,this._tail=t.previous}else{let e=t.next,n=t.previous;if(!e||!n)throw new Error("Invalid list");e.previous=n,n.next=e}t.next=void 0,t.previous=void 0,this._state++}touch(t,e){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(e!==1&&e!==2)){if(e===1){if(t===this._head)return;let n=t.next,r=t.previous;t===this._tail?(r.next=void 0,this._tail=r):(n.previous=r,r.next=n),t.previous=void 0,t.next=this._head,this._head.previous=t,this._head=t,this._state++}else if(e===2){if(t===this._tail)return;let n=t.next,r=t.previous;t===this._head?(n.previous=void 0,this._head=n):(n.previous=r,r.next=n),t.next=void 0,t.previous=this._tail,this._tail.next=t,this._tail=t,this._state++}}}toJSON(){let t=[];return this.forEach((e,n)=>{t.push([n,e])}),t}fromJSON(t){this.clear();for(let[e,n]of t)this.set(e,n)}},Ca=class extends Ea{constructor(t,e=1){super(),this._limit=t,this._ratio=Math.min(Math.max(0,e),1)}get limit(){return this._limit}set limit(t){this._limit=t,this.checkTrim()}get ratio(){return this._ratio}set ratio(t){this._ratio=Math.min(Math.max(0,t),1),this.checkTrim()}get(t,e=2){return super.get(t,e)}peek(t){return super.get(t,0)}set(t,e){return super.set(t,e,2),this}checkTrim(){this.size>this._limit&&this.trim(Math.round(this._limit*this._ratio))}},bt=class extends Ca{constructor(t,e=1){super(t,e)}trim(t){this.trimOld(t)}set(t,e){return super.set(t,e),this.checkTrim(),this}};var ro=class{constructor(){this.map=new Map}add(t,e){let n=this.map.get(t);n||(n=new Set,this.map.set(t,n)),n.add(e)}delete(t,e){let n=this.map.get(t);n&&(n.delete(e),n.size===0&&this.map.delete(t))}forEach(t,e){let n=this.map.get(t);n&&n.forEach(e)}get(t){let e=this.map.get(t);return e||new Set}};function io(i,t){if(!i)throw new Error(t?`Assertion failed (${t})`:"Assertion Failed")}function oo(i,t="unexpected state"){if(!i)throw typeof t=="string"?new ae(`Assertion Failed: ${t}`):t}function Qr(i){if(!i()){debugger;i(),fe(new ae("Assertion Failed"))}}function Me(i){return typeof i=="string"}function so(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof RegExp)&&!(i instanceof Date)}function Yr(i){return typeof i=="number"&&!isNaN(i)}function od(i){return!!i&&typeof i[Symbol.iterator]=="function"}function Sg(i){return typeof i>"u"}function jn(i){return!Xr(i)}function Xr(i){return Sg(i)||i===null}function sd(i,t){if(!i)throw new Error(t?`Unexpected type, expected '${t}'`:"Unexpected type")}function Zr(i){return typeof i=="function"}function We(i,t){for(let e in t)if(!(e in i))return!1;return!0}var ei;(rt=>{function i(P){return!!P&&typeof P=="object"&&typeof P[Symbol.iterator]=="function"}rt.is=i;let t=Object.freeze([]);function e(){return t}rt.empty=e;function*n(P){yield P}rt.single=n;function r(P){return i(P)?P:n(P)}rt.wrap=r;function o(P){return P??t}rt.from=o;function*s(P){for(let F=P.length-1;F>=0;F--)yield P[F]}rt.reverse=s;function a(P){return!P||P[Symbol.iterator]().next().done===!0}rt.isEmpty=a;function l(P){return P[Symbol.iterator]().next().value}rt.first=l;function c(P,F){let A=0;for(let Z of P)if(F(Z,A++))return!0;return!1}rt.some=c;function p(P,F){let A=0;for(let Z of P)if(!F(Z,A++))return!1;return!0}rt.every=p;function u(P,F){for(let A of P)if(F(A))return A}rt.find=u;function*f(P,F){for(let A of P)F(A)&&(yield A)}rt.filter=f;function*m(P,F){let A=0;for(let Z of P)yield F(Z,A++)}rt.map=m;function*v(P,F){let A=0;for(let Z of P)yield*F(Z,A++)}rt.flatMap=v;function*h(...P){for(let F of P)od(F)?yield*F:yield F}rt.concat=h;function I(P,F,A){let Z=A;for(let ie of P)Z=F(Z,ie);return Z}rt.reduce=I;function y(P){let F=0;for(let A of P)F++;return F}rt.length=y;function*S(P,F,A=P.length){for(F<-P.length&&(F=0),F<0&&(F+=P.length),A<0?A+=P.length:A>P.length&&(A=P.length);F<A;F++)yield P[F]}rt.slice=S;function C(P,F=Number.POSITIVE_INFINITY){let A=[];if(F===0)return[A,P];let Z=P[Symbol.iterator]();for(let ie=0;ie<F;ie++){let Ue=Z.next();if(Ue.done)return[A,rt.empty()];A.push(Ue.value)}return[A,{[Symbol.iterator](){return Z}}]}rt.consume=C;async function X(P){let F=[];for await(let A of P)F.push(A);return F}rt.asyncToArray=X;async function Fe(P){let F=[];for await(let A of P)F=F.concat(A);return F}rt.asyncToArrayFlat=Fe})(ei||={});var Tg=!1,Hn=null;var ad=class i{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(t){let e=this.livingDisposables.get(t);return e||(e={parent:null,source:null,isSingleton:!1,value:t,idx:i.idx++},this.livingDisposables.set(t,e)),e}trackDisposable(t){let e=this.getDisposableData(t);e.source||(e.source=new Error().stack)}setParent(t,e){let n=this.getDisposableData(t);n.parent=e}markAsDisposed(t){this.livingDisposables.delete(t)}markAsSingleton(t){this.getDisposableData(t).isSingleton=!0}getRootParent(t,e){let n=e.get(t);if(n)return n;let r=t.parent?this.getRootParent(this.getDisposableData(t.parent),e):t;return e.set(t,r),r}getTrackedDisposables(){let t=new Map;return[...this.livingDisposables.entries()].filter(([,n])=>n.source!==null&&!this.getRootParent(n,t).isSingleton).flatMap(([n])=>n)}computeLeakingDisposables(t=10,e){let n;if(e)n=e;else{let l=new Map,c=[...this.livingDisposables.values()].filter(u=>u.source!==null&&!this.getRootParent(u,l).isSingleton);if(c.length===0)return;let p=new Set(c.map(u=>u.value));if(n=c.filter(u=>!(u.parent&&p.has(u.parent))),n.length===0)throw new Error("There are cyclic diposable chains!")}if(!n)return;function r(l){function c(u,f){for(;u.length>0&&f.some(m=>typeof m=="string"?m===u[0]:u[0].match(m));)u.shift()}let p=l.source.split(`
`).map(u=>u.trim().replace("at ","")).filter(u=>u!=="");return c(p,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),p.reverse()}let o=new ro;for(let l of n){let c=r(l);for(let p=0;p<=c.length;p++)o.add(c.slice(0,p).join(`
`),l)}n.sort(Gc(l=>l.idx,Jc));let s="",a=0;for(let l of n.slice(0,t)){a++;let c=r(l),p=[];for(let u=0;u<c.length;u++){let f=c[u];f=`(shared with ${o.get(c.slice(0,u+1).join(`
`)).size}/${n.length} leaks) at ${f}`;let v=o.get(c.slice(0,u).join(`
`)),h=ed([...v].map(I=>r(I)[u]),I=>I);delete h[c[u]];for(let[I,y]of Object.entries(h))y&&p.unshift(`    - stacktraces of ${y.length} other leaks continue with ${I}`);p.unshift(f)}s+=`


==================== Leaking disposable ${a}/${n.length}: ${l.value.constructor.name} ====================
${p.join(`
`)}
============================================================

`}return n.length>t&&(s+=`


... and ${n.length-t} more leaking disposables

`),{leaks:n,details:s}}};function xg(i){Hn=i}if(Tg){let i="__is_disposable_tracked__";xg(new class{trackDisposable(t){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[i]||console.log(e)},3e3)}setParent(t,e){if(t&&t!==L.None)try{t[i]=!0}catch{}}markAsDisposed(t){if(t&&t!==L.None)try{t[i]=!0}catch{}}markAsSingleton(t){}})}function Yt(i){return Hn?.trackDisposable(i),i}function Xt(i){Hn?.markAsDisposed(i)}function bn(i,t){Hn?.setParent(i,t)}function _g(i,t){if(Hn)for(let e of i)Hn.setParent(e,t)}function lo(i){return typeof i=="object"&&i!==null&&typeof i.dispose=="function"&&i.dispose.length===0}function Ke(i){if(ei.is(i)){let t=[];for(let e of i)if(e)try{e.dispose()}catch(n){t.push(n)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function ld(...i){let t=w(()=>Ke(i));return _g(i,t),t}var wa=class{constructor(t){this._isDisposed=!1,this._fn=t,Yt(this)}dispose(){if(!this._isDisposed){if(!this._fn)throw new Error("Unbound disposable context: Need to use an arrow function to preserve the value of this");this._isDisposed=!0,Xt(this),this._fn()}}};function w(i){return new wa(i)}var N=class i{constructor(){this._toDispose=new Set;this._isDisposed=!1;Yt(this)}static{this.DISABLE_DISPOSED_WARNING=!1}dispose(){this._isDisposed||(Xt(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Ke(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t||t===L.None)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return bn(t,this),this._isDisposed?i.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.delete(t)&&bn(t,null)}assertNotDisposed(){this._isDisposed&&fe(new ae("Object disposed"))}},L=class{constructor(){this._store=new N;Yt(this),bn(this._store,this)}static{this.None=Object.freeze({dispose(){}})}dispose(){Xt(this),this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}},Qt=class{constructor(){this._isDisposed=!1;Yt(this)}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),t&&bn(t,this),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Xt(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let t=this._value;return this._value=void 0,t&&bn(t,null),t}};var ao=class{constructor(){this.references=new Map}acquire(t,...e){let n=this.references.get(t);n||(n={counter:0,object:this.createReferencedObject(t,...e)},this.references.set(t,n));let{object:r}=n,o=zn(()=>{--n.counter===0&&(this.destroyReferencedObject(t,n.object),this.references.delete(t))});return n.counter++,{object:r,dispose:o}}};var it=class{constructor(t=new Map){this._isDisposed=!1;this._store=t,Yt(this)}dispose(){Xt(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{Ke(this._store.values())}finally{this._store.clear()}}has(t){return this._store.has(t)}get size(){return this._store.size}get(t){return this._store.get(t)}set(t,e,n=!1){this._isDisposed&&console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),n||this._store.get(t)?.dispose(),this._store.set(t,e),bn(e,this)}deleteAndDispose(t){this._store.get(t)?.dispose(),this._store.delete(t)}deleteAndLeak(t){let e=this._store.get(t);return e&&bn(e,null),this._store.delete(t),e}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}};function cd(i,t){return i.then(e=>(t.isDisposed?e.dispose():t.add(e),e))}var le=class i{static{this.Undefined=new i(void 0)}constructor(t){this.element=t,this.next=i.Undefined,this.prev=i.Undefined}},ti=class{constructor(){this._first=le.Undefined;this._last=le.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===le.Undefined}clear(){let t=this._first;for(;t!==le.Undefined;){let e=t.next;t.prev=le.Undefined,t.next=le.Undefined,t=e}this._first=le.Undefined,this._last=le.Undefined,this._size=0}unshift(t){return this._insert(t,!1)}push(t){return this._insert(t,!0)}_insert(t,e){let n=new le(t);if(this._first===le.Undefined)this._first=n,this._last=n;else if(e){let o=this._last;this._last=n,n.prev=o,o.next=n}else{let o=this._first;this._first=n,n.next=o,o.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==le.Undefined){let t=this._first.element;return this._remove(this._first),t}}pop(){if(this._last!==le.Undefined){let t=this._last.element;return this._remove(this._last),t}}peek(){if(this._last!==le.Undefined)return this._last.element}_remove(t){if(t.prev!==le.Undefined&&t.next!==le.Undefined){let e=t.prev;e.next=t.next,t.next.prev=e}else t.prev===le.Undefined&&t.next===le.Undefined?(this._first=le.Undefined,this._last=le.Undefined):t.next===le.Undefined?(this._last=this._last.prev,this._last.next=le.Undefined):t.prev===le.Undefined&&(this._first=this._first.next,this._first.prev=le.Undefined);this._size-=1}*[Symbol.iterator](){let t=this._first;for(;t!==le.Undefined;)yield t.element,t=t.next}};function Eg(){return globalThis._VSCODE_NLS_MESSAGES}function Pa(){return globalThis._VSCODE_NLS_LANGUAGE}var Cg=Pa()==="pseudo"||typeof document<"u"&&document.location&&typeof document.location.hash=="string"&&document.location.hash.indexOf("pseudo=true")>=0;function dd(i,t){let e;return t.length===0?e=i:e=i.replace(/\{(\d+)\}/g,(n,r)=>{let o=r[0],s=t[o],a=n;return typeof s=="string"?a=s:(typeof s=="number"||typeof s=="boolean"||s===void 0||s===null)&&(a=String(s)),a}),Cg&&(e="\uFF3B"+e.replace(/[aouei]/g,"$&$&")+"\uFF3D"),e}function g(i,t,...e){return dd(typeof i=="number"?Rg(i,t):t,e)}function Rg(i,t){let e=Eg()?.[i];if(typeof e!="string"){if(typeof t=="string")return t;throw new Error(`!!! NLS MISSING: ${i} !!!`)}return e}var yn="en",ri=!1,ii=!1,ni=!1,wg=!1,pd=!1,Da=!1,Pg=!1,fd=!1,Ag=!1,kg=!1,co,uo=yn,ud=yn,Dg,wt,Pt=globalThis,Ge;typeof Pt.vscode<"u"&&typeof Pt.vscode.process<"u"?Ge=Pt.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(Ge=process);var gd=typeof Ge?.versions?.electron=="string",Og=gd&&Ge?.type==="renderer";if(typeof Ge=="object"){ri=Ge.platform==="win32",ii=Ge.platform==="darwin",ni=Ge.platform==="linux",wg=ni&&!!Ge.env.SNAP&&!!Ge.env.SNAP_REVISION,Pg=gd,Ag=!!Ge.env.CI||!!Ge.env.BUILD_ARTIFACTSTAGINGDIRECTORY||!!Ge.env.GITHUB_WORKSPACE,co=yn,uo=yn;let i=Ge.env.VSCODE_NLS_CONFIG;if(i)try{let t=JSON.parse(i);co=t.userLocale,ud=t.osLocale,uo=t.resolvedLanguage||yn,Dg=t.languagePack?.translationsConfigFile}catch{}pd=!0}else typeof navigator=="object"&&!Og?(wt=navigator.userAgent,ri=wt.indexOf("Windows")>=0,ii=wt.indexOf("Macintosh")>=0,fd=(wt.indexOf("Macintosh")>=0||wt.indexOf("iPad")>=0||wt.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,ni=wt.indexOf("Linux")>=0,kg=wt?.indexOf("Mobi")>=0,Da=!0,uo=Pa()||yn,co=navigator.language.toLowerCase(),ud=co):console.error("Unable to resolve platform.");var ka=0;ii?ka=1:ri?ka=3:ni&&(ka=2);var B=ri,Je=ii,ve=ni;var md=pd;var In=Da,Lg=Da&&typeof Pt.importScripts=="function",hd=Lg?Pt.origin:void 0;var yt=wt,Zt=uo,Fg;(n=>{function i(){return Zt}n.value=i;function t(){return Zt.length===2?Zt==="en":Zt.length>=3?Zt[0]==="e"&&Zt[1]==="n"&&Zt[2]==="-":!1}n.isDefaultVariant=t;function e(){return Zt==="en"}n.isDefault=e})(Fg||={});var Ug=typeof Pt.postMessage=="function"&&!Pt.importScripts,vd=(()=>{if(Ug){let i=[];Pt.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let n=0,r=i.length;n<r;n++){let o=i[n];if(o.id===e.data.vscodeScheduleAsyncWork){i.splice(n,1),o.callback();return}}});let t=0;return e=>{let n=++t;i.push({id:n,callback:e}),Pt.postMessage({vscodeScheduleAsyncWork:n},"*")}}return i=>setTimeout(i)})();var po=ii||fd?2:ri?1:3;var Oa=!!(yt&&yt.indexOf("Chrome")>=0),bd=!!(yt&&yt.indexOf("Firefox")>=0),yd=!!(!Oa&&yt&&yt.indexOf("Safari")>=0),Id=!!(yt&&yt.indexOf("Edg/")>=0),ny=!!(yt&&yt.indexOf("Android")>=0);var Sn,La=globalThis.vscode;if(typeof La<"u"&&typeof La.process<"u"){let i=La.process;Sn={get platform(){return i.platform},get arch(){return i.arch},get env(){return i.env},cwd(){return i.cwd()}}}else typeof process<"u"&&typeof process?.versions?.node=="string"?Sn={get platform(){return process.platform},get arch(){return process.arch},get env(){return process.env},cwd(){return process.env.VSCODE_CWD||process.cwd()}}:Sn={get platform(){return B?"win32":Je?"darwin":"linux"},get arch(){},get env(){return{}},cwd(){return"/"}};var Gn=Sn.cwd,be=Sn.env,go=Sn.platform,oy=Sn.arch;var Ng=globalThis.performance.now.bind(globalThis.performance),mo=class i{static create(t){return new i(t)}constructor(t){this._now=t===!1?Date.now:Ng,this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}};var Sd=!1,Mg=!1,Wg=100,Td=6e4;function xd(){return!!be.VSCODE_DEV}var Q;(hn=>{hn.None=()=>L.None;function t(k){if(Mg){let{onDidAddListener:T}=k,E=Qn.create(),R=0;k.onDidAddListener=()=>{++R===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),E.print()),T?.()}}}function e(k,T,E){return m(k,()=>{},0,void 0,T??!0,void 0,E)}hn.defer=e;function n(k){return(T,E=null,R)=>{let D=!1,U;return U=k($=>{if(!D)return U?U.dispose():D=!0,T.call(E,$)},null,R),D&&U.dispose(),U}}hn.once=n;function r(k,T){return hn.once(hn.filter(k,T))}hn.onceIf=r;function o(k,T,E){return u((R,D=null,U)=>k($=>R.call(D,T($)),null,U),E)}hn.map=o;function s(k,T,E){return u((R,D=null,U)=>k($=>{T($),R.call(D,$)},null,U),E)}hn.forEach=s;function a(k,T,E){return u((R,D=null,U)=>k($=>T($)&&R.call(D,$),null,U),E)}hn.filter=a;function l(k){return k}hn.signal=l;function c(...k){return(T,E=null,R)=>{let D=ld(...k.map(U=>U($=>T.call(E,$))));return f(D,R)}}hn.any=c;function p(k,T,E,R){let D=E;return o(k,U=>(D=T(D,U),D),R)}hn.reduce=p;function u(k,T){let E,R={onWillAddFirstListener(){E=k(D.fire,D)},onDidRemoveLastListener(){E?.dispose()}};T||t(R);let D=new x(R);return T?.add(D),D.event}function f(k,T){return T instanceof Array?T.push(k):T&&T.add(k),k}function m(k,T,E=100,R=!1,D=!1,U,$){let we,oe,Ne,Pe=0,qe,Rt={leakWarningThreshold:U,onWillAddFirstListener(){we=k(Wc=>{Pe++,oe=T(oe,Wc),R&&!Ne&&(vn.fire(oe),oe=void 0),qe=()=>{let Bc=oe;oe=void 0,Ne=void 0,(!R||Pe>1)&&vn.fire(Bc),Pe=0},typeof E=="number"?(Ne&&clearTimeout(Ne),Ne=setTimeout(qe,E)):Ne===void 0&&(Ne=null,queueMicrotask(qe))})},onWillRemoveListener(){D&&Pe>0&&qe?.()},onDidRemoveLastListener(){qe=void 0,we.dispose()}};$||t(Rt);let vn=new x(Rt);return $?.add(vn),vn.event}hn.debounce=m;function v(k,T=0,E,R){return hn.debounce(k,(D,U)=>D?(D.push(U),D):[U],T,void 0,E??!0,void 0,R)}hn.accumulate=v;function h(k,T,E=100,R=!0,D=!0,U,$){let we,oe,Ne,Pe=0,qe={leakWarningThreshold:U,onWillAddFirstListener(){we=k(vn=>{Pe++,oe=T(oe,vn),Ne===void 0&&(R&&(Rt.fire(oe),oe=void 0,Pe=0),typeof E=="number"?Ne=setTimeout(()=>{D&&Pe>0&&Rt.fire(oe),oe=void 0,Ne=void 0,Pe=0},E):(Ne=0,queueMicrotask(()=>{D&&Pe>0&&Rt.fire(oe),oe=void 0,Ne=void 0,Pe=0})))})},onDidRemoveLastListener(){we.dispose()}};$||t(qe);let Rt=new x(qe);return $?.add(Rt),Rt.event}hn.throttle=h;function I(k,T=(R,D)=>R===D,E){let R=!0,D;return a(k,U=>{let $=R||!T(U,D);return R=!1,D=U,$},E)}hn.latch=I;function y(k,T,E){return[hn.filter(k,T,E),hn.filter(k,R=>!T(R),E)]}hn.split=y;function S(k,T,E=!1,R=[],D){let U=R.slice(),$;xd()&&($={stack:Qn.create(),timerId:setTimeout(()=>{U&&U.length>0&&$&&!$.warned&&($.warned=!0,console.warn(`[Event.buffer][${T}] potential LEAK detected: ${U.length} events buffered for ${Td/1e3}s without being consumed. Buffered here:`),$.stack.print())},Td),warned:!1},D&&D.add(w(()=>clearTimeout($.timerId))));let we=()=>{$&&clearTimeout($.timerId)},oe=k(qe=>{U?(U.push(qe),xd()&&$&&!$.warned&&U.length>=Wg&&($.warned=!0,console.warn(`[Event.buffer][${T}] potential LEAK detected: ${U.length} events buffered without being consumed. Buffered here:`),$.stack.print())):Pe.fire(qe)});D&&D.add(oe);let Ne=()=>{U?.forEach(qe=>Pe.fire(qe)),U=null,we()},Pe=new x({onWillAddFirstListener(){oe||(oe=k(qe=>Pe.fire(qe)),D&&D.add(oe))},onDidAddFirstListener(){U&&(E?setTimeout(Ne):Ne())},onDidRemoveLastListener(){oe&&oe.dispose(),oe=null,we()}});return D&&D.add(Pe),Pe.event}hn.buffer=S;function C(k,T){return(R,D,U)=>{let $=T(new Fe);return k(function(we){let oe=$.evaluate(we);oe!==X&&R.call(D,oe)},void 0,U)}}hn.chain=C;let X=Symbol("HaltChainable");class Fe{constructor(){this.steps=[]}map(T){return this.steps.push(T),this}forEach(T){return this.steps.push(E=>(T(E),E)),this}filter(T){return this.steps.push(E=>T(E)?E:X),this}reduce(T,E){let R=E;return this.steps.push(D=>(R=T(R,D),R)),this}latch(T=(E,R)=>E===R){let E=!0,R;return this.steps.push(D=>{let U=E||!T(D,R);return E=!1,R=D,U?D:X}),this}evaluate(T){for(let E of this.steps)if(T=E(T),T===X)break;return T}}function rt(k,T,E=R=>R){let R=(...we)=>$.fire(E(...we)),D=()=>k.on(T,R),U=()=>k.removeListener(T,R),$=new x({onWillAddFirstListener:D,onDidRemoveLastListener:U});return $.event}hn.fromNodeEventEmitter=rt;function P(k,T,E=R=>R){let R=(...we)=>$.fire(E(...we)),D=()=>k.addEventListener(T,R),U=()=>k.removeEventListener(T,R),$=new x({onWillAddFirstListener:D,onDidRemoveLastListener:U});return $.event}hn.fromDOMEventEmitter=P;function F(k,T){let E,R,D=new Promise(U=>{R=n(k)(U),Ba(R,T),E=()=>{Ed(R,T)}});return D.cancel=E,T&&D.finally(()=>Ed(R,T)),D}hn.toPromise=F;function A(k,T){return k(E=>T.fire(E))}hn.forward=A;function Z(k,T,E){return T(E),k(R=>T(R))}hn.runAndSubscribe=Z;class ie{constructor(T,E){this._observable=T;this._counter=0;this._hasChanged=!1;let R={onWillAddFirstListener:()=>{T.addObserver(this),this._observable.reportChanges()},onDidRemoveLastListener:()=>{T.removeObserver(this)}};E||t(R),this.emitter=new x(R),E&&E.add(this.emitter)}beginUpdate(T){this._counter++}handlePossibleChange(T){}handleChange(T,E){this._hasChanged=!0}endUpdate(T){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function Ue(k,T){return new ie(k,T).emitter.event}hn.fromObservable=Ue;function fg(k){return(T,E,R)=>{let D=0,U=!1,$={beginUpdate(){D++},endUpdate(){D--,D===0&&(k.reportChanges(),U&&(U=!1,T.call(E)))},handlePossibleChange(){},handleChange(){U=!0}};k.addObserver($),k.reportChanges();let we={dispose(){k.removeObserver($)}};return Ba(we,R),we}}hn.fromObservableLight=fg})(Q||={});var Ua=class i{constructor(t){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${t}_${i._idPool++}`,i.all.add(this)}static{this.all=new Set}static{this._idPool=0}start(t){this._stopWatch=new mo,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}},_d=-1;var Na=class i{constructor(t,e,n=(i._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t;this.threshold=e;this.name=n;this._warnCountdown=0}static{this._idPool=1}dispose(){this._stacks?.clear()}check(t,e){let n=this.threshold;if(n<=0||e<n)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=n*.5;let[o,s]=this.getMostFrequentStack(),a=`[${this.name}] potential listener LEAK detected, having ${e} listeners already. MOST frequent listener (${s}):`;console.warn(a),console.warn(o);let l=s/e>.3?"dominated":"popular",c=new ho(l,a,o,e);this._errorHandler(c)}return()=>{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,e=0;for(let[n,r]of this._stacks)(!t||e<r)&&(t=[n,r],e=r);return t}},Qn=class i{constructor(t){this.value=t}static create(){let t=new Error;return new i(t.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},ho=class i extends Error{constructor(t,e,n,r){super(`potential listener LEAK detected, ${t}`),this.name="ListenerLeakError",this.kind=t,this.listenerCount=r,this.details=e,this.stack=n}static is(t){return t instanceof i||t instanceof Error&&typeof t.kind=="string"&&typeof t.listenerCount=="number"}},Ma=class extends ho{constructor(t,e,n,r){super(t,e,n,r),this.name="ListenerRefusalError"}},Bg=0,Jn=class{constructor(t){this.value=t;this.id=Bg++}},$g=2,Vg=(i,t)=>{if(i instanceof Jn)t(i);else for(let e=0;e<i.length;e++){let n=i[e];n&&t(n)}},x=class{constructor(t){this._size=0;this._options=t,this._leakageMon=_d>0||this._options?.leakWarningThreshold?new Na(t?.onListenerError??fe,this._options?.leakWarningThreshold??_d):void 0,this._perfMon=this._options?._profName?new Ua(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Sd){let t=this._listeners;queueMicrotask(()=>{Vg(t,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(t,e,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let c=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],p=c[1]/this._size>.3?"dominated":"popular",u=new Ma(p,`${l}. HINT: Stack shows most frequent listener (${c[1]}-times)`,c[0],this._size);return(this._options?.onListenerError||fe)(u),L.None}if(this._disposed)return L.None;e&&(t=t.bind(e));let r=new Jn(t),o,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Qn.create(),o=this._leakageMon.check(r.stack,this._size+1)),Sd&&(r.stack=s??Qn.create()),this._listeners?this._listeners instanceof Jn?(this._deliveryQueue??=new Wa,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._options?.onDidAddListener?.(this),this._size++;let a=w(()=>{o?.(),this._removeListener(r)});return Ba(a,n),a},this._event}_removeListener(t){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let e=this._listeners,n=e.indexOf(t);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,e[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*$g<=e.length){let o=0;for(let s=0;s<e.length;s++)e[s]?e[o++]=e[s]:r&&o<this._deliveryQueue.end&&(this._deliveryQueue.end--,o<this._deliveryQueue.i&&this._deliveryQueue.i--);e.length=o}}_deliver(t,e){if(!t)return;let n=this._options?.onListenerError||fe;if(!n){t.value(e);return}try{t.value(e)}catch(r){n(r)}}_deliverQueue(t){let e=t.current._listeners;for(;t.i<t.end;)this._deliver(e[t.i++],t.value);t.reset()}fire(t){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof Jn)this._deliver(this._listeners,t);else{let e=this._deliveryQueue;e.enqueue(this,t,this._listeners.length),this._deliverQueue(e)}this._perfMon?.stop()}hasListeners(){return this._size>0}};var Wa=class{constructor(){this.i=-1;this.end=0}enqueue(t,e,n){this.i=0,this.end=n,this.current=t,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var vo=class{constructor(){this.hasListeners=!1;this.events=[];this.emitter=new x({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(t){let e={event:t,listener:null};return this.events.push(e),this.hasListeners&&this.hook(e),w(zn(()=>{this.hasListeners&&this.unhook(e);let r=this.events.indexOf(e);this.events.splice(r,1)}))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach(t=>this.hook(t))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach(t=>this.unhook(t))}hook(t){t.listener=t.event(e=>this.emitter.fire(e))}unhook(t){t.listener?.dispose(),t.listener=null}dispose(){this.emitter.dispose();for(let t of this.events)t.listener?.dispose();this.events=[]}};var oi=class{constructor(){this.listening=!1;this.inputEvent=Q.None;this.inputEventListener=L.None;this.emitter=new x({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}});this.event=this.emitter.event}set input(t){this.inputEvent=t,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=t(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}};function Ba(i,t){t instanceof N?t.add(i):Array.isArray(t)&&t.push(i)}function Ed(i,t){if(t instanceof N)t.delete(i);else if(Array.isArray(t)){let e=t.indexOf(i);e!==-1&&t.splice(e,1)}i.dispose()}var Cd=Object.freeze(function(i,t){let e=setTimeout(i.bind(t),0);return{dispose(){clearTimeout(e)}}}),Ze;(n=>{function i(r){return r===n.None||r===n.Cancelled||r instanceof Yn?!0:!r||typeof r!="object"?!1:typeof r.isCancellationRequested=="boolean"&&typeof r.onCancellationRequested=="function"}n.isCancellationToken=i,n.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Q.None}),n.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Cd})})(Ze||={});var Yn=class{constructor(){this._isCancelled=!1;this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Cd:(this._emitter||(this._emitter=new x),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},_e=class{constructor(t){this._token=void 0;this._parentListener=void 0;this._parentListener=t&&t.onCancellationRequested(this.cancel,this)}get token(){return this._token||(this._token=new Yn),this._token}cancel(){this._token?this._token instanceof Yn&&this._token.cancel():this._token=Ze.Cancelled}dispose(t=!1){t&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof Yn&&this._token.dispose():this._token=Ze.None}};var qg=65,Kg=97,zg=90,jg=122,Tn=46,ke=47,Qe=92,At=58,Hg=63,bo=class extends Error{constructor(t,e,n){let r;typeof e=="string"&&e.indexOf("not ")===0?(r="must not be",e=e.replace(/^not /,"")):r="must be";let o=t.indexOf(".")!==-1?"property":"argument",s=`The "${t}" ${o} ${r} of type ${e}`;s+=`. Received type ${typeof n}`,super(s),this.code="ERR_INVALID_ARG_TYPE"}};function Gg(i,t){if(i===null||typeof i!="object")throw new bo(t,"Object",i)}function ye(i,t){if(typeof i!="string")throw new bo(t,"string",i)}var Ye=go==="win32";function V(i){return i===ke||i===Qe}function $a(i){return i===ke}function kt(i){return i>=qg&&i<=zg||i>=Kg&&i<=jg}function yo(i,t,e,n){let r="",o=0,s=-1,a=0,l=0;for(let c=0;c<=i.length;++c){if(c<i.length)l=i.charCodeAt(c);else{if(n(l))break;l=ke}if(n(l)){if(!(s===c-1||a===1))if(a===2){if(r.length<2||o!==2||r.charCodeAt(r.length-1)!==Tn||r.charCodeAt(r.length-2)!==Tn){if(r.length>2){let p=r.lastIndexOf(e);p===-1?(r="",o=0):(r=r.slice(0,p),o=r.length-1-r.lastIndexOf(e)),s=c,a=0;continue}else if(r.length!==0){r="",o=0,s=c,a=0;continue}}t&&(r+=r.length>0?`${e}..`:"..",o=2)}else r.length>0?r+=`${e}${i.slice(s+1,c)}`:r=i.slice(s+1,c),o=c-s-1;s=c,a=0}else l===Tn&&a!==-1?++a:a=-1}return r}function Jg(i){return i?`${i[0]==="."?"":"."}${i}`:""}function Rd(i,t){Gg(t,"pathObject");let e=t.dir||t.root,n=t.base||`${t.name||""}${Jg(t.ext)}`;return e?e===t.root?`${e}${n}`:`${e}${i}${n}`:n}var ge={resolve(...i){let t="",e="",n=!1;for(let r=i.length-1;r>=-1;r--){let o;if(r>=0){if(o=i[r],ye(o,`paths[${r}]`),o.length===0)continue}else t.length===0?o=Gn():(o=be[`=${t}`]||Gn(),(o===void 0||o.slice(0,2).toLowerCase()!==t.toLowerCase()&&o.charCodeAt(2)===Qe)&&(o=`${t}\\`));let s=o.length,a=0,l="",c=!1,p=o.charCodeAt(0);if(s===1)V(p)&&(a=1,c=!0);else if(V(p))if(c=!0,V(o.charCodeAt(1))){let u=2,f=u;for(;u<s&&!V(o.charCodeAt(u));)u++;if(u<s&&u!==f){let m=o.slice(f,u);for(f=u;u<s&&V(o.charCodeAt(u));)u++;if(u<s&&u!==f){for(f=u;u<s&&!V(o.charCodeAt(u));)u++;(u===s||u!==f)&&(l=`\\\\${m}\\${o.slice(f,u)}`,a=u)}}}else a=1;else kt(p)&&o.charCodeAt(1)===At&&(l=o.slice(0,2),a=2,s>2&&V(o.charCodeAt(2))&&(c=!0,a=3));if(l.length>0)if(t.length>0){if(l.toLowerCase()!==t.toLowerCase())continue}else t=l;if(n){if(t.length>0)break}else if(e=`${o.slice(a)}\\${e}`,n=c,c&&t.length>0)break}return e=yo(e,!n,"\\",V),n?`${t}\\${e}`:`${t}${e}`||"."},normalize(i){ye(i,"path");let t=i.length;if(t===0)return".";let e=0,n,r=!1,o=i.charCodeAt(0);if(t===1)return $a(o)?"\\":i;if(V(o))if(r=!0,V(i.charCodeAt(1))){let a=2,l=a;for(;a<t&&!V(i.charCodeAt(a));)a++;if(a<t&&a!==l){let c=i.slice(l,a);for(l=a;a<t&&V(i.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&!V(i.charCodeAt(a));)a++;if(a===t)return`\\\\${c}\\${i.slice(l)}\\`;a!==l&&(n=`\\\\${c}\\${i.slice(l,a)}`,e=a)}}}else e=1;else kt(o)&&i.charCodeAt(1)===At&&(n=i.slice(0,2),e=2,t>2&&V(i.charCodeAt(2))&&(r=!0,e=3));let s=e<t?yo(i.slice(e),!r,"\\",V):"";if(s.length===0&&!r&&(s="."),s.length>0&&V(i.charCodeAt(t-1))&&(s+="\\"),!r&&n===void 0&&i.includes(":")){if(s.length>=2&&kt(s.charCodeAt(0))&&s.charCodeAt(1)===At)return`.\\${s}`;let a=i.indexOf(":");do if(a===t-1||V(i.charCodeAt(a+1)))return`.\\${s}`;while((a=i.indexOf(":",a+1))!==-1)}return n===void 0?r?`\\${s}`:s:r?`${n}\\${s}`:`${n}${s}`},isAbsolute(i){ye(i,"path");let t=i.length;if(t===0)return!1;let e=i.charCodeAt(0);return V(e)||t>2&&kt(e)&&i.charCodeAt(1)===At&&V(i.charCodeAt(2))},join(...i){if(i.length===0)return".";let t,e;for(let o=0;o<i.length;++o){let s=i[o];ye(s,"path"),s.length>0&&(t===void 0?t=e=s:t+=`\\${s}`)}if(t===void 0)return".";let n=!0,r=0;if(typeof e=="string"&&V(e.charCodeAt(0))){++r;let o=e.length;o>1&&V(e.charCodeAt(1))&&(++r,o>2&&(V(e.charCodeAt(2))?++r:n=!1))}if(n){for(;r<t.length&&V(t.charCodeAt(r));)r++;r>=2&&(t=`\\${t.slice(r)}`)}return ge.normalize(t)},relative(i,t){if(ye(i,"from"),ye(t,"to"),i===t)return"";let e=ge.resolve(i),n=ge.resolve(t);if(e===n||(i=e.toLowerCase(),t=n.toLowerCase(),i===t))return"";if(e.length!==i.length||n.length!==t.length){let v=e.split("\\"),h=n.split("\\");v[v.length-1]===""&&v.pop(),h[h.length-1]===""&&h.pop();let I=v.length,y=h.length,S=I<y?I:y,C;for(C=0;C<S&&v[C].toLowerCase()===h[C].toLowerCase();C++);return C===0?n:C===S?y>S?h.slice(C).join("\\"):I>S?"..\\".repeat(I-1-C)+"..":"":"..\\".repeat(I-C)+h.slice(C).join("\\")}let r=0;for(;r<i.length&&i.charCodeAt(r)===Qe;)r++;let o=i.length;for(;o-1>r&&i.charCodeAt(o-1)===Qe;)o--;let s=o-r,a=0;for(;a<t.length&&t.charCodeAt(a)===Qe;)a++;let l=t.length;for(;l-1>a&&t.charCodeAt(l-1)===Qe;)l--;let c=l-a,p=s<c?s:c,u=-1,f=0;for(;f<p;f++){let v=i.charCodeAt(r+f);if(v!==t.charCodeAt(a+f))break;v===Qe&&(u=f)}if(f!==p){if(u===-1)return n}else{if(c>p){if(t.charCodeAt(a+f)===Qe)return n.slice(a+f+1);if(f===2)return n.slice(a+f)}s>p&&(i.charCodeAt(r+f)===Qe?u=f:f===2&&(u=3)),u===-1&&(u=0)}let m="";for(f=r+u+1;f<=o;++f)(f===o||i.charCodeAt(f)===Qe)&&(m+=m.length===0?"..":"\\..");return a+=u,m.length>0?`${m}${n.slice(a,l)}`:(n.charCodeAt(a)===Qe&&++a,n.slice(a,l))},toNamespacedPath(i){if(typeof i!="string"||i.length===0)return i;let t=ge.resolve(i);if(t.length<=2)return i;if(t.charCodeAt(0)===Qe){if(t.charCodeAt(1)===Qe){let e=t.charCodeAt(2);if(e!==Hg&&e!==Tn)return`\\\\?\\UNC\\${t.slice(2)}`}}else if(kt(t.charCodeAt(0))&&t.charCodeAt(1)===At&&t.charCodeAt(2)===Qe)return`\\\\?\\${t}`;return t},dirname(i){ye(i,"path");let t=i.length;if(t===0)return".";let e=-1,n=0,r=i.charCodeAt(0);if(t===1)return V(r)?i:".";if(V(r)){if(e=n=1,V(i.charCodeAt(1))){let a=2,l=a;for(;a<t&&!V(i.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&V(i.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&!V(i.charCodeAt(a));)a++;if(a===t)return i;a!==l&&(e=n=a+1)}}}}else kt(r)&&i.charCodeAt(1)===At&&(e=t>2&&V(i.charCodeAt(2))?3:2,n=e);let o=-1,s=!0;for(let a=t-1;a>=n;--a)if(V(i.charCodeAt(a))){if(!s){o=a;break}}else s=!1;if(o===-1){if(e===-1)return".";o=e}return i.slice(0,o)},basename(i,t){t!==void 0&&ye(t,"suffix"),ye(i,"path");let e=0,n=-1,r=!0,o;if(i.length>=2&&kt(i.charCodeAt(0))&&i.charCodeAt(1)===At&&(e=2),t!==void 0&&t.length>0&&t.length<=i.length){if(t===i)return"";let s=t.length-1,a=-1;for(o=i.length-1;o>=e;--o){let l=i.charCodeAt(o);if(V(l)){if(!r){e=o+1;break}}else a===-1&&(r=!1,a=o+1),s>=0&&(l===t.charCodeAt(s)?--s===-1&&(n=o):(s=-1,n=a))}return e===n?n=a:n===-1&&(n=i.length),i.slice(e,n)}for(o=i.length-1;o>=e;--o)if(V(i.charCodeAt(o))){if(!r){e=o+1;break}}else n===-1&&(r=!1,n=o+1);return n===-1?"":i.slice(e,n)},extname(i){ye(i,"path");let t=0,e=-1,n=0,r=-1,o=!0,s=0;i.length>=2&&i.charCodeAt(1)===At&&kt(i.charCodeAt(0))&&(t=n=2);for(let a=i.length-1;a>=t;--a){let l=i.charCodeAt(a);if(V(l)){if(!o){n=a+1;break}continue}r===-1&&(o=!1,r=a+1),l===Tn?e===-1?e=a:s!==1&&(s=1):e!==-1&&(s=-1)}return e===-1||r===-1||s===0||s===1&&e===r-1&&e===n+1?"":i.slice(e,r)},format:Rd.bind(null,"\\"),parse(i){ye(i,"path");let t={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return t;let e=i.length,n=0,r=i.charCodeAt(0);if(e===1)return V(r)?(t.root=t.dir=i,t):(t.base=t.name=i,t);if(V(r)){if(n=1,V(i.charCodeAt(1))){let u=2,f=u;for(;u<e&&!V(i.charCodeAt(u));)u++;if(u<e&&u!==f){for(f=u;u<e&&V(i.charCodeAt(u));)u++;if(u<e&&u!==f){for(f=u;u<e&&!V(i.charCodeAt(u));)u++;u===e?n=u:u!==f&&(n=u+1)}}}}else if(kt(r)&&i.charCodeAt(1)===At){if(e<=2)return t.root=t.dir=i,t;if(n=2,V(i.charCodeAt(2))){if(e===3)return t.root=t.dir=i,t;n=3}}n>0&&(t.root=i.slice(0,n));let o=-1,s=n,a=-1,l=!0,c=i.length-1,p=0;for(;c>=n;--c){if(r=i.charCodeAt(c),V(r)){if(!l){s=c+1;break}continue}a===-1&&(l=!1,a=c+1),r===Tn?o===-1?o=c:p!==1&&(p=1):o!==-1&&(p=-1)}return a!==-1&&(o===-1||p===0||p===1&&o===a-1&&o===s+1?t.base=t.name=i.slice(s,a):(t.name=i.slice(s,o),t.base=i.slice(s,a),t.ext=i.slice(o,a))),s>0&&s!==n?t.dir=i.slice(0,s-1):t.dir=t.root,t},sep:"\\",delimiter:";",win32:null,posix:null},Qg=(()=>{if(Ye){let i=/\\/g;return()=>{let t=Gn().replace(i,"/");return t.slice(t.indexOf("/"))}}return()=>Gn()})(),z={resolve(...i){let t="",e=!1;for(let n=i.length-1;n>=0&&!e;n--){let r=i[n];ye(r,`paths[${n}]`),r.length!==0&&(t=`${r}/${t}`,e=r.charCodeAt(0)===ke)}if(!e){let n=Qg();t=`${n}/${t}`,e=n.charCodeAt(0)===ke}return t=yo(t,!e,"/",$a),e?`/${t}`:t.length>0?t:"."},normalize(i){if(ye(i,"path"),i.length===0)return".";let t=i.charCodeAt(0)===ke,e=i.charCodeAt(i.length-1)===ke;return i=yo(i,!t,"/",$a),i.length===0?t?"/":e?"./":".":(e&&(i+="/"),t?`/${i}`:i)},isAbsolute(i){return ye(i,"path"),i.length>0&&i.charCodeAt(0)===ke},join(...i){if(i.length===0)return".";let t=[];for(let e=0;e<i.length;++e){let n=i[e];ye(n,"path"),n.length>0&&t.push(n)}return t.length===0?".":z.normalize(t.join("/"))},relative(i,t){if(ye(i,"from"),ye(t,"to"),i===t||(i=z.resolve(i),t=z.resolve(t),i===t))return"";let e=1,n=i.length,r=n-e,o=1,s=t.length-o,a=r<s?r:s,l=-1,c=0;for(;c<a;c++){let u=i.charCodeAt(e+c);if(u!==t.charCodeAt(o+c))break;u===ke&&(l=c)}if(c===a)if(s>a){if(t.charCodeAt(o+c)===ke)return t.slice(o+c+1);if(c===0)return t.slice(o+c)}else r>a&&(i.charCodeAt(e+c)===ke?l=c:c===0&&(l=0));let p="";for(c=e+l+1;c<=n;++c)(c===n||i.charCodeAt(c)===ke)&&(p+=p.length===0?"..":"/..");return`${p}${t.slice(o+l)}`},toNamespacedPath(i){return i},dirname(i){if(ye(i,"path"),i.length===0)return".";let t=i.charCodeAt(0)===ke,e=-1,n=!0;for(let r=i.length-1;r>=1;--r)if(i.charCodeAt(r)===ke){if(!n){e=r;break}}else n=!1;return e===-1?t?"/":".":t&&e===1?"//":i.slice(0,e)},basename(i,t){t!==void 0&&ye(t,"suffix"),ye(i,"path");let e=0,n=-1,r=!0,o;if(t!==void 0&&t.length>0&&t.length<=i.length){if(t===i)return"";let s=t.length-1,a=-1;for(o=i.length-1;o>=0;--o){let l=i.charCodeAt(o);if(l===ke){if(!r){e=o+1;break}}else a===-1&&(r=!1,a=o+1),s>=0&&(l===t.charCodeAt(s)?--s===-1&&(n=o):(s=-1,n=a))}return e===n?n=a:n===-1&&(n=i.length),i.slice(e,n)}for(o=i.length-1;o>=0;--o)if(i.charCodeAt(o)===ke){if(!r){e=o+1;break}}else n===-1&&(r=!1,n=o+1);return n===-1?"":i.slice(e,n)},extname(i){ye(i,"path");let t=-1,e=0,n=-1,r=!0,o=0;for(let s=i.length-1;s>=0;--s){let a=i[s];if(a==="/"){if(!r){e=s+1;break}continue}n===-1&&(r=!1,n=s+1),a==="."?t===-1?t=s:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||n===-1||o===0||o===1&&t===n-1&&t===e+1?"":i.slice(t,n)},format:Rd.bind(null,"/"),parse(i){ye(i,"path");let t={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return t;let e=i.charCodeAt(0)===ke,n;e?(t.root="/",n=1):n=0;let r=-1,o=0,s=-1,a=!0,l=i.length-1,c=0;for(;l>=n;--l){let p=i.charCodeAt(l);if(p===ke){if(!a){o=l+1;break}continue}s===-1&&(a=!1,s=l+1),p===Tn?r===-1?r=l:c!==1&&(c=1):r!==-1&&(c=-1)}if(s!==-1){let p=o===0&&e?1:o;r===-1||c===0||c===1&&r===s-1&&r===o+1?t.base=t.name=i.slice(p,s):(t.name=i.slice(p,r),t.base=i.slice(p,s),t.ext=i.slice(r,s))}return o>0?t.dir=i.slice(0,o-1):e&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};z.win32=ge.win32=ge;z.posix=ge.posix=z;var ot=Ye?ge.normalize:z.normalize,Xn=Ye?ge.isAbsolute:z.isAbsolute,q=Ye?ge.join:z.join,xn=Ye?ge.resolve:z.resolve,wd=Ye?ge.relative:z.relative,me=Ye?ge.dirname:z.dirname,Te=Ye?ge.basename:z.basename,Pd=Ye?ge.extname:z.extname,Ty=Ye?ge.format:z.format,xy=Ye?ge.parse:z.parse,_y=Ye?ge.toNamespacedPath:z.toNamespacedPath,Se=Ye?ge.sep:z.sep,Va=Ye?ge.delimiter:z.delimiter;function Yg(i){return i}var Io=class{constructor(t,e){this.lastCache=void 0;this.lastArgKey=void 0;typeof t=="function"?(this._fn=t,this._computeKey=Yg):(this._fn=e,this._computeKey=t.getCacheKey)}get(t){let e=this._computeKey(t);return this.lastArgKey!==e&&(this.lastArgKey=e,this.lastCache=this._fn(t)),this.lastCache}};var He=class{constructor(t){this.executor=t;this._state=0}get hasValue(){return this._state===2}get value(){if(this._state===0){this._state=1;try{this._value=this.executor()}catch(t){this._error=t}finally{this._state=2}}else if(this._state===1)throw new Error("Cannot read the value of a lazy that is being initialized");if(this._error)throw this._error;return this._value}get rawValue(){return this._value}};function Ld(i){return!i||typeof i!="string"?!0:i.trim().length===0}var Xg=/{(\d+)}/g;function _n(i,...t){return t.length===0?i:i.replace(Xg,function(e,n){let r=parseInt(n,10);return isNaN(r)||r<0||r>=t.length?e:t[r]})}function Dt(i){return i.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function qa(i,t){if(!i||!t)return i;let e=t.length,n=0;if(e===1){let r=t.charCodeAt(0);for(;n<i.length&&i.charCodeAt(n)===r;)n++}else for(;i.startsWith(t,n);)n+=e;return i.substring(n)}function Zn(i,t){if(!i||!t)return i;let e=t.length,n=i.length;if(e===1){let o=n,s=t.charCodeAt(0);for(;o>0&&i.charCodeAt(o-1)===s;)o--;return i.substring(0,o)}let r=n;for(;r>0&&i.endsWith(t,r);)r-=e;return i.substring(0,r)}function Fd(i){return i.source==="^"||i.source==="^$"||i.source==="$"||i.source==="^\\s*$"?!1:!!(i.exec("")&&i.lastIndex===0)}function ai(i,t){return i<t?-1:i>t?1:0}function So(i,t,e=0,n=i.length,r=0,o=t.length){for(;e<n&&r<o;e++,r++){let l=i.charCodeAt(e),c=t.charCodeAt(r);if(l<c)return-1;if(l>c)return 1}let s=n-e,a=o-r;return s<a?-1:s>a?1:0}function Ka(i,t){return En(i,t,0,i.length,0,t.length)}function En(i,t,e=0,n=i.length,r=0,o=t.length){for(;e<n&&r<o;e++,r++){let l=i.charCodeAt(e),c=t.charCodeAt(r);if(l===c)continue;if(l>=128||c>=128)return So(i.toLowerCase(),t.toLowerCase(),e,n,r,o);Ad(l)&&(l-=32),Ad(c)&&(c-=32);let p=l-c;if(p!==0)return p}let s=n-e,a=o-r;return s<a?-1:s>a?1:0}function Ad(i){return i>=97&&i<=122}function za(i){return i>=65&&i<=90}function Cn(i,t){return i.length===t.length&&En(i,t)===0}function tn(i,t){let e=t.length;return e<=i.length&&En(i,t,0,e)===0}function Ud(i,t){let e=i.length,n=e-t.length;return n>=0&&En(i,t,n,e)===0}function Nd(i){return 55296<=i&&i<=56319}function ja(i){return 56320<=i&&i<=57343}function Md(i,t){return(i-55296<<10)+(t-56320)+65536}var Zg=/(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/,em=/(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/,tm=/\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/,nm=new RegExp("(?:"+[Zg.source,em.source,tm.source].join("|")+")","g");function Wd(i){return i&&(i=i.replace(nm,"")),i}var Fy=String.fromCharCode(65279);var kd=class i{static{this._INSTANCE=null}static getInstance(){return i._INSTANCE||(i._INSTANCE=new i),i._INSTANCE}constructor(){this._data=rm()}getGraphemeBreakType(t){if(t<32)return t===10?3:t===13?2:4;if(t<127)return 0;let e=this._data,n=e.length/3,r=1;for(;r<=n;)if(t<e[3*r])r=2*r;else if(t>e[3*r+1])r=2*r+1;else return e[3*r+2];return 0}};function rm(){return JSON.parse("[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]")}var Dd=class i{constructor(t){this.confusableDictionary=t}static{this.ambiguousCharacterData=new He(()=>JSON.parse('{"_common":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,1523,96,8242,96,1370,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,118002,50,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,118003,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,118004,52,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,118005,53,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,118006,54,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,118007,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,118008,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,118009,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,117974,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,117975,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71913,67,71922,67,65315,67,8557,67,8450,67,8493,67,117976,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,117977,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,117978,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,117979,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,117980,71,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,117981,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,117983,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,117984,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,118001,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,117982,108,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,117985,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,117986,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,117987,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,118000,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,117988,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,117989,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,117990,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,117991,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,117992,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,117993,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,117994,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,117995,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71910,87,71919,87,117996,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,117997,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,117998,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,71909,90,66293,90,65338,90,8484,90,8488,90,117999,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65283,35,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125,119846,109],"_default":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"cs":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"de":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"es":[8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"fr":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"it":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"ja":[8211,45,8218,44,65281,33,8216,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65292,44,65297,49,65307,59],"ko":[8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"pl":[65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"pt-BR":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"qps-ploc":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"ru":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"tr":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"zh-hans":[160,32,65374,126,8218,44,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65297,49],"zh-hant":[8211,45,65374,126,8218,44,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89]}'))}static{this.cache=new Io(t=>{let e=t.split(",");function n(u){let f=new Map;for(let m=0;m<u.length;m+=2)f.set(u[m],u[m+1]);return f}function r(u,f){let m=new Map(u);for(let[v,h]of f)m.set(v,h);return m}function o(u,f){if(!u)return f;let m=new Map;for(let[v,h]of u)f.has(v)&&m.set(v,h);return m}let s=this.ambiguousCharacterData.value,a=e.filter(u=>!u.startsWith("_")&&Object.hasOwn(s,u));a.length===0&&(a=["_default"]);let l;for(let u of a){let f=n(s[u]);l=o(l,f)}let c=n(s._common),p=r(c,l);return new i(p)})}static getInstance(t){return i.cache.get(Array.from(t).join(","))}static{this._locales=new He(()=>Object.keys(i.ambiguousCharacterData.value).filter(t=>!t.startsWith("_")))}static getLocales(){return i._locales.value}isAmbiguous(t){return this.confusableDictionary.has(t)}containsAmbiguousCharacter(t){for(let e=0;e<t.length;e++){let n=t.codePointAt(e);if(typeof n=="number"&&this.isAmbiguous(n))return!0}return!1}getPrimaryConfusable(t){return this.confusableDictionary.get(t)}getConfusableCodePoints(){return new Set(this.confusableDictionary.keys())}},Od=class i{static getRawData(){return JSON.parse('{"_common":[11,12,13,127,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999],"cs":[173,8203,12288],"de":[173,8203,12288],"es":[8203,12288],"fr":[173,8203,12288],"it":[160,173,12288],"ja":[173],"ko":[173,12288],"pl":[173,8203,12288],"pt-BR":[173,8203,12288],"qps-ploc":[160,173,8203,12288],"ru":[173,12288],"tr":[160,173,8203,12288],"zh-hans":[160,173,8203,12288],"zh-hant":[173,12288]}')}static{this._data=void 0}static getData(){return this._data||(this._data=new Set([...Object.values(i.getRawData())].flat())),this._data}static isInvisibleCharacter(t){return i.getData().has(t)}static containsInvisibleCharacter(t){for(let e=0;e<t.length;e++){let n=t.codePointAt(e);if(typeof n=="number"&&(i.isInvisibleCharacter(n)||n===32))return!0}return!1}static get codePoints(){return i.getData()}};function nn(i){return i===47||i===92}function To(i){return i.replace(/[\\/]/g,z.sep)}function Bd(i){return i.indexOf("/")===-1&&(i=To(i)),/^[a-zA-Z]:(\/|$)/.test(i)&&(i="/"+i),i}function Ga(i,t=z.sep){if(!i)return"";let e=i.length,n=i.charCodeAt(0);if(nn(n)){if(nn(i.charCodeAt(1))&&!nn(i.charCodeAt(2))){let o=3,s=o;for(;o<e&&!nn(i.charCodeAt(o));o++);if(s!==o&&!nn(i.charCodeAt(o+1))){for(o+=1;o<e;o++)if(nn(i.charCodeAt(o)))return i.slice(0,o+1).replace(/[\\/]/g,t)}}return t}else if($d(n)&&i.charCodeAt(1)===58)return nn(i.charCodeAt(2))?i.slice(0,2)+t:i.slice(0,2);let r=i.indexOf("://");if(r!==-1){for(r+=3;r<e;r++)if(nn(i.charCodeAt(r)))return i.slice(0,r+1)}return""}function er(i,t,e){let n=i===t;return!e||n?n:!i||!t?!1:Cn(i,t)}function Ot(i,t,e,n=Se){if(i===t)return!0;if(!i||!t||t.length>i.length)return!1;if(e){if(!tn(i,t))return!1;if(t.length===i.length)return!0;let o=t.length;return t.charAt(t.length-1)===n&&o--,i.charAt(o)===n}return t.charAt(t.length-1)!==n&&(t+=n),i.indexOf(t)===0}function $d(i){return i>=65&&i<=90||i>=97&&i<=122}function Vd(i){return B?(i=Zn(i,Se),i.endsWith(":")&&(i+=Se)):(i=Zn(i,Se),i||(i=Se)),i}function Ja(i){let t=ot(i);return B?i.length>3?!1:qd(t)&&(i.length===2||t.charCodeAt(2)===92):t===z.sep}function qd(i,t=B){return t?$d(i.charCodeAt(0))&&i.charCodeAt(1)===58:!1}var im="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",om="BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";function Kd(i,t,e=8){let n="";for(let o=0;o<e;o++){let s;o===0&&B&&!t&&(e===3||e===4)?s=om:s=im,n+=s.charAt(Math.floor(Math.random()*s.length))}let r;return t?r=`${t}-${n}`:r=n,i?q(i,r):r}var am=/^\w[\w\d+.-]*$/,lm=/^\//,cm=/^\/\//;function dm(i,t){if(!i.scheme&&t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${i.authority}", path: "${i.path}", query: "${i.query}", fragment: "${i.fragment}"}`);if(i.scheme&&!am.test(i.scheme)){let e=[...i.scheme.matchAll(/[^\w\d+.-]/gu)],n=e.length>0?` Found '${e[0][0]}' at index ${e[0].index} (${e.length} total)`:"";throw new Error(`[UriError]: Scheme contains illegal characters.${n} (len:${i.scheme.length})`)}if(i.path){if(i.authority){if(!lm.test(i.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(cm.test(i.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function um(i,t){return!i&&!t?"file":i}function pm(i,t){switch(i){case"https":case"http":case"file":t?t[0]!==pt&&(t=pt+t):t=pt;break}return t}var se="",pt="/",fm=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,b=class i{static isUri(t){return t instanceof i?!0:!t||typeof t!="object"?!1:typeof t.authority=="string"&&typeof t.fragment=="string"&&typeof t.path=="string"&&typeof t.query=="string"&&typeof t.scheme=="string"&&typeof t.fsPath=="string"&&typeof t.with=="function"&&typeof t.toString=="function"}constructor(t,e,n,r,o,s=!1){typeof t=="object"?(this.scheme=t.scheme||se,this.authority=t.authority||se,this.path=t.path||se,this.query=t.query||se,this.fragment=t.fragment||se):(this.scheme=um(t,s),this.authority=e||se,this.path=pm(this.scheme,n||se),this.query=r||se,this.fragment=o||se,dm(this,s))}get fsPath(){return li(this,!1)}with(t){if(!t)return this;let{scheme:e,authority:n,path:r,query:o,fragment:s}=t;return e===void 0?e=this.scheme:e===null&&(e=se),n===void 0?n=this.authority:n===null&&(n=se),r===void 0?r=this.path:r===null&&(r=se),o===void 0?o=this.query:o===null&&(o=se),s===void 0?s=this.fragment:s===null&&(s=se),e===this.scheme&&n===this.authority&&r===this.path&&o===this.query&&s===this.fragment?this:new rn(e,n,r,o,s)}static parse(t,e=!1){let n=fm.exec(t);return n?new rn(n[2]||se,xo(n[4]||se),xo(n[5]||se),xo(n[7]||se),xo(n[9]||se),e):new rn(se,se,se,se,se)}static file(t){let e=se;if(B&&(t=t.replace(/\\/g,pt)),t[0]===pt&&t[1]===pt){let n=t.indexOf(pt,2);n===-1?(e=t.substring(2),t=pt):(e=t.substring(2,n),t=t.substring(n)||pt)}return new rn("file",e,t,se,se)}static from(t,e){return new rn(t.scheme,t.authority,t.path,t.query,t.fragment,e)}static joinPath(t,...e){if(!t.path)throw new Error(`[UriError]: cannot call joinPath on URI without path: ${t.toString()}`);let n;return B&&t.scheme==="file"?n=i.file(ge.join(li(t,!0),...e)).path:n=z.join(t.path,...e),t.with({path:n})}toString(t=!1){return Qa(this,t)}toJSON(){return this}static revive(t){if(t){if(t instanceof i)return t;{let e=new rn(t);return e._formatted=t.external??null,e._fsPath=t._sep===Gd?t.fsPath??null:null,e}}else return t}[Symbol.for("debug.description")](){return`URI(${this.toString()})`}};var Gd=B?1:void 0,rn=class extends b{constructor(){super(...arguments);this._formatted=null;this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=li(this,!1)),this._fsPath}toString(e=!1){return e?Qa(this,!0):(this._formatted||(this._formatted=Qa(this,!1)),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=Gd),this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),this.query&&(e.query=this.query),this.fragment&&(e.fragment=this.fragment),e}},Jd={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function zd(i,t,e){let n,r=-1;for(let o=0;o<i.length;o++){let s=i.charCodeAt(o);if(s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||s===45||s===46||s===95||s===126||t&&s===47||e&&s===91||e&&s===93||e&&s===58)r!==-1&&(n+=encodeURIComponent(i.substring(r,o)),r=-1),n!==void 0&&(n+=i.charAt(o));else{n===void 0&&(n=i.substr(0,o));let a=Jd[s];a!==void 0?(r!==-1&&(n+=encodeURIComponent(i.substring(r,o)),r=-1),n+=a):r===-1&&(r=o)}}return r!==-1&&(n+=encodeURIComponent(i.substring(r))),n!==void 0?n:i}function gm(i){let t;for(let e=0;e<i.length;e++){let n=i.charCodeAt(e);n===35||n===63?(t===void 0&&(t=i.substr(0,e)),t+=Jd[n]):t!==void 0&&(t+=i[e])}return t!==void 0?t:i}function li(i,t){let e;return i.authority&&i.path.length>1&&i.scheme==="file"?e=`//${i.authority}${i.path}`:i.path.charCodeAt(0)===47&&(i.path.charCodeAt(1)>=65&&i.path.charCodeAt(1)<=90||i.path.charCodeAt(1)>=97&&i.path.charCodeAt(1)<=122)&&i.path.charCodeAt(2)===58?t?e=i.path.substr(1):e=i.path[1].toLowerCase()+i.path.substr(2):e=i.path,B&&(e=e.replace(/\//g,"\\")),e}function Qa(i,t){let e=t?gm:zd,n="",{scheme:r,authority:o,path:s,query:a,fragment:l}=i;if(r&&(n+=r,n+=":"),(o||r==="file")&&(n+=pt,n+=pt),o){let c=o.indexOf("@");if(c!==-1){let p=o.substr(0,c);o=o.substr(c+1),c=p.lastIndexOf(":"),c===-1?n+=e(p,!1,!1):(n+=e(p.substr(0,c),!1,!1),n+=":",n+=e(p.substr(c+1),!1,!0)),n+="@"}o=o.toLowerCase(),c=o.lastIndexOf(":"),c===-1?n+=e(o,!1,!0):(n+=e(o.substr(0,c),!1,!0),n+=o.substr(c))}if(s){if(s.length>=3&&s.charCodeAt(0)===47&&s.charCodeAt(2)===58){let c=s.charCodeAt(1);c>=65&&c<=90&&(s=`/${String.fromCharCode(c+32)}:${s.substr(3)}`)}else if(s.length>=2&&s.charCodeAt(1)===58){let c=s.charCodeAt(0);c>=65&&c<=90&&(s=`${String.fromCharCode(c+32)}:${s.substr(2)}`)}n+=e(s,!0,!1)}return a&&(n+="?",n+=e(a,!1,!1)),l&&(n+="#",n+=t?l:zd(l,!1,!1)),n}function Qd(i){try{return decodeURIComponent(i)}catch{return i.length>3?i.substr(0,3)+Qd(i.substr(3)):i}}var jd=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function xo(i){return i.match(jd)?i.replace(jd,t=>Qd(t)):i}var ee;(W=>(W.inMemory="inmemory",W.vscode="vscode",W.internal="private",W.walkThrough="walkThrough",W.walkThroughSnippet="walkThroughSnippet",W.http="http",W.https="https",W.file="file",W.mailto="mailto",W.untitled="untitled",W.data="data",W.command="command",W.vscodeRemote="vscode-remote",W.vscodeRemoteResource="vscode-remote-resource",W.vscodeManagedRemoteResource="vscode-managed-remote-resource",W.vscodeUserData="vscode-userdata",W.vscodeCustomEditor="vscode-custom-editor",W.vscodeNotebookCell="vscode-notebook-cell",W.vscodeNotebookCellMetadata="vscode-notebook-cell-metadata",W.vscodeNotebookCellMetadataDiff="vscode-notebook-cell-metadata-diff",W.vscodeNotebookCellOutput="vscode-notebook-cell-output",W.vscodeNotebookCellOutputDiff="vscode-notebook-cell-output-diff",W.vscodeNotebookMetadata="vscode-notebook-metadata",W.vscodeInteractiveInput="vscode-interactive-input",W.vscodeSettings="vscode-settings",W.vscodeWorkspaceTrust="vscode-workspace-trust",W.vscodeTerminal="vscode-terminal",W.vscodeImageCarousel="vscode-image-carousel",W.vscodeChatCodeBlock="vscode-chat-code-block",W.vscodeChatCodeCompareBlock="vscode-chat-code-compare-block",W.vscodeChatEditor="vscode-chat-editor",W.vscodeChatInput="chatSessionInput",W.vscodeLocalChatSession="vscode-chat-session",W.webviewPanel="webview-panel",W.vscodeWebview="vscode-webview",W.vscodeBrowser="vscode-browser",W.extension="extension",W.vscodeFileResource="vscode-file",W.tmp="tmp",W.vsls="vsls",W.vscodeSourceControl="vscode-scm",W.commentsInput="comment",W.codeSetting="code-setting",W.outputChannel="output",W.accessibleView="accessible-view",W.chatEditingSnapshotScheme="chat-editing-snapshot-text-model",W.chatEditingModel="chat-editing-text-model",W.copilotPr="copilot-pr"))(ee||={});var Za="tkn",Ya=class{constructor(){this._hosts=Object.create(null);this._ports=Object.create(null);this._connectionTokens=Object.create(null);this._preferredWebSchema="http";this._delegate=null;this._serverRootPath="/"}setPreferredWebSchema(t){this._preferredWebSchema=t}setDelegate(t){this._delegate=t}setServerRootPath(t,e){this._serverRootPath=z.join(e??"/",hm(t))}getServerRootPath(){return this._serverRootPath}get _remoteResourcesPath(){return z.join(this._serverRootPath,ee.vscodeRemoteResource)}set(t,e,n){this._hosts[t]=e,this._ports[t]=n}setConnectionToken(t,e){this._connectionTokens[t]=e}getPreferredWebSchema(){return this._preferredWebSchema}rewrite(t){if(this._delegate)try{return this._delegate(t)}catch(a){return fe(a),t}let e=t.authority,n=this._hosts[e];n&&n.indexOf(":")!==-1&&n.indexOf("[")===-1&&(n=`[${n}]`);let r=this._ports[e],o=this._connectionTokens[e],s=`path=${encodeURIComponent(t.path)}`;return typeof o=="string"&&(s+=`&${Za}=${encodeURIComponent(o)}`),b.from({scheme:In?this._preferredWebSchema:ee.vscodeRemoteResource,authority:`${n}:${r}`,path:In?(window.location.pathname+"/"+this._remoteResourcesPath).replace(/\/\/+/g,"/"):this._remoteResourcesPath,query:s})}},mm=new Ya;function hm(i){return`${i.quality??"oss"}-${i.commit??"dev"}`}var vm="vscode-app",Xa=class i{static{this.FALLBACK_AUTHORITY=vm}asBrowserUri(t){let e=this.toUri(t);return this.uriToBrowserUri(e)}uriToBrowserUri(t){return t.scheme===ee.vscodeRemote?mm.rewrite(t):t.scheme===ee.file&&(md||hd===`${ee.vscodeFileResource}://${i.FALLBACK_AUTHORITY}`)?t.with({scheme:ee.vscodeFileResource,authority:t.authority||i.FALLBACK_AUTHORITY,query:null,fragment:null}):t}asFileUri(t){let e=this.toUri(t);return this.uriToFileUri(e)}uriToFileUri(t){return t.scheme===ee.vscodeFileResource?t.with({scheme:ee.file,authority:t.authority!==i.FALLBACK_AUTHORITY?t.authority:null,query:null,fragment:null}):t}toUri(t){if(b.isUri(t))return t;if(globalThis._VSCODE_FILE_ROOT){let e=globalThis._VSCODE_FILE_ROOT;if(/^\w[\w\d+.-]*:\/\//.test(e))return b.joinPath(b.parse(e,!0),t);let n=q(e,t);return b.file(n)}throw new Error("Cannot determine URI for module id!")}},Xe=new Xa,Gy=Object.freeze({"Cache-Control":"no-cache, no-store"}),Jy=Object.freeze({"Document-Policy":"include-js-call-stacks-in-crash-reports"}),bm;(o=>{let i=new Map([["1",{"Cross-Origin-Opener-Policy":"same-origin"}],["2",{"Cross-Origin-Embedder-Policy":"require-corp"}],["3",{"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"require-corp"}]]);o.CoopAndCoep=Object.freeze(i.get("3"));let e="vscode-coi";function n(s){let a;typeof s=="string"?a=new URL(s).searchParams:s instanceof URL?a=s.searchParams:b.isUri(s)&&(a=new URL(s.toString(!0)).searchParams);let l=a?.get(e);if(l)return i.get(l)}o.getHeadersFromQuery=n;function r(s,a,l){if(!globalThis.crossOriginIsolated)return;let c=a&&l?"3":l?"2":"1";s instanceof URLSearchParams?s.set(e,c):s[e]=c}o.addSearchParam=r})(bm||={});function Lt(i){return li(i,!0)}var ci=class{constructor(t){this._ignorePathCasing=t}compare(t,e,n=!1){return t===e?0:ai(this.getComparisonKey(t,n),this.getComparisonKey(e,n))}isEqual(t,e,n=!1){return t===e?!0:!t||!e?!1:this.getComparisonKey(t,n)===this.getComparisonKey(e,n)}getComparisonKey(t,e=!1){return t.with({path:this._ignorePathCasing(t)?t.path.toLowerCase():void 0,fragment:e?null:void 0}).toString()}ignorePathCasing(t){return this._ignorePathCasing(t)}isEqualOrParent(t,e,n=!1){if(t.scheme===e.scheme){if(t.scheme===ee.file)return Ot(Lt(t),Lt(e),this._ignorePathCasing(t))&&t.query===e.query&&(n||t.fragment===e.fragment);if(Yd(t.authority,e.authority))return Ot(t.path,e.path,this._ignorePathCasing(t),"/")&&t.query===e.query&&(n||t.fragment===e.fragment)}return!1}joinPath(t,...e){return b.joinPath(t,...e)}basenameOrAuthority(t){return Ee(t)||t.authority}basename(t,e){return z.basename(t.path,e)}extname(t){return z.extname(t.path)}dirname(t){if(t.path.length===0)return t;let e;return t.scheme===ee.file?e=b.file(me(Lt(t))).path:(e=z.dirname(t.path),t.authority&&e.length&&e.charCodeAt(0)!==47&&(console.error(`dirname("${t.toString})) resulted in a relative path`),e="/")),t.with({path:e})}normalizePath(t){if(!t.path.length)return t;let e;return t.scheme===ee.file?e=b.file(ot(Lt(t))).path:e=z.normalize(t.path),t.with({path:e})}relativePath(t,e){if(t.scheme!==e.scheme||!Yd(t.authority,e.authority))return;if(t.scheme===ee.file){let o=wd(Lt(t),Lt(e));return B?To(o):o}let n=t.path||"/",r=e.path||"/";if(this._ignorePathCasing(t)){let o=0;for(let s=Math.min(n.length,r.length);o<s&&!(n.charCodeAt(o)!==r.charCodeAt(o)&&n.charAt(o).toLowerCase()!==r.charAt(o).toLowerCase());o++);n=r.substr(0,o)+n.substr(o)}return z.relative(n,r)}resolvePath(t,e){if(t.scheme===ee.file){let n=b.file(xn(Lt(t),e));return t.with({authority:n.authority,path:n.path})}return e=Bd(e),t.with({path:z.resolve(t.path,e)})}isAbsolutePath(t){return!!t.path&&t.path[0]==="/"}isEqualAuthority(t,e){return t===e||t!==void 0&&e!==void 0&&Cn(t,e)}hasTrailingPathSeparator(t,e=Se){if(t.scheme===ee.file){let n=Lt(t);return n.length>Ga(n).length&&n[n.length-1]===e}else{let n=t.path;return n.length>1&&n.charCodeAt(n.length-1)===47&&!/^[a-zA-Z]:(\/$|\\$)/.test(t.fsPath)}}removeTrailingPathSeparator(t,e=Se){return Xd(t,e)?t.with({path:t.path.substr(0,t.path.length-1)}):t}addTrailingPathSeparator(t,e=Se){let n=!1;if(t.scheme===ee.file){let r=Lt(t);n=r!==void 0&&r.length===Ga(r).length&&r[r.length-1]===e}else{e="/";let r=t.path;n=r.length===1&&r.charCodeAt(r.length-1)===47}return!n&&!Xd(t,e)?t.with({path:t.path+"/"}):t}},j=new ci(()=>!1),It=new ci(i=>i.scheme===ee.file?!ve:!0),el=new ci(i=>!0),ym=j.isEqual.bind(j),Zd=j.isEqualOrParent.bind(j),nI=j.getComparisonKey.bind(j),rI=j.basenameOrAuthority.bind(j),Ee=j.basename.bind(j),tl=j.extname.bind(j),on=j.dirname.bind(j),te=j.joinPath.bind(j),Ft=j.normalizePath.bind(j),iI=j.relativePath.bind(j),oI=j.resolvePath.bind(j),eu=j.isAbsolutePath.bind(j),Yd=j.isEqualAuthority.bind(j),Xd=j.hasTrailingPathSeparator.bind(j),sI=j.removeTrailingPathSeparator.bind(j),aI=j.addTrailingPathSeparator.bind(j);var Im;(o=>{o.META_DATA_LABEL="label",o.META_DATA_DESCRIPTION="description",o.META_DATA_SIZE="size",o.META_DATA_MIME="mime";function r(s){let a=new Map;s.path.substring(s.path.indexOf(";")+1,s.path.lastIndexOf(";")).split(";").forEach(p=>{let[u,f]=p.split(":");u&&f&&a.set(u,f)});let c=s.path.substring(0,s.path.indexOf(";"));return c&&a.set(o.META_DATA_MIME,c),a}o.parseMetaData=r})(Im||={});var tu=Symbol("MicrotaskDelay");function wo(i){return!!i&&typeof i.then=="function"}function ir(i){let t=new _e,e=i(t.token),n=!1,r=new Promise((o,s)=>{let a=t.token.onCancellationRequested(()=>{n=!0,a.dispose(),s(new Ae)});Promise.resolve(e).then(l=>{a.dispose(),t.dispose(),n?lo(l)&&l.dispose():o(l)},l=>{a.dispose(),t.dispose(),s(l)})});return new class{cancel(){t.cancel(),t.dispose()}then(o,s){return r.then(o,s)}catch(o){return this.then(void 0,o)}finally(o){return r.finally(o)}}}function iu(i){let t=-1,e=i.map((r,o)=>r.then(s=>(t=o,s))),n=Promise.race(e);return n.cancel=()=>{i.forEach((r,o)=>{o!==t&&r.cancel&&r.cancel()})},n.finally(()=>{n.cancel()}),n}var nl=class{constructor(){this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null,this.cancellationTokenSource=new _e}queue(t){if(this.cancellationTokenSource.token.isCancellationRequested)return Promise.reject(new Error("Throttler is disposed"));if(this.activePromise){if(this.queuedPromiseFactory=t,!this.queuedPromise){let e=()=>{if(this.queuedPromise=null,this.cancellationTokenSource.token.isCancellationRequested)return;let n=this.queue(this.queuedPromiseFactory);return this.queuedPromiseFactory=null,n};this.queuedPromise=new Promise(n=>{this.activePromise.then(e,e).then(n)})}return new Promise((e,n)=>{this.queuedPromise.then(e,n)})}return this.activePromise=t(this.cancellationTokenSource.token),new Promise((e,n)=>{this.activePromise.then(r=>{this.activePromise=null,e(r)},r=>{this.activePromise=null,n(r)})})}dispose(){this.cancellationTokenSource.cancel()}};var St=class{constructor(){this.promiseMap=new Map}queue(t,e){let r=(this.promiseMap.get(t)??Promise.resolve()).catch(()=>{}).then(e).finally(()=>{this.promiseMap.get(t)===r&&this.promiseMap.delete(t)});return this.promiseMap.set(t,r),r}peek(t){return this.promiseMap.get(t)||void 0}keys(){return this.promiseMap.keys()}},Tm=(i,t)=>{let e=!0,n=setTimeout(()=>{e=!1,t()},i);return{isTriggered:()=>e,dispose:()=>{clearTimeout(n),e=!1}}},xm=i=>{let t=!0;return queueMicrotask(()=>{t&&(t=!1,i())}),{isTriggered:()=>t,dispose:()=>{t=!1}}},di=class{constructor(t){this.defaultDelay=t;this.deferred=null,this.completionPromise=null,this.doResolve=null,this.doReject=null,this.task=null}trigger(t,e=this.defaultDelay){this.task=t,this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise((r,o)=>{this.doResolve=r,this.doReject=o}).then(()=>{if(this.completionPromise=null,this.doResolve=null,this.task){let r=this.task;return this.task=null,r()}}));let n=()=>{this.deferred=null,this.doResolve?.(null)};return this.deferred=e===tu?xm(n):Tm(e,n),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject?.(new Ae),this.completionPromise=null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}},Rn=class{constructor(t){this.delayer=new di(t),this.throttler=new nl}trigger(t,e){return this.delayer.trigger(()=>this.throttler.queue(t),e)}isTriggered(){return this.delayer.isTriggered()}cancel(){this.delayer.cancel()}dispose(){this.delayer.dispose(),this.throttler.dispose()}},Eo=class{constructor(){this._isOpen=!1,this._promise=new Promise((t,e)=>{this._completePromise=t})}isOpen(){return this._isOpen}open(){this._isOpen=!0,this._completePromise(!0)}wait(){return this._promise}};function Ut(i,t){return t?new Promise((e,n)=>{let r=setTimeout(()=>{o.dispose(),e()},i),o=t.onCancellationRequested(()=>{clearTimeout(r),o.dispose(),n(new Ae)})}):ir(e=>Ut(i,e))}function ou(i,t=0,e){let n=setTimeout(()=>{i(),e&&r.dispose()},t),r=w(()=>{clearTimeout(n),e?.delete(r)});return e?.add(r),r}var ui=class{constructor(t){this._size=0;this._isDisposed=!1;this.maxDegreeOfParalellism=t,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new x}whenIdle(){return this.size>0?Q.toPromise(this.onDrained):Promise.resolve()}get onDrained(){return this._onDrained.event}get size(){return this._size}queue(t){if(this._isDisposed)throw new Error("Object has been disposed");return this._size++,new Promise((e,n)=>{this.outstandingPromises.push({factory:t,c:e,e:n}),this.consume()})}consume(){for(;this.outstandingPromises.length&&this.runningPromises<this.maxDegreeOfParalellism;){let t=this.outstandingPromises.shift();this.runningPromises++;let e=t.factory();e.then(t.c,t.e),e.then(()=>this.consumed(),()=>this.consumed())}}consumed(){this._isDisposed||(this.runningPromises--,--this._size===0&&this._onDrained.fire(),this.outstandingPromises.length>0&&this.consume())}clear(){if(this._isDisposed)throw new Error("Object has been disposed");this.outstandingPromises.length=0,this._size=this.runningPromises}dispose(){this._isDisposed=!0,this.outstandingPromises.length=0,this._size=0,this._onDrained.dispose()}},rl=class extends ui{constructor(){super(1)}};var tr=class{constructor(){this.queues=new Map;this.drainers=new Set;this.drainListeners=void 0;this.drainListenerCount=0}async whenDrained(){if(this.isDrained())return;let t=new Be;return this.drainers.add(t),t.p}isDrained(){for(let[,t]of this.queues)if(t.size>0)return!1;return!0}queueSize(t,e=j){let n=e.getComparisonKey(t);return this.queues.get(n)?.size??0}queueFor(t,e,n=j){let r=n.getComparisonKey(t),o=this.queues.get(r);if(!o){o=new rl;let s=this.drainListenerCount++,a=Q.once(o.onDrained)(()=>{o?.dispose(),this.queues.delete(r),this.onDidQueueDrain(),this.drainListeners?.deleteAndDispose(s),this.drainListeners?.size===0&&(this.drainListeners.dispose(),this.drainListeners=void 0)});this.drainListeners||(this.drainListeners=new it),this.drainListeners.set(s,a),this.queues.set(r,o)}return o.queue(e)}onDidQueueDrain(){this.isDrained()&&this.releaseDrainers()}releaseDrainers(){for(let t of this.drainers)t.complete();this.drainers.clear()}dispose(){for(let[,t]of this.queues)t.dispose();this.queues.clear(),this.releaseDrainers(),this.drainListeners?.dispose()}};var nr=class{constructor(t,e){this.timeoutToken=void 0,this.runner=t,this.timeout=e,this.timeoutHandler=this.onTimeout.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearTimeout(this.timeoutToken),this.timeoutToken=void 0)}schedule(t=this.timeout){this.cancel(),this.timeoutToken=setTimeout(this.timeoutHandler,t)}get delay(){return this.timeout}set delay(t){this.timeout=t}isScheduled(){return this.timeoutToken!==void 0}flush(){this.isScheduled()&&(this.cancel(),this.doRun())}onTimeout(){this.timeoutToken=void 0,this.runner&&this.doRun()}doRun(){this.runner?.()}};var Co=class extends nr{constructor(e,n){super(e,n);this.units=[]}work(e){this.units.push(e),this.isScheduled()||this.schedule()}doRun(){let e=this.units;this.units=[],this.runner?.(e)}dispose(){this.units=[],super.dispose()}},rr=class extends L{constructor(e,n){super();this.options=e;this.handler=n;this.pendingWork=[];this.throttler=this._register(new Qt);this.disposed=!1;this.lastExecutionTime=0}get pending(){return this.pendingWork.length}work(e){if(this.disposed)return!1;if(typeof this.options.maxBufferedWork=="number"){if(this.throttler.value){if(this.pending+e.length>this.options.maxBufferedWork)return!1}else if(this.pending+e.length-this.options.maxWorkChunkSize>this.options.maxBufferedWork)return!1}for(let r of e)this.pendingWork.push(r);let n=Date.now()-this.lastExecutionTime;return!this.throttler.value&&(!this.options.waitThrottleDelayBetweenWorkUnits||n>=this.options.throttleDelay)?this.doWork():!this.throttler.value&&this.options.waitThrottleDelayBetweenWorkUnits&&this.scheduleThrottler(Math.max(this.options.throttleDelay-n,0)),!0}doWork(){this.lastExecutionTime=Date.now(),this.handler(this.pendingWork.splice(0,this.options.maxWorkChunkSize)),this.pendingWork.length>0&&this.scheduleThrottler()}scheduleThrottler(e=this.options.throttleDelay){this.throttler.value=new nr(()=>{this.throttler.clear(),this.doWork()},e),this.throttler.value.schedule()}dispose(){super.dispose(),this.pendingWork.length=0,this.disposed=!0}},_m,_o;(function(){let i=globalThis;typeof i.requestIdleCallback!="function"||typeof i.cancelIdleCallback!="function"?_o=(t,e,n)=>{vd(()=>{if(r)return;let o=Date.now()+15;e(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,o-Date.now())}}))});let r=!1;return{dispose(){r||(r=!0)}}}:_o=(t,e,n)=>{let r=t.requestIdleCallback(e,typeof n=="number"?{timeout:n}:void 0),o=!1;return{dispose(){o||(o=!0,t.cancelIdleCallback(r))}}},_m=(t,e)=>_o(globalThis,t,e)})();var il=class{constructor(t,e){this._didRun=!1;this._executor=()=>{try{this._value=e()}catch(n){this._error=n}finally{this._didRun=!0}},this._handle=_o(t,()=>this._executor())}dispose(){this._handle.dispose()}get value(){if(this._didRun||(this._handle.dispose(),this._executor()),this._error)throw this._error;return this._value}get isInitialized(){return this._didRun}},Ro=class extends il{constructor(t){super(globalThis,t)}};async function su(i,t,e){let n;for(let r=0;r<e;r++)try{return await i()}catch(o){n=o,await Ut(t)}throw n}var Be=class i{static fromPromise(t){let e=new i;return e.settleWith(t),e}get isRejected(){return this.outcome?.outcome===1}get isResolved(){return this.outcome?.outcome===0}get isSettled(){return!!this.outcome}get value(){return this.outcome?.outcome===0?this.outcome?.value:void 0}constructor(){this.p=new Promise((t,e)=>{this.completeCallback=t,this.errorCallback=e})}complete(t){return this.isSettled?Promise.resolve():new Promise(e=>{this.completeCallback(t),this.outcome={outcome:0,value:t},e()})}error(t){return this.isSettled?Promise.resolve():new Promise(e=>{this.errorCallback(t),this.outcome={outcome:1,value:t},e()})}settleWith(t){return t.then(e=>this.complete(e),e=>this.error(e))}cancel(){return this.error(new Ae)}},wn;(e=>{async function i(n){let r,o=await Promise.all(n.map(s=>s.then(a=>a,a=>{r||(r=a)})));if(typeof r<"u")throw r;return o}e.settled=i;function t(n){return new Promise(async(r,o)=>{try{await n(r,o)}catch(s){o(s)}})}e.withAsyncBody=t})(wn||={});var nu=class i{static fromArray(t){return new i(e=>{e.emitMany(t)})}static fromPromise(t){return new i(async e=>{e.emitMany(await t)})}static fromPromisesResolveOrder(t){return new i(async e=>{await Promise.all(t.map(async n=>e.emitOne(await n)))})}static merge(t){return new i(async e=>{await Promise.all(t.map(async n=>{for await(let r of n)e.emitOne(r)}))})}static{this.EMPTY=i.fromArray([])}constructor(t,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new x,queueMicrotask(async()=>{let n={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(n)),this.resolve()}catch(r){this.reject(r)}finally{n.emitOne=void 0,n.emitMany=void 0,n.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await Q.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,e){return new i(async n=>{for await(let r of t)n.emitOne(e(r))})}map(t){return i.map(this,t)}static filter(t,e){return new i(async n=>{for await(let r of t)e(r)&&n.emitOne(r)})}filter(t){return i.filter(this,t)}static coalesce(t){return i.filter(t,e=>!!e)}coalesce(){return i.coalesce(this)}static async toPromise(t){let e=[];for await(let n of t)e.push(n);return e}toPromise(){return i.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};var ol=class{constructor(){this._unsatisfiedConsumers=[];this._unconsumedValues=[]}get hasFinalValue(){return!!this._finalValue}produce(t){if(this._ensureNoFinalValue(),this._unsatisfiedConsumers.length>0){let e=this._unsatisfiedConsumers.shift();this._resolveOrRejectDeferred(e,t)}else this._unconsumedValues.push(t)}produceFinal(t){this._ensureNoFinalValue(),this._finalValue=t;for(let e of this._unsatisfiedConsumers)this._resolveOrRejectDeferred(e,t);this._unsatisfiedConsumers.length=0}_ensureNoFinalValue(){if(this._finalValue)throw new ae("ProducerConsumer: cannot produce after final value has been set")}_resolveOrRejectDeferred(t,e){e.ok?t.complete(e.value):t.error(e.error)}consume(){if(this._unconsumedValues.length>0||this._finalValue){let t=this._unconsumedValues.length>0?this._unconsumedValues.shift():this._finalValue;return t.ok?Promise.resolve(t.value):Promise.reject(t.error)}else{let t=new Be;return this._unsatisfiedConsumers.push(t),t.p}}},ru=class i{constructor(t,e){this._onReturn=e;this._producerConsumer=new ol;this._iterator={next:()=>this._producerConsumer.consume(),return:()=>(this._onReturn?.(),Promise.resolve({done:!0,value:void 0})),throw:async t=>(this._finishError(t),{done:!0,value:void 0})};queueMicrotask(async()=>{let n=t({emitOne:r=>this._producerConsumer.produce({ok:!0,value:{done:!1,value:r}}),emitMany:r=>{for(let o of r)this._producerConsumer.produce({ok:!0,value:{done:!1,value:o}})},reject:r=>this._finishError(r)});if(!this._producerConsumer.hasFinalValue)try{await n,this._finishOk()}catch(r){this._finishError(r)}})}static fromArray(t){return new i(e=>{e.emitMany(t)})}static fromPromise(t){return new i(async e=>{e.emitMany(await t)})}static fromPromisesResolveOrder(t){return new i(async e=>{await Promise.all(t.map(async n=>e.emitOne(await n)))})}static merge(t){return new i(async e=>{await Promise.all(t.map(async n=>{for await(let r of n)e.emitOne(r)}))})}static{this.EMPTY=i.fromArray([])}static map(t,e){return new i(async n=>{for await(let r of t)n.emitOne(e(r))})}static tee(t){let e,n,r=new Be,o=async()=>{if(!(!e||!n))try{for await(let l of t)e.emitOne(l),n.emitOne(l)}catch(l){e.reject(l),n.reject(l)}finally{r.complete()}},s=new i(async l=>(e=l,o(),r.p)),a=new i(async l=>(n=l,o(),r.p));return[s,a]}map(t){return i.map(this,t)}static coalesce(t){return i.filter(t,e=>!!e)}coalesce(){return i.coalesce(this)}static filter(t,e){return new i(async n=>{for await(let r of t)e(r)&&n.emitOne(r)})}filter(t){return i.filter(this,t)}_finishOk(){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!0,value:{done:!0,value:void 0}})}_finishError(t){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!1,error:t})}[Symbol.asyncIterator](){return this._iterator}};function pi(i){let t=i;return t?[t.on,t.pause,t.resume,t.destroy].every(e=>typeof e=="function"):!1}function Po(i){let t=i;return t?pi(t.stream)&&Array.isArray(t.buffer)&&typeof t.ended=="boolean":!1}function Nt(i,t){return new sl(i,t)}var sl=class{constructor(t,e){this.reducer=t;this.options=e;this.state={flowing:!1,ended:!1,destroyed:!1};this.buffer={data:[],error:[]};this.listeners={data:[],error:[],end:[]};this.pendingWritePromises=[]}pause(){this.state.destroyed||(this.state.flowing=!1)}resume(){this.state.destroyed||this.state.flowing||(this.state.flowing=!0,this.flowData(),this.flowErrors(),this.flowEnd())}write(t){if(!this.state.destroyed){if(this.state.flowing)this.emitData(t);else if(this.buffer.data.push(t),typeof this.options?.highWaterMark=="number"&&this.buffer.data.length>this.options.highWaterMark)return new Promise(e=>this.pendingWritePromises.push(e))}}error(t){this.state.destroyed||(this.state.flowing?this.emitError(t):this.buffer.error.push(t))}end(t){this.state.destroyed||(typeof t<"u"&&this.write(t),this.state.flowing?(this.emitEnd(),this.destroy()):this.state.ended=!0)}emitData(t){this.listeners.data.slice(0).forEach(e=>e(t))}emitError(t){this.listeners.error.length===0?fe(t):this.listeners.error.slice(0).forEach(e=>e(t))}emitEnd(){this.listeners.end.slice(0).forEach(t=>t())}on(t,e){if(!this.state.destroyed)switch(t){case"data":this.listeners.data.push(e),this.resume();break;case"end":this.listeners.end.push(e),this.state.flowing&&this.flowEnd()&&this.destroy();break;case"error":this.listeners.error.push(e),this.state.flowing&&this.flowErrors();break}}removeListener(t,e){if(this.state.destroyed)return;let n;switch(t){case"data":n=this.listeners.data;break;case"end":n=this.listeners.end;break;case"error":n=this.listeners.error;break}if(n){let r=n.indexOf(e);r>=0&&n.splice(r,1)}}flowData(){if(this.buffer.data.length===0)return;if(typeof this.reducer=="function"){let e=this.reducer(this.buffer.data);this.emitData(e)}else for(let e of this.buffer.data)this.emitData(e);this.buffer.data.length=0;let t=[...this.pendingWritePromises];this.pendingWritePromises.length=0,t.forEach(e=>e())}flowErrors(){if(this.listeners.error.length>0){for(let t of this.buffer.error)this.emitError(t);this.buffer.error.length=0}}flowEnd(){return this.state.ended?(this.emitEnd(),this.listeners.end.length>0):!1}destroy(){this.state.destroyed||(this.state.destroyed=!0,this.state.ended=!0,this.buffer.data.length=0,this.buffer.error.length=0,this.listeners.data.length=0,this.listeners.error.length=0,this.listeners.end.length=0,this.pendingWritePromises.length=0)}};function au(i,t){let e=[],n;for(;(n=i.read())!==null;)e.push(n);return t(e)}function lu(i,t,e){let n=[],r;for(;(r=i.read())!==null&&n.length<e;)n.push(r);return r===null&&n.length>0?t(n):{read:()=>{if(n.length>0)return n.shift();if(typeof r<"u"){let o=r;return r=void 0,o}return i.read()}}}function Ao(i,t){return new Promise((e,n)=>{let r=[];ko(i,{onData:o=>{t&&r.push(o)},onError:o=>{t?n(o):e(void 0)},onEnd:()=>{e(t?t(r):void 0)}})})}function ko(i,t,e){i.on("error",n=>{e?.isCancellationRequested||t.onError(n)}),i.on("end",()=>{e?.isCancellationRequested||t.onEnd()}),i.on("data",n=>{e?.isCancellationRequested||t.onData(n)})}function cu(i,t){return new Promise((e,n)=>{let r=new N,o=[],s=c=>{if(o.push(c),o.length>t)return r.dispose(),i.pause(),e({stream:i,buffer:o,ended:!1})},a=c=>(r.dispose(),n(c)),l=()=>(r.dispose(),e({stream:i,buffer:o,ended:!0}));r.add(w(()=>i.removeListener("error",a))),i.on("error",a),r.add(w(()=>i.removeListener("end",l))),i.on("end",l),r.add(w(()=>i.removeListener("data",s))),i.on("data",s)})}function du(i){let t=!1;return{read:()=>t?null:(t=!0,i)}}function al(i,t,e){let n=Nt(e);return ko(i,{onData:r=>n.write(t.data(r)),onError:r=>n.error(t.error?t.error(r):r),onEnd:()=>n.end()}),n}var fi=typeof Buffer<"u",Cm=new He(()=>new Uint8Array(256)),ll,cl,_=class i{static alloc(t){return fi?new i(Buffer.allocUnsafe(t)):new i(new Uint8Array(t))}static wrap(t){return fi&&!Buffer.isBuffer(t)&&(t=Buffer.from(t.buffer,t.byteOffset,t.byteLength)),new i(t)}static fromString(t,e){return!(e?.dontUseNodeBuffer||!1)&&fi?new i(Buffer.from(t)):(ll||(ll=new TextEncoder),new i(ll.encode(t)))}static fromByteArray(t){let e=i.alloc(t.length);for(let n=0,r=t.length;n<r;n++)e.buffer[n]=t[n];return e}static concat(t,e){if(typeof e>"u"){e=0;for(let o=0,s=t.length;o<s;o++)e+=t[o].byteLength}let n=i.alloc(e),r=0;for(let o=0,s=t.length;o<s;o++){let a=t[o];n.set(a,r),r+=a.byteLength}return n}static isNativeBuffer(t){return fi&&Buffer.isBuffer(t)}constructor(t){this.buffer=t,this.byteLength=this.buffer.byteLength}clone(){let t=i.alloc(this.byteLength);return t.set(this),t}toString(){return fi?this.buffer.toString():(cl||(cl=new TextDecoder(void 0,{ignoreBOM:!0})),cl.decode(this.buffer))}slice(t,e){return new i(this.buffer.subarray(t,e))}set(t,e){if(t instanceof i)this.buffer.set(t.buffer,e);else if(t instanceof Uint8Array)this.buffer.set(t,e);else if(t instanceof ArrayBuffer)this.buffer.set(new Uint8Array(t),e);else if(ArrayBuffer.isView(t))this.buffer.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),e);else throw new Error("Unknown argument 'array'")}readUInt32BE(t){return wm(this.buffer,t)}writeUInt32BE(t,e){Pm(this.buffer,t,e)}readUInt32LE(t){return Am(this.buffer,t)}writeUInt32LE(t,e){km(this.buffer,t,e)}readUInt8(t){return Dm(this.buffer,t)}writeUInt8(t,e){Om(this.buffer,t,e)}indexOf(t,e=0){return Rm(this.buffer,t instanceof i?t.buffer:t,e)}equals(t){return this===t?!0:this.byteLength!==t.byteLength?!1:this.buffer.every((e,n)=>e===t.buffer[n])}};function Rm(i,t,e=0){let n=t.byteLength,r=i.byteLength;if(n===0)return 0;if(n===1)return i.indexOf(t[0],e);if(n>r-e)return-1;let o=Cm.value;o.fill(t.length);for(let c=0;c<t.length;c++)o[t[c]]=t.length-c-1;let s=e+t.length-1,a=s,l=-1;for(;s<r;)if(i[s]===t[a]){if(a===0){l=s;break}s--,a--}else s+=Math.max(t.length-a,o[i[s]]),a=t.length-1;return l}function wm(i,t){return i[t]*2**24+i[t+1]*2**16+i[t+2]*2**8+i[t+3]}function Pm(i,t,e){i[e+3]=t,t=t>>>8,i[e+2]=t,t=t>>>8,i[e+1]=t,t=t>>>8,i[e]=t}function Am(i,t){return i[t+0]<<0>>>0|i[t+1]<<8>>>0|i[t+2]<<16>>>0|i[t+3]<<24>>>0}function km(i,t,e){i[e+0]=t&255,t=t>>>8,i[e+1]=t&255,t=t>>>8,i[e+2]=t&255,t=t>>>8,i[e+3]=t&255}function Dm(i,t){return i[t]}function Om(i,t,e){i[e]=t}function fu(i){return au(i,t=>_.concat(t))}function gu(i){return du(i)}function gi(i){return Ao(i,t=>_.concat(t))}async function mu(i){return i.ended?_.concat(i.buffer):_.concat([...i.buffer,await gi(i.stream)])}function hu(i){return Nt(t=>_.concat(t),i)}function Do(i){let t=0,e=0,n=0,r=new Uint8Array(Math.floor(i.length/4*3)),o=a=>{switch(e){case 3:r[n++]=t|a,e=0;break;case 2:r[n++]=t|a>>>2,t=a<<6,e=3;break;case 1:r[n++]=t|a>>>4,t=a<<4,e=2;break;default:t=a<<2,e=1}};for(let a=0;a<i.length;a++){let l=i.charCodeAt(a);if(l>=65&&l<=90)o(l-65);else if(l>=97&&l<=122)o(l-97+26);else if(l>=48&&l<=57)o(l-48+52);else if(l===43||l===45)o(62);else if(l===47||l===95)o(63);else{if(l===61)break;throw new SyntaxError(`Unexpected base64 character ${i[a]}`)}}let s=n;for(;e>0;)o(0);return _.wrap(r).slice(0,s)}var uu="0123456789abcdef";function sn({buffer:i}){let t="";for(let e=0;e<i.length;e++){let n=i[e];t+=uu[n>>>4],t+=uu[n&15]}return t}function dl(i){if(i.length%2!==0)throw new SyntaxError("Hex string must have an even length");let t=new Uint8Array(i.length>>1);for(let e=0;e<i.length;)t[e>>1]=pu(i,e++)<<4|pu(i,e++);return _.wrap(t)}function pu(i,t){let e=i.charCodeAt(t);if(e>=48&&e<=57)return e-48;if(e>=97&&e<=102)return e-87;if(e>=65&&e<=70)return e-55;throw new SyntaxError(`Invalid hex character at position ${t}`)}function J(i,t,e){let n=null,r=null;if(typeof e.value=="function"?(n="value",r=e.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof e.get=="function"&&(n="get",r=e.get),!r)throw new Error("not supported");let o=`$memoize$${t}`;e[n]=function(...s){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,s)}),this[o]}}function mi(i,t=0){if(!i||t>200)return i;if(typeof i=="object"){switch(i.$mid){case 1:return b.revive(i);case 2:return new RegExp(i.source,i.flags);case 17:return new Date(i.source)}if(i instanceof _||i instanceof Uint8Array)return i;if(Array.isArray(i))for(let e=0;e<i.length;++e)i[e]=mi(i[e],t+1);else for(let e in i)Object.hasOwnProperty.call(i,e)&&(i[e]=mi(i[e],t+1))}return i}function ar(i){switch(i){case 100:return"req";case 101:return"cancel";case 102:return"subscribe";case 103:return"unsubscribe"}}function Oo(i){switch(i){case 200:return"init";case 201:return"reply:";case 202:case 203:return"replyErr:";case 204:return"event:"}}function or(i){let t=0;for(let e=0;;e+=7){let n=i.read(1);if(t|=(n.buffer[0]&127)<<e,!(n.buffer[0]&128))return t}}var Lm=an(0);function sr(i,t){if(t===0){i.write(Lm);return}let e=0;for(let r=t;r!==0;r=r>>>7)e++;let n=_.alloc(e);for(let r=0;t!==0;r++)n.buffer[r]=t&127,t=t>>>7,t>0&&(n.buffer[r]|=128);i.write(n)}var hi=class{constructor(t){this.buffer=t;this.pos=0}read(t){let e=this.buffer.slice(this.pos,this.pos+t);return this.pos+=e.byteLength,e}},Lo=class{constructor(){this.buffers=[]}get buffer(){return _.concat(this.buffers)}write(t){this.buffers.push(t)}};function an(i){let t=_.alloc(1);return t.writeUInt8(i,0),t}var Pn={Undefined:an(0),String:an(1),Buffer:an(2),VSBuffer:an(3),Array:an(4),Object:an(5),Uint:an(6)};function vi(i,t){if(typeof t>"u")i.write(Pn.Undefined);else if(typeof t=="string"){let e=_.fromString(t);i.write(Pn.String),sr(i,e.byteLength),i.write(e)}else if(_.isNativeBuffer(t)){let e=_.wrap(t);i.write(Pn.Buffer),sr(i,e.byteLength),i.write(e)}else if(t instanceof _)i.write(Pn.VSBuffer),sr(i,t.byteLength),i.write(t);else if(Array.isArray(t)){i.write(Pn.Array),sr(i,t.length);for(let e of t)vi(i,e)}else if(typeof t=="number"&&(t|0)===t)i.write(Pn.Uint),sr(i,t);else{let e=_.fromString(JSON.stringify(t));i.write(Pn.Object),sr(i,e.byteLength),i.write(e)}}function cr(i){switch(i.read(1).readUInt8(0)){case 0:return;case 1:return i.read(or(i)).toString();case 2:return i.read(or(i)).buffer;case 3:return i.read(or(i));case 4:{let e=or(i),n=[];for(let r=0;r<e;r++)n.push(cr(i));return n}case 5:return JSON.parse(i.read(or(i)).toString());case 6:return or(i)}}var bi=class{constructor(t,e,n=null,r=1e3){this.protocol=t;this.ctx=e;this.logger=n;this.timeoutDelay=r;this.channels=new Map;this.activeRequests=new Map;this.pendingRequests=new Map;this.protocolListener=this.protocol.onMessage(o=>this.onRawMessage(o)),this.sendResponse({type:200})}registerChannel(t,e){this.channels.set(t,e),setTimeout(()=>this.flushPendingRequests(t),0)}sendResponse(t){switch(t.type){case 200:{let e=this.send([t.type]);this.logger?.logOutgoing(e,0,1,Oo(t.type));return}case 201:case 202:case 204:case 203:{let e=this.send([t.type,t.id],t.data);this.logger?.logOutgoing(e,t.id,1,Oo(t.type),t.data);return}}}send(t,e=void 0){let n=new Lo;return vi(n,t),vi(n,e),this.sendBuffer(n.buffer)}sendBuffer(t){try{return this.protocol.send(t),t.byteLength}catch{return 0}}onRawMessage(t){let e=new hi(t),n=cr(e),r=cr(e),o=n[0];switch(o){case 100:return this.logger?.logIncoming(t.byteLength,n[1],1,`${ar(o)}: ${n[2]}.${n[3]}`,r),this.onPromise({type:o,id:n[1],channelName:n[2],name:n[3],arg:r});case 102:return this.logger?.logIncoming(t.byteLength,n[1],1,`${ar(o)}: ${n[2]}.${n[3]}`,r),this.onEventListen({type:o,id:n[1],channelName:n[2],name:n[3],arg:r});case 101:return this.logger?.logIncoming(t.byteLength,n[1],1,`${ar(o)}`),this.disposeActiveRequest({type:o,id:n[1]});case 103:return this.logger?.logIncoming(t.byteLength,n[1],1,`${ar(o)}`),this.disposeActiveRequest({type:o,id:n[1]})}}onPromise(t){let e=this.channels.get(t.channelName);if(!e){this.collectPendingRequest(t);return}let n=new _e,r;try{r=e.call(this.ctx,t.name,t.arg,n.token)}catch(a){r=Promise.reject(a)}let o=t.id;r.then(a=>{this.sendResponse({id:o,data:a,type:201})},a=>{a instanceof Error?this.sendResponse({id:o,data:{message:a.message,name:a.name,stack:a.stack?a.stack.split(`
`):void 0},type:202}):this.sendResponse({id:o,data:a,type:203})}).finally(()=>{s.dispose(),this.activeRequests.delete(t.id)});let s=w(()=>n.cancel());this.activeRequests.set(t.id,s)}onEventListen(t){let e=this.channels.get(t.channelName);if(!e){this.collectPendingRequest(t);return}let n=t.id,o=e.listen(this.ctx,t.name,t.arg)(s=>this.sendResponse({id:n,data:s,type:204}));this.activeRequests.set(t.id,o)}disposeActiveRequest(t){let e=this.activeRequests.get(t.id);e&&(e.dispose(),this.activeRequests.delete(t.id))}collectPendingRequest(t){let e=this.pendingRequests.get(t.channelName);e||(e=[],this.pendingRequests.set(t.channelName,e));let n=setTimeout(()=>{console.error(`Unknown channel: ${t.channelName}`),t.type===100&&this.sendResponse({id:t.id,data:{name:"Unknown channel",message:`Channel name '${t.channelName}' timed out after ${this.timeoutDelay}ms`,stack:void 0},type:202})},this.timeoutDelay);e.push({request:t,timeoutTimer:n})}flushPendingRequests(t){let e=this.pendingRequests.get(t);if(e){for(let n of e)switch(clearTimeout(n.timeoutTimer),n.request.type){case 100:this.onPromise(n.request);break;case 102:this.onEventListen(n.request);break}this.pendingRequests.delete(t)}}dispose(){this.protocolListener&&(this.protocolListener.dispose(),this.protocolListener=null),Ke(this.activeRequests.values()),this.activeRequests.clear()}};var lr=class{constructor(t,e=null){this.protocol=t;this.isDisposed=!1;this.state=0;this.activeRequests=new Set;this.handlers=new Map;this.lastRequestId=0;this._onDidInitialize=new x;this.onDidInitialize=this._onDidInitialize.event;this.protocolListener=this.protocol.onMessage(n=>this.onBuffer(n)),this.logger=e}getChannel(t){let e=this;return{call(n,r,o){return e.isDisposed?Promise.reject(new Ae):e.requestPromise(t,n,r,o)},listen(n,r){return e.isDisposed?Q.None:e.requestEvent(t,n,r)}}}requestPromise(t,e,n,r=Ze.None){let o=this.lastRequestId++,a={id:o,type:100,channelName:t,name:e,arg:n};if(r.isCancellationRequested)return Promise.reject(new Ae);let l,c;return new Promise((u,f)=>{if(r.isCancellationRequested)return f(new Ae);let m=()=>{let I=y=>{switch(y.type){case 201:this.handlers.delete(o),u(y.data);break;case 202:{this.handlers.delete(o);let S=new Error(y.data.message);S.stack=Array.isArray(y.data.stack)?y.data.stack.join(`
`):y.data.stack,S.name=y.data.name,f(S);break}case 203:this.handlers.delete(o),f(y.data);break}};this.handlers.set(o,I),this.sendRequest(a)},v=null;this.state===1?m():(v=ir(I=>this.whenInitialized()),v.then(()=>{v=null,m()}));let h=()=>{v?(v.cancel(),v=null):this.sendRequest({id:o,type:101}),f(new Ae)};l=r.onCancellationRequested(h),c={dispose:zn(()=>{h(),l.dispose()})},this.activeRequests.add(c)}).finally(()=>{l?.dispose(),this.activeRequests.delete(c)})}requestEvent(t,e,n){let r=this.lastRequestId++,s={id:r,type:102,channelName:t,name:e,arg:n},a=null,l=new x({onWillAddFirstListener:()=>{let p=()=>{this.activeRequests.add(l),this.sendRequest(s)};this.state===1?p():(a=ir(u=>this.whenInitialized()),a.then(()=>{a=null,p()}))},onDidRemoveLastListener:()=>{a?(a.cancel(),a=null):(this.activeRequests.delete(l),this.sendRequest({id:r,type:103})),this.handlers.delete(r)}}),c=p=>l.fire(p.data);return this.handlers.set(r,c),l.event}sendRequest(t){switch(t.type){case 100:case 102:{let e=this.send([t.type,t.id,t.channelName,t.name],t.arg);this.logger?.logOutgoing(e,t.id,0,`${ar(t.type)}: ${t.channelName}.${t.name}`,t.arg);return}case 101:case 103:{let e=this.send([t.type,t.id]);this.logger?.logOutgoing(e,t.id,0,ar(t.type));return}}}send(t,e=void 0){let n=new Lo;return vi(n,t),vi(n,e),this.sendBuffer(n.buffer)}sendBuffer(t){try{return this.protocol.send(t),t.byteLength}catch{return 0}}onBuffer(t){let e=new hi(t),n=cr(e),r=cr(e),o=n[0];switch(o){case 200:return this.logger?.logIncoming(t.byteLength,0,0,Oo(o)),this.onResponse({type:n[0]});case 201:case 202:case 204:case 203:return this.logger?.logIncoming(t.byteLength,n[1],0,Oo(o),r),this.onResponse({type:n[0],id:n[1],data:r})}}onResponse(t){if(t.type===200){this.state=1,this._onDidInitialize.fire();return}this.handlers.get(t.id)?.(t)}get onDidInitializePromise(){return Q.toPromise(this.onDidInitialize)}whenInitialized(){return this.state===1?Promise.resolve():this.onDidInitializePromise}dispose(){this.isDisposed=!0,this.protocolListener&&(this.protocolListener.dispose(),this.protocolListener=null),Ke(this.activeRequests.values()),this.activeRequests.clear(),this._onDidInitialize.dispose()}};O([J],lr.prototype,"onDidInitializePromise",1);var Fo=class{constructor(t,e,n){this.channels=new Map;this._connections=new Set;this._onDidAddConnection=new x;this.onDidAddConnection=this._onDidAddConnection.event;this._onDidRemoveConnection=new x;this.onDidRemoveConnection=this._onDidRemoveConnection.event;this.disposables=new N;this.disposables.add(t(({protocol:r,onDidClientDisconnect:o})=>{let s=Q.once(r.onMessage);this.disposables.add(s(a=>{let l=new hi(a),c=cr(l),p=new bi(r,c,e,n),u=new lr(r,e);this.channels.forEach((m,v)=>p.registerChannel(v,m));let f={channelServer:p,channelClient:u,ctx:c};this._connections.add(f),this._onDidAddConnection.fire(f),this.disposables.add(o(()=>{p.dispose(),u.dispose(),this._connections.delete(f),this._onDidRemoveConnection.fire(f)}))}))}))}get connections(){let t=[];return this._connections.forEach(e=>t.push(e)),t}getChannel(t,e){let n=this;return{call(r,o,s){let a;if(Zr(e)){let c=jc(n.connections.filter(e));a=c?Promise.resolve(c):Q.toPromise(Q.filter(n.onDidAddConnection,e))}else a=e.routeCall(n,r,o);let l=a.then(c=>c.channelClient.getChannel(t));return vu(l).call(r,o,s)},listen(r,o){if(Zr(e))return n.getMulticastEvent(t,e,r,o);let s=e.routeEvent(n,r,o).then(a=>a.channelClient.getChannel(t));return vu(s).listen(r,o)}}}getMulticastEvent(t,e,n,r){let o=this,s,a=new x({onWillAddFirstListener:()=>{s=new N;let l=new vo,c=new Map,p=f=>{let v=f.channelClient.getChannel(t).listen(n,r),h=l.add(v);c.set(f,h)},u=f=>{let m=c.get(f);m&&(m.dispose(),c.delete(f))};o.connections.filter(e).forEach(p),Q.filter(o.onDidAddConnection,e)(p,void 0,s),o.onDidRemoveConnection(u,void 0,s),l.event(a.fire,a,s),s.add(l)},onDidRemoveLastListener:()=>{s?.dispose(),s=void 0}});return o.disposables.add(a),a.event}registerChannel(t,e){this.channels.set(t,e);for(let n of this._connections)n.channelServer.registerChannel(t,e)}dispose(){this.disposables.dispose();for(let t of this._connections)t.channelClient.dispose(),t.channelServer.dispose();this._connections.clear(),this.channels.clear(),this._onDidAddConnection.dispose(),this._onDidRemoveConnection.dispose()}};function vu(i){return{call(t,e,n){return i.then(r=>r.call(t,e,n))},listen(t,e){let n=new oi;return i.then(r=>n.input=r.listen(t,e)),n.event}}}function bu(i){let t=!1;return{call(e,n,r){return t?i.call(e,n,r):Ut(0).then(()=>t=!0).then(()=>i.call(e,n,r))},listen(e,n){if(t)return i.listen(e,n);let r=new oi;return Ut(0).then(()=>t=!0).then(()=>r.input=i.listen(e,n)),r.event}}}var dr;(r=>{function i(o,s,a){let l=o,c=a?.disableMarshalling,p=new Map;for(let u in l)e(u)&&p.set(u,Q.buffer(l[u],u,!0,void 0,s));return new class{listen(u,f,m){let v=p.get(f);if(v)return v;let h=l[f];if(typeof h=="function"){if(n(f))return h.call(l,m);if(e(f))return p.set(f,Q.buffer(l[f],f,!0,void 0,s)),p.get(f)}throw new vt(`Event not found: ${f}`)}call(u,f,m){let v=l[f];if(typeof v=="function"){if(!c&&Array.isArray(m))for(let I=0;I<m.length;I++)m[I]=mi(m[I]);let h=v.apply(l,m);return h instanceof Promise||(h=Promise.resolve(h)),h}throw new vt(`Method not found: ${f}`)}}}r.fromService=i;function t(o,s){let a=s?.disableMarshalling;return new Proxy({},{get(l,c){if(typeof c=="string")return s?.properties?.has(c)?s.properties.get(c):n(c)?function(p){return o.listen(c,p)}:e(c)?o.listen(c):async function(...p){let u;s&&!Xr(s.context)?u=[s.context,...p]:u=p;let f=await o.call(c,u);return a?f:mi(f)};throw new vt(`Property not found: ${String(c)}`)}})}r.toService=t;function e(o){return o[0]==="o"&&o[1]==="n"&&za(o.charCodeAt(2))}function n(o){return/^onDynamic/.test(o)&&za(o.charCodeAt(9))}})(dr||={});import{fork as ah}from"child_process";function yu(i){let t=i;return t&&typeof t.type=="string"&&typeof t.severity=="string"}function Fm(i){let t=[],e;try{let n=JSON.parse(i.arguments),r=n[n.length-1];r&&r.__$stack&&(n.pop(),e=r.__$stack),t.push(...n)}catch{t.push("Unable to log remote console arguments",i.arguments)}return{args:t,stack:e}}function Um(i){if(!i)return i;let t=i.indexOf(`
`);return t===-1?i:i.substring(0,t)}function Iu(i,t){let{args:e,stack:n}=Fm(i),r=typeof e[0]=="string"&&e.length===1,o=Um(n);o&&(o=`(${o.trim()})`);let s=[];if(typeof e[0]=="string"?o&&r?s=[`%c[${t}] %c${e[0]} %c${o}`,ur("blue"),ur(""),ur("grey")]:s=[`%c[${t}] %c${e[0]}`,ur("blue"),ur(""),...e.slice(1)]:s=[`%c[${t}]%`,ur("blue"),...e],o&&!r&&s.push(o),typeof console[i.severity]!="function")throw new Error("Unknown console method");console[i.severity].apply(console,s)}function ur(i){return`color: ${i}`}function pl(i){if(!i||typeof i!="object"||i instanceof RegExp)return i;let t=Array.isArray(i)?[]:{};return Object.entries(i).forEach(([e,n])=>{t[e]=n&&typeof n=="object"?pl(n):n}),t}var Nm=Object.prototype.hasOwnProperty;function fl(i,t){return ul(i,t,new Set)}function ul(i,t,e){if(Xr(i))return i;let n=t(i);if(typeof n<"u")return n;if(Array.isArray(i)){let r=[];for(let o of i)r.push(ul(o,t,e));return r}if(so(i)){if(e.has(i))throw new Error("Cannot clone recursive data-structure");e.add(i);let r={};for(let o in i)Nm.call(i,o)&&(r[o]=ul(i[o],t,e));return e.delete(i),r}return i}function An(i,t){if(i===t)return!0;if(i==null||t===null||t===void 0||typeof i!=typeof t||typeof i!="object"||Array.isArray(i)!==Array.isArray(t))return!1;let e,n;if(Array.isArray(i)){if(i.length!==t.length)return!1;for(e=0;e<i.length;e++)if(!An(i[e],t[e]))return!1}else{let r=[];for(n in i)r.push(n);r.sort();let o=[];for(n in t)o.push(n);if(o.sort(),!An(r,o))return!1;for(e=0;e<r.length;e++)if(!An(i[r[e]],t[r[e]]))return!1}return!0}import*as sh from"child_process";import{promises as D0}from"fs";function Su(i){i&&(delete i.DEBUG,ve&&delete i.LD_PRELOAD)}import*as M from"fs";import{tmpdir as qm}from"os";import{promisify as Ii}from"util";var Mm=new bt(1e4);function yi(i){return Tu(i,"NFC",Mm)}var Wm=new bt(1e4);function Bm(i){return Tu(i,"NFD",Wm)}var $m=/[^\u0000-\u0080]/;function Tu(i,t,e){if(!i)return i;let n=e.get(i);if(n)return n;let r;return $m.test(i)?r=i.normalize(t):r=i,e.set(i,r),r}var Vm=(function(){let i=new bt(1e4),t=/[\u0300-\u036f]/g;return function(e){let n=i.get(e);if(n)return n;let r=Bm(e).replace(t,""),o=(r.length===e.length?r:e).toLowerCase();return i.set(e,o),o}})();async function Eu(i,t=0,e){if(Ja(i))throw new Error("rimraf - will refuse to recursively delete root");return t===0?gl(i):Km(i,e)}async function Km(i,t=Kd(qm())){try{try{await M.promises.rename(i,t)}catch(e){return e.code==="ENOENT"?void 0:gl(i)}gl(t).catch(()=>{})}catch(e){if(e.code!=="ENOENT")throw e}}async function gl(i){return M.promises.rm(i,{recursive:!0,force:!0,maxRetries:3})}async function Uo(i,t){try{return await xu(i,t)}catch(e){if(e.code==="ENOENT"&&B&&Ja(i))try{return await xu(`${i}.`,t)}catch{}throw e}}async function xu(i,t){return jm(await(t?zm(i):M.promises.readdir(i)))}async function zm(i){try{return await M.promises.readdir(i,{withFileTypes:!0})}catch(n){n.code!=="ENOENT"&&console.warn("[node.js fs] readdir with filetypes failed with error: ",n)}let t=[],e=await Uo(i);for(let n of e){let r=!1,o=!1,s=!1;try{let a=await M.promises.lstat(q(i,n));r=a.isFile(),o=a.isDirectory(),s=a.isSymbolicLink()}catch(a){a.code!=="ENOENT"&&console.warn("[node.js fs] unexpected error from lstat after readdir: ",a)}t.push({name:n,isFile:()=>r,isDirectory:()=>o,isSymbolicLink:()=>s})}return t}function jm(i){return i.map(t=>typeof t=="string"?Je?yi(t):t:(t.name=Je?yi(t.name):t.name,t))}async function Hm(i){let t=await Uo(i),e=[];for(let n of t)await Tt.existsDirectory(q(i,n))&&e.push(n);return e}var Tt;(n=>{async function i(r){let o;try{if(o=await M.promises.lstat(r),!o.isSymbolicLink())return{stat:o}}catch{}try{return{stat:await M.promises.stat(r),symbolicLink:o?.isSymbolicLink()?{dangling:!1}:void 0}}catch(s){if(s.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};if(B&&s.code==="EACCES")try{return{stat:await M.promises.stat(await M.promises.readlink(r)),symbolicLink:{dangling:!1}}}catch(a){if(a.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};throw a}throw s}}n.stat=i;async function t(r){try{let{stat:o,symbolicLink:s}=await n.stat(r);return o.isFile()&&s?.dangling!==!0}catch{}return!1}n.existsFile=t;async function e(r){try{let{stat:o,symbolicLink:s}=await n.stat(r);return o.isDirectory()&&s?.dangling!==!0}catch{}return!1}n.existsDirectory=e})(Tt||={});var Gm=new tr;function Jm(i,t,e){return Gm.queueFor(b.file(i),()=>{let n=Xm(e);return new Promise((r,o)=>Ym(i,t,n,s=>s?o(s):r()))},It)}var Cu=!0;function Qm(i){Cu=i}function Ym(i,t,e,n){if(!Cu)return M.writeFile(i,t,{mode:e.mode,flag:e.flag},n);M.open(i,e.flag,e.mode,(r,o)=>{if(r)return n(r);M.writeFile(o,t,s=>{if(s)return M.close(o,()=>n(s));M.fdatasync(o,a=>(a&&(console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ",a),Qm(!1)),M.close(o,l=>n(l))))})})}function Xm(i){return i?{mode:typeof i.mode=="number"?i.mode:438,flag:typeof i.flag=="string"?i.flag:"w"}:{mode:438,flag:"w"}}async function Zm(i,t,e=6e4){if(i!==t)try{B&&typeof e=="number"?await Ru(i,t,Date.now(),e):await M.promises.rename(i,t)}catch(n){if(i.toLowerCase()!==t.toLowerCase()&&n.code==="EXDEV"||i.endsWith("."))await wu(i,t,{preserveSymlinks:!1}),await Eu(i,1);else throw n}}async function Ru(i,t,e,n,r=0){try{return await M.promises.rename(i,t)}catch(o){if(o.code!=="EACCES"&&o.code!=="EPERM"&&o.code!=="EBUSY")throw o;if(Date.now()-e>=n)throw console.error(`[node.js fs] rename failed after ${r} retries with error: ${o}`),o;if(r===0){let s=!1;try{let{stat:a}=await Tt.stat(t);a.isFile()||(s=!0)}catch{}if(s)throw o}return await Ut(Math.min(100,r*10)),Ru(i,t,e,n,r+1)}}async function wu(i,t,e){return Pu(i,t,{root:{source:i,target:t},options:e,handledSourcePaths:new Set})}var _u=511;async function Pu(i,t,e){if(e.handledSourcePaths.has(i))return;e.handledSourcePaths.add(i);let{stat:n,symbolicLink:r}=await Tt.stat(i);if(r){if(e.options.preserveSymlinks)try{return await nh(i,t,e)}catch{}if(r.dangling)return}return n.isDirectory()?eh(i,t,n.mode&_u,e):th(i,t,n.mode&_u)}async function eh(i,t,e,n){await M.promises.mkdir(t,{recursive:!0,mode:e});let r=await Uo(i);for(let o of r)await Pu(q(i,o),q(t,o),n)}async function th(i,t,e){await M.promises.copyFile(i,t),await M.promises.chmod(t,e)}async function nh(i,t,e){let n=await M.promises.readlink(i);Ot(n,e.root.source,!ve)&&(n=q(e.root.target,n.substr(e.root.source.length+1))),await M.promises.symlink(n,t)}async function rh(i){try{return await Ii(M.realpath)(i)}catch{let t=ih(i);return await M.promises.access(t,M.constants.R_OK),t}}function ih(i){return Zn(ot(i),Se)}var he=new class{get read(){return(i,t,e,n,r)=>new Promise((o,s)=>{M.read(i,t,e,n,r,(a,l,c)=>a?s(a):o({bytesRead:l,buffer:c}))})}get write(){return(i,t,e,n,r)=>new Promise((o,s)=>{M.write(i,t,e,n,r,(a,l,c)=>a?s(a):o({bytesWritten:l,buffer:c}))})}get fdatasync(){return Ii(M.fdatasync)}get open(){return Ii(M.open)}get close(){return Ii(M.close)}get ftruncate(){return Ii(M.ftruncate)}async exists(i){try{return await M.promises.access(i),!0}catch{return!1}}get readdir(){return Uo}get readDirsInDir(){return Hm}get writeFile(){return Jm}get rm(){return Eu}get rename(){return Zm}get copy(){return wu}get realpath(){return rh}};function Au(i){let t=[],e=!1,n=function(r){if(e){t.push(r);return}(!i.send(r,s=>{if(s&&console.error(s),e=!1,t.length>0){let a=t.slice(0);t=[],a.forEach(l=>n(l))}})||B)&&(e=!0)};return{send:n}}var No=class extends bi{constructor(t){super({send:e=>{try{process.send?.(e.buffer.toString("base64"))}catch{}},onMessage:Q.fromNodeEventEmitter(process,"message",e=>_.wrap(Buffer.from(e,"base64")))},t),process.once("disconnect",()=>this.dispose())}},Mo=class{constructor(t,e){this.modulePath=t;this.options=e;this.activeRequests=new Set;this.channels=new Map;this._onDidProcessExit=new x;this.onDidProcessExit=this._onDidProcessExit.event;let n=e.timeout||6e4;this.disposeDelayer=new di(n),this.child=null,this._client=null}getChannel(t){let e=this;return{call(n,r,o){return e.requestPromise(t,n,r,o)},listen(n,r){return e.requestEvent(t,n,r)}}}requestPromise(t,e,n,r=Ze.None){if(!this.disposeDelayer)return Promise.reject(new Error("disposed"));if(r.isCancellationRequested)return Promise.reject(eo());this.disposeDelayer.cancel();let o=this.getCachedChannel(t),s=ir(c=>o.call(e,n,c)),a=r.onCancellationRequested(()=>s.cancel()),l=w(()=>s.cancel());return this.activeRequests.add(l),s.finally(()=>{a.dispose(),this.activeRequests.delete(l),this.activeRequests.size===0&&this.disposeDelayer&&this.disposeDelayer.trigger(()=>this.disposeClient())}),s}requestEvent(t,e,n){if(!this.disposeDelayer)return Q.None;this.disposeDelayer.cancel();let r,o=new x({onWillAddFirstListener:()=>{r=this.getCachedChannel(t).listen(e,n)(o.fire,o),this.activeRequests.add(r)},onDidRemoveLastListener:()=>{this.activeRequests.delete(r),r.dispose(),this.activeRequests.size===0&&this.disposeDelayer&&this.disposeDelayer.trigger(()=>this.disposeClient())}});return o.event}get client(){if(!this._client){let t=this.options.args||[],e=Object.create(null);e.env={...pl(process.env),VSCODE_PARENT_PID:String(process.pid)},this.options.env&&(e.env={...e.env,...this.options.env}),this.options.freshExecArgv&&(e.execArgv=[]),typeof this.options.debug=="number"&&(e.execArgv=["--nolazy","--inspect="+this.options.debug]),typeof this.options.debugBrk=="number"&&(e.execArgv=["--nolazy","--inspect-brk="+this.options.debugBrk]),e.execArgv===void 0&&(e.execArgv=process.execArgv.filter(u=>!/^--inspect(-brk)?=/.test(u)).filter(u=>!u.startsWith("--vscode-"))),Su(e.env),this.child=ah(this.modulePath,t,e);let n=new x,o=Q.fromNodeEventEmitter(this.child,"message",u=>u)(u=>{if(yu(u)){Iu(u,`IPC Library: ${this.options.serverName}`);return}n.fire(_.wrap(Buffer.from(u,"base64")))}),s=this.options.useQueue?Au(this.child):this.child,a=u=>this.child?.connected&&s.send(u.buffer.toString("base64")),l=n.event,c={send:a,onMessage:l};this._client=new lr(c);let p=()=>this.disposeClient();process.once("exit",p),this.child.on("error",u=>console.warn('IPC "'+this.options.serverName+'" errored with '+u)),this.child.on("exit",(u,f)=>{process.removeListener("exit",p),o.dispose(),this.activeRequests.forEach(m=>Ke(m)),this.activeRequests.clear(),u!==0&&f!=="SIGTERM"&&console.warn('IPC "'+this.options.serverName+'" crashed with exit code '+u+" and signal "+f),this.disposeDelayer?.cancel(),this.disposeClient(),this._onDidProcessExit.fire({code:u,signal:f})})}return this._client}getCachedChannel(t){let e=this.channels.get(t);return e||(e=this.client.getChannel(t),this.channels.set(t,e)),e}disposeClient(){this._client&&(this.child&&(this.child.kill(),this.child=null),this._client=null,this.channels.clear())}dispose(){this._onDidProcessExit.dispose(),this.disposeDelayer?.cancel(),this.disposeDelayer=void 0,this.disposeClient(),this.activeRequests.clear()}};function Wo(i){return!!i.parentPort}var ml=class{constructor(t){this.port=t;this.onMessage=Q.fromNodeEventEmitter(this.port,"message",e=>e.data?_.wrap(e.data):_.alloc(0)),t.start()}send(t){this.port.postMessage(t.buffer)}disconnect(){this.port.close()}},Bo=class i extends Fo{static getOnDidClientConnect(t){sd(Wo(process),"Electron Utility Process");let e=new x;return process.parentPort.on("message",n=>{if(t?.handledClientConnection(n))return;let r=n.ports.at(0);r&&e.fire(r)}),Q.map(e.event,n=>({protocol:new ml(n),onDidClientDisconnect:Q.fromNodeEventEmitter(n,"close")}))}constructor(t){super(i.getOnDidClientConnect(t))}};var ne=(function(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let i=new Uint8Array(16),t=[];for(let e=0;e<256;e++)t.push(e.toString(16).padStart(2,"0"));return function(){crypto.getRandomValues(i),i[6]=i[6]&15|64,i[8]=i[8]&63|128;let n=0,r="";return r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r}})();import*as Xi from"os";var ft;(r=>{r.serviceIds=new Map,r.DI_TARGET="$di$target",r.DI_DEPENDENCIES="$di$dependencies";function n(o){return o[r.DI_DEPENDENCIES]||[]}r.getServiceDependencies=n})(ft||={});var pr=re("instantiationService");function lh(i,t,e){t[ft.DI_TARGET]===t?t[ft.DI_DEPENDENCIES].push({id:i,index:e}):(t[ft.DI_DEPENDENCIES]=[{id:i,index:e}],t[ft.DI_TARGET]=t)}function re(i){if(ft.serviceIds.has(i))return ft.serviceIds.get(i);let t=function(e,n,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");lh(t,e,r)};return t.toString=()=>i,ft.serviceIds.set(i,t),t}var ku="branchNameHint",ce;(n=>{function i(r,o){return b.from({scheme:r,path:`/${o}`})}n.uri=i;function t(r){return(typeof r=="string"?b.parse(r):r).path.substring(1)}n.id=t;function e(r){return(typeof r=="string"?b.parse(r):r).scheme||void 0}n.provider=e})(ce||={});var yS=re("agentService"),IS=re("agentHostService");function hl(i,t){return t&&(i.stack||i.stacktrace)?g(116,null,Ou(i),Du(i.stack)||Du(i.stacktrace)):Ou(i)}function Du(i){return Array.isArray(i)?i.join(`
`):i}function Ou(i){return i.code==="ERR_UNC_HOST_NOT_ALLOWED"?`${i.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`:typeof i.code=="string"&&typeof i.errno=="number"&&typeof i.syscall=="string"?g(115,null,i.message):i.message||g(113,null)}function kn(i=null,t=!1){if(!i)return g(113,null);if(Array.isArray(i)){let e=no(i),n=kn(e[0],t);return e.length>1?g(114,null,n,e.length):n}if(Me(i))return i;if(i.detail){let e=i.detail;if(e.error)return hl(e.error,t);if(e.exception)return hl(e.exception,t)}return i.stack?hl(i,t):i.message?i.message:g(113,null)}var ze=class{constructor(t,e,n){this.owner=t;this.debugNameSource=e;this.referenceFn=n}getDebugName(t){return Nu(t,this)}},Lu=new Map,vl=new WeakMap;function Nu(i,t){let e=vl.get(i);if(e)return e;let n=ch(i,t);if(n){let r=Lu.get(n)??0;r++,Lu.set(n,r);let o=r===1?n:`${n}#${r}`;return vl.set(i,o),o}}function ch(i,t){let e=vl.get(i);if(e)return e;let n=t.owner?uh(t.owner)+".":"",r,o=t.debugNameSource;if(o!==void 0)if(typeof o=="function"){if(r=o(),r!==void 0)return n+r}else return n+o;let s=t.referenceFn;if(s!==void 0&&(r=Si(s),r!==void 0))return n+r;if(t.owner!==void 0){let a=dh(t.owner,i);if(a!==void 0)return n+a}}function dh(i,t){for(let e in i)if(i[e]===t)return e}var Fu=new Map,Uu=new WeakMap;function uh(i){let t=Uu.get(i);if(t)return t;let e=bl(i)??"Object",n=Fu.get(e)??0;n++,Fu.set(e,n);let r=n===1?e:`${e}#${n}`;return Uu.set(i,r),r}function bl(i){let t=i.constructor;if(t)return t.name==="Object"?void 0:t.name}function Si(i){let t=i.toString(),n=/\/\*\*\s*@description\s*([^*]*)\*\//.exec(t);return(n?n[1]:void 0)?.trim()}function st(i,t){return i===t}function ph(){return(i,t)=>i===t}function fh(i,t,e){return Jr(i,t,e??st)}function gh(i){return(t,e)=>Jr(t,e,i??st)}function $o(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++)if(!$o(i[e],t[e]))return!1;return!0}if(i&&typeof i=="object"&&t&&typeof t=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let e=i,n=t,r=Object.keys(e),o=Object.keys(n),s=new Set(o);if(r.length!==o.length)return!1;for(let a of r)if(!s.has(a)||!$o(e[a],n[a]))return!1;return!0}return!1}function mh(){return(i,t)=>$o(i,t)}function hh(i,t){return JSON.stringify(i)===JSON.stringify(t)}function vh(){return(i,t)=>JSON.stringify(i)===JSON.stringify(t)}function bh(){return(i,t)=>i.equals(t)}function yh(i,t,e){return i==null||t===void 0||t===null?t===i:e(i,t)}function Ih(i){return(t,e)=>t==null||e===void 0||e===null?e===t:i(t,e)}var Sh;(u=>(u.strict=st,u.strictC=ph,u.array=fh,u.arrayC=gh,u.structural=$o,u.structuralC=mh,u.jsonStringify=hh,u.jsonStringifyC=vh,u.thisC=bh,u.ifDefined=yh,u.ifDefinedC=Ih))(Sh||={});function yl(i){let t=new Error("BugIndicatingErrorRecovery: "+i);fe(t),console.error("recovered from an error that indicates a bug",t)}var Dn;function Ti(i){Dn?Dn instanceof Vo?Dn.loggers.push(i):Dn=new Vo([Dn,i]):Dn=i}function de(){return Dn}var Il;function Mu(i){Il=i}function Wu(i){Il&&Il(i)}var Vo=class{constructor(t){this.loggers=t}handleObservableCreated(t,e){for(let n of this.loggers)n.handleObservableCreated(t,e)}handleOnListenerCountChanged(t,e){for(let n of this.loggers)n.handleOnListenerCountChanged(t,e)}handleObservableUpdated(t,e){for(let n of this.loggers)n.handleObservableUpdated(t,e)}handleAutorunCreated(t,e){for(let n of this.loggers)n.handleAutorunCreated(t,e)}handleAutorunDisposed(t){for(let e of this.loggers)e.handleAutorunDisposed(t)}handleAutorunDependencyChanged(t,e,n){for(let r of this.loggers)r.handleAutorunDependencyChanged(t,e,n)}handleAutorunStarted(t){for(let e of this.loggers)e.handleAutorunStarted(t)}handleAutorunFinished(t){for(let e of this.loggers)e.handleAutorunFinished(t)}handleDerivedDependencyChanged(t,e,n){for(let r of this.loggers)r.handleDerivedDependencyChanged(t,e,n)}handleDerivedCleared(t){for(let e of this.loggers)e.handleDerivedCleared(t)}handleBeginTransaction(t){for(let e of this.loggers)e.handleBeginTransaction(t)}handleEndTransaction(t){for(let e of this.loggers)e.handleEndTransaction(t)}};function fr(i,t){let e=new On(i,t);try{i(e)}finally{e.finish()}}function Sl(i,t,e){i?t(i):fr(t,e)}var On=class{constructor(t,e){this._fn=t;this._getDebugName=e;this._updatingObservers=[];de()?.handleBeginTransaction(this)}getDebugName(){return this._getDebugName?this._getDebugName():Si(this._fn)}updateObserver(t,e){if(!this._updatingObservers){yl("Transaction already finished!"),fr(n=>{n.updateObserver(t,e)});return}this._updatingObservers.push({observer:t,observable:e}),t.beginUpdate(e)}finish(){let t=this._updatingObservers;if(!t){yl("transaction.finish() has already been called!");return}for(let e=0;e<t.length;e++){let{observer:n,observable:r}=t[e];n.endUpdate(r)}this._updatingObservers=null,de()?.handleEndTransaction(this)}debugGetUpdatingObservers(){return this._updatingObservers}};var xe;(n=>{let i=!1;function t(){i=!0}n.enable=t;function e(){if(!i)return;let r=Error,o=r.stackTraceLimit;r.stackTraceLimit=3;let s=new Error().stack;return r.stackTraceLimit=o,Tl.fromStack(s,2)}n.ofCaller=e})(xe||={});var Tl=class i{constructor(t,e,n,r){this.fileName=t;this.line=e;this.column=n;this.id=r}static fromStack(t,e){let n=t.split(`
`),r=Th(n[e+1]);if(r)return new i(r.fileName,r.line,r.column,r.id)}};function Th(i){let t=i.match(/\((.*):(\d+):(\d+)\)/);if(t)return{fileName:t[1],line:parseInt(t[2]),column:parseInt(t[3]),id:i};let e=i.match(/at ([^\(\)]*):(\d+):(\d+)/);if(e)return{fileName:e[1],line:parseInt(e[2]),column:parseInt(e[3]),id:i}}var xl;function Bu(i){xl=i}var $u;function Vu(i){$u=i}var qu;function Ku(i){qu=i}var _l;function zu(i){_l=i}var qo=class{get TChange(){return null}reportChanges(){this.get()}read(t){return t?t.readObservable(this):this.get()}map(t,e,n=xe.ofCaller()){let r=e===void 0?void 0:t,o=e===void 0?t:e;return xl({owner:r,debugName:()=>{let s=Si(o);if(s!==void 0)return s;let l=/^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/.exec(o.toString());if(l)return`${this.debugName}.${l[2]}`;if(!r)return`${this.debugName} (mapped)`},debugReferenceFn:o},s=>o(this.read(s),s),n)}flatten(){return xl({owner:void 0,debugName:()=>`${this.debugName} (flattened)`},t=>this.read(t).read(t))}recomputeInitiallyAndOnChange(t,e){return t.add($u(this,e)),this}keepObserved(t){return t.add(qu(this)),this}get debugValue(){return this.get()}get debug(){return new El(this)}},El=class{constructor(t){this.observable=t}getDependencyGraph(){return _l(this.observable,{type:"dependencies"})}getObserverGraph(){return _l(this.observable,{type:"observers"})}},gt=class extends qo{constructor(e){super();this._observers=new Set;de()?.handleObservableCreated(this,e)}addObserver(e){let n=this._observers.size;this._observers.add(e),n===0&&this.onFirstObserverAdded(),n!==this._observers.size&&de()?.handleOnListenerCountChanged(this,this._observers.size)}removeObserver(e){let n=this._observers.delete(e);n&&this._observers.size===0&&this.onLastObserverRemoved(),n&&de()?.handleOnListenerCountChanged(this,this._observers.size)}onFirstObserverAdded(){}onLastObserverRemoved(){}log(){let e=!!de();return Wu(this),e||de()?.handleObservableCreated(this,xe.ofCaller()),this}debugGetObservers(){return this._observers}};function Ln(i,t,e=xe.ofCaller()){let n;return typeof i=="string"?n=new ze(void 0,i,void 0):n=new ze(i,void 0,void 0),new Mt(n,t,st,e)}var Mt=class extends gt{constructor(e,n,r,o){super(o);this._debugNameData=e;this._equalityComparator=r;this._value=n,de()?.handleObservableUpdated(this,{hadValue:!1,newValue:n,change:void 0,didChange:!0,oldValue:void 0})}get debugName(){return this._debugNameData.getDebugName(this)??"ObservableValue"}get(){return this._value}set(e,n,r){if(r===void 0&&this._equalityComparator(this._value,e))return;let o;n||(n=o=new On(()=>{},()=>`Setting ${this.debugName}`));try{let s=this._value;this._setValue(e),de()?.handleObservableUpdated(this,{oldValue:s,newValue:e,change:r,didChange:!0,hadValue:!0});for(let a of this._observers)n.updateObserver(a,this),a.handleChange(this,r)}finally{o&&o.finish()}}toString(){return`${this.debugName}: ${this._value}`}_setValue(e){this._value=e}debugGetState(){return{value:this._value}}debugSetValue(e){this._value=e}};function xh(i){switch(i){case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var Wt=class{constructor(t,e,n,r){this._debugNameData=t;this._runFn=e;this._changeTracker=n;this._state=2;this._updateCount=0;this._disposed=!1;this._dependencies=new Set;this._dependenciesToBeRemoved=new Set;this._isRunning=!1;this._iteration=0;this._store=void 0;this._delayedStore=void 0;this._changeSummary=this._changeTracker?.createChangeSummary(void 0),de()?.handleAutorunCreated(this,r),this._run(),Yt(this)}get debugName(){return this._debugNameData.getDebugName(this)??"(anonymous)"}dispose(){if(!this._disposed){this._disposed=!0;for(let t of this._dependencies)t.removeObserver(this);this._dependencies.clear(),this._store!==void 0&&this._store.dispose(),this._delayedStore!==void 0&&this._delayedStore.dispose(),de()?.handleAutorunDisposed(this),Xt(this)}}_run(){let t=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=t,this._state=3;try{if(!this._disposed){de()?.handleAutorunStarted(this);let e=this._changeSummary,n=this._delayedStore;n!==void 0&&(this._delayedStore=void 0);try{this._isRunning=!0,this._changeTracker&&(this._changeTracker.beforeUpdate?.(this,e),this._changeSummary=this._changeTracker.createChangeSummary(e)),this._store!==void 0&&(this._store.dispose(),this._store=void 0),this._runFn(this,e)}catch(r){Jt(r)}finally{this._isRunning=!1,n!==void 0&&n.dispose()}}}finally{this._disposed||de()?.handleAutorunFinished(this);for(let e of this._dependenciesToBeRemoved)e.removeObserver(this);this._dependenciesToBeRemoved.clear()}}toString(){return`Autorun<${this.debugName}>`}beginUpdate(t){this._state===3&&(this._checkIterations(),this._state=1),this._updateCount++}endUpdate(t){try{if(this._updateCount===1){this._iteration=1;do{if(this._checkIterations())return;if(this._state===1){this._state=3;for(let e of this._dependencies)if(e.reportChanges(),this._state===2)break}this._iteration++,this._state!==3&&this._run()}while(this._state!==3)}}finally{this._updateCount--}Qr(()=>this._updateCount>=0)}handlePossibleChange(t){this._state===3&&this._isDependency(t)&&(this._checkIterations(),this._state=1)}handleChange(t,e){if(this._isDependency(t)){de()?.handleAutorunDependencyChanged(this,t,e);try{(!this._changeTracker||this._changeTracker.handleChange({changedObservable:t,change:e,didChange:r=>r===t},this._changeSummary))&&(this._checkIterations(),this._state=2)}catch(n){Jt(n)}}}_isDependency(t){return this._dependencies.has(t)&&!this._dependenciesToBeRemoved.has(t)}_ensureNoRunning(){if(!this._isRunning)throw new ae("The reader object cannot be used outside its compute function!")}readObservable(t){if(this._ensureNoRunning(),this._disposed)return t.get();t.addObserver(this);let e=t.get();return this._dependencies.add(t),this._dependenciesToBeRemoved.delete(t),e}get store(){if(this._ensureNoRunning(),this._disposed)throw new ae("Cannot access store after dispose");return this._store===void 0&&(this._store=new N),this._store}get delayedStore(){if(this._ensureNoRunning(),this._disposed)throw new ae("Cannot access store after dispose");return this._delayedStore===void 0&&(this._delayedStore=new N),this._delayedStore}debugGetState(){return{isRunning:this._isRunning,updateCount:this._updateCount,dependencies:this._dependencies,state:this._state,stateStr:xh(this._state)}}debugRerun(){this._isRunning?this._state=2:this._run()}_checkIterations(){return this._iteration>100?(Jt(new ae(`Autorun '${this.debugName}' is stuck in an infinite update loop.`)),!0):!1}};function xi(i,t=xe.ofCaller()){return new Wt(new ze(void 0,void 0,i),i,void 0,t)}function _h(i){switch(i){case 0:return"initial";case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var De=class extends gt{constructor(e,n,r,o=void 0,s,a){super(a);this._debugNameData=e;this._computeFn=n;this._changeTracker=r;this._handleLastObserverRemoved=o;this._equalityComparator=s;this._state=0;this._value=void 0;this._updateCount=0;this._dependencies=new Set;this._dependenciesToBeRemoved=new Set;this._changeSummary=void 0;this._isUpdating=!1;this._isComputing=!1;this._didReportChange=!1;this._isInBeforeUpdate=!1;this._isReaderValid=!1;this._store=void 0;this._delayedStore=void 0;this._removedObserverToCallEndUpdateOn=null;this._changeSummary=this._changeTracker?.createChangeSummary(void 0)}get debugName(){return this._debugNameData.getDebugName(this)??"(anonymous)"}onLastObserverRemoved(){this._state=0,this._value=void 0,de()?.handleDerivedCleared(this);for(let e of this._dependencies)e.removeObserver(this);this._dependencies.clear(),this._store!==void 0&&(this._store.dispose(),this._store=void 0),this._delayedStore!==void 0&&(this._delayedStore.dispose(),this._delayedStore=void 0),this._handleLastObserverRemoved?.()}get(){if(this._isComputing,this._observers.size===0){let n;try{this._isReaderValid=!0;let r;this._changeTracker&&(r=this._changeTracker.createChangeSummary(void 0),this._changeTracker.beforeUpdate?.(this,r)),n=this._computeFn(this,r)}finally{this._isReaderValid=!1}return this.onLastObserverRemoved(),n}else{do{if(this._state===1){for(let n of this._dependencies)if(n.reportChanges(),this._state===2)break}this._state===1&&(this._state=3),this._state!==3&&this._recompute()}while(this._state!==3);return this._value}}_recompute(){let e=!1;this._isComputing=!0,this._didReportChange=!1;let n=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=n;try{let r=this._changeSummary;this._isReaderValid=!0,this._changeTracker&&(this._isInBeforeUpdate=!0,this._changeTracker.beforeUpdate?.(this,r),this._isInBeforeUpdate=!1,this._changeSummary=this._changeTracker?.createChangeSummary(r));let o=this._state!==0,s=this._value;this._state=3;let a=this._delayedStore;a!==void 0&&(this._delayedStore=void 0);try{this._store!==void 0&&(this._store.dispose(),this._store=void 0),this._value=this._computeFn(this,r)}finally{this._isReaderValid=!1;for(let l of this._dependenciesToBeRemoved)l.removeObserver(this);this._dependenciesToBeRemoved.clear(),a!==void 0&&a.dispose()}e=this._didReportChange||o&&!this._equalityComparator(s,this._value),de()?.handleObservableUpdated(this,{oldValue:s,newValue:this._value,change:void 0,didChange:e,hadValue:o})}catch(r){Jt(r)}if(this._isComputing=!1,!this._didReportChange&&e)for(let r of this._observers)r.handleChange(this,void 0);else this._didReportChange=!1}toString(){return`LazyDerived<${this.debugName}>`}beginUpdate(e){if(this._isUpdating)throw new ae("Cyclic deriveds are not supported yet!");this._updateCount++,this._isUpdating=!0;try{let n=this._updateCount===1;if(this._state===3&&(this._state=1,!n))for(let r of this._observers)r.handlePossibleChange(this);if(n)for(let r of this._observers)r.beginUpdate(this)}finally{this._isUpdating=!1}}endUpdate(e){if(this._updateCount--,this._updateCount===0){let n=[...this._observers];for(let r of n)r.endUpdate(this);if(this._removedObserverToCallEndUpdateOn){let r=[...this._removedObserverToCallEndUpdateOn];this._removedObserverToCallEndUpdateOn=null;for(let o of r)o.endUpdate(this)}}Qr(()=>this._updateCount>=0)}handlePossibleChange(e){if(this._state===3&&this._dependencies.has(e)&&!this._dependenciesToBeRemoved.has(e)){this._state=1;for(let n of this._observers)n.handlePossibleChange(this)}}handleChange(e,n){if(this._dependencies.has(e)&&!this._dependenciesToBeRemoved.has(e)||this._isInBeforeUpdate){de()?.handleDerivedDependencyChanged(this,e,n);let r=!1;try{r=this._changeTracker?this._changeTracker.handleChange({changedObservable:e,change:n,didChange:s=>s===e},this._changeSummary):!0}catch(s){Jt(s)}let o=this._state===3;if(r&&(this._state===1||o)&&(this._state=2,o))for(let s of this._observers)s.handlePossibleChange(this)}}_ensureReaderValid(){if(!this._isReaderValid)throw new ae("The reader object cannot be used outside its compute function!")}readObservable(e){this._ensureReaderValid(),e.addObserver(this);let n=e.get();return this._dependencies.add(e),this._dependenciesToBeRemoved.delete(e),n}reportChange(e){this._ensureReaderValid(),this._didReportChange=!0;for(let n of this._observers)n.handleChange(this,e)}get store(){return this._ensureReaderValid(),this._store===void 0&&(this._store=new N),this._store}get delayedStore(){return this._ensureReaderValid(),this._delayedStore===void 0&&(this._delayedStore=new N),this._delayedStore}addObserver(e){let n=!this._observers.has(e)&&this._updateCount>0;super.addObserver(e),n&&(this._removedObserverToCallEndUpdateOn?.delete(e)||e.beginUpdate(this))}removeObserver(e){this._observers.has(e)&&this._updateCount>0&&(this._removedObserverToCallEndUpdateOn||(this._removedObserverToCallEndUpdateOn=new Set),this._removedObserverToCallEndUpdateOn.add(e)),super.removeObserver(e)}debugGetState(){return{state:this._state,stateStr:_h(this._state),updateCount:this._updateCount,isComputing:this._isComputing,dependencies:this._dependencies,value:this._value}}debugSetValue(e){this._value=e}debugRecompute(){this.beginUpdate(this);try{this._isComputing?this._state=2:this._recompute()}finally{this.endUpdate(this)}}setValue(e,n,r){this._value=e;let o=this._observers;n.updateObserver(this,this);for(let s of o)s.handleChange(this,r)}};function Cl(i,t,e=xe.ofCaller()){return new De(new ze(i.owner,i.debugName,i.debugReferenceFn),t,void 0,i.onLastObserverRemoved,i.equalsFn??st,e)}Bu(Cl);function gr(...i){let t,e,n,r;return i.length===2?[e,n]=i:[t,e,n,r]=i,new at(new ze(t,void 0,n),e,n,()=>at.globalTransaction,st,r??xe.ofCaller())}var at=class extends gt{constructor(e,n,r,o,s,a){super(a);this._debugNameData=e;this.event=n;this._getValue=r;this._getTransaction=o;this._equalityComparator=s;this._hasValue=!1;this.handleEvent=e=>{let n=this._getValue(e),r=this._value,o=!this._hasValue||!this._equalityComparator(r,n),s=!1;o&&(this._value=n,this._hasValue&&(s=!0,Sl(this._getTransaction(),a=>{de()?.handleObservableUpdated(this,{oldValue:r,newValue:n,change:void 0,didChange:o,hadValue:this._hasValue});for(let l of this._observers)a.updateObserver(l,this),l.handleChange(this,void 0)},()=>{let a=this.getDebugName();return"Event fired"+(a?`: ${a}`:"")})),this._hasValue=!0),s||de()?.handleObservableUpdated(this,{oldValue:r,newValue:n,change:void 0,didChange:o,hadValue:this._hasValue})}}getDebugName(){return this._debugNameData.getDebugName(this)}get debugName(){let e=this.getDebugName();return"From Event"+(e?`: ${e}`:"")}onFirstObserverAdded(){this._subscription=this.event(this.handleEvent)}onLastObserverRemoved(){this._subscription.dispose(),this._subscription=void 0,this._hasValue=!1,this._value=void 0}get(){return this._subscription?(this._hasValue||this.handleEvent(void 0),this._value):this._getValue(void 0)}debugSetValue(e){this._value=e}debugGetState(){return{value:this._value,hasValue:this._hasValue}}};(e=>{e.Observer=at;function t(n,r){let o=!1;at.globalTransaction===void 0&&(at.globalTransaction=n,o=!0);try{r()}finally{o&&(at.globalTransaction=void 0)}}e.batchEventsGlobally=t})(gr||={});function Hu(i){let t=new Ko(!1,void 0);return i.addObserver(t),w(()=>{i.removeObserver(t)})}Ku(Hu);function Gu(i,t){let e=new Ko(!0,t);i.addObserver(e);try{e.beginUpdate(i)}finally{e.endUpdate(i)}return w(()=>{i.removeObserver(e)})}Vu(Gu);var Ko=class{constructor(t,e){this._forceRecompute=t;this._handleValue=e;this._counter=0}beginUpdate(t){this._counter++}endUpdate(t){this._counter===1&&this._forceRecompute&&(this._handleValue?this._handleValue(t.get()):t.reportChanges()),this._counter--}handlePossibleChange(t){}handleChange(t,e){}};var zo;function Qu(i){zo||(zo=new _i,Ti(zo)),zo.addFilteredObj(i)}var _i=class{constructor(){this.indentation=0;this.changedObservablesSets=new WeakMap}addFilteredObj(t){this._filteredObjects||(this._filteredObjects=new Set),this._filteredObjects.add(t)}_isIncluded(t){return this._filteredObjects?.has(t)??!0}textToConsoleArgs(t){return Ah([mr(Oh("|  ",this.indentation)),t])}formatInfo(t){return t.hadValue?t.didChange?[mr(" "),lt(et(t.oldValue,70),{color:"red",strikeThrough:!0}),mr(" "),lt(et(t.newValue,60),{color:"green"})]:[mr(" (unchanged)")]:[mr(" "),lt(et(t.newValue,60),{color:"green"}),mr(" (initial)")]}handleObservableCreated(t){if(t instanceof De){let e=t;if(this.changedObservablesSets.set(e,new Set),!1){let r=[];e.__debugUpdating=r;let o=e.beginUpdate;e.beginUpdate=a=>(r.push(a),o.apply(e,[a]));let s=e.endUpdate;e.endUpdate=a=>{let l=r.indexOf(a);return l===-1&&console.error("endUpdate called without beginUpdate",e.debugName,a.debugName),r.splice(l,1),s.apply(e,[a])}}}}handleOnListenerCountChanged(t,e){}handleObservableUpdated(t,e){if(this._isIncluded(t)){if(t instanceof De){this._handleDerivedRecomputed(t,e);return}console.log(...this.textToConsoleArgs([hr("observable value changed"),lt(t.debugName,{color:"BlueViolet"}),...this.formatInfo(e)]))}}formatChanges(t){if(t.size!==0)return lt(" (changed deps: "+[...t].map(e=>e.debugName).join(", ")+")",{color:"gray"})}handleDerivedDependencyChanged(t,e,n){this._isIncluded(t)&&this.changedObservablesSets.get(t)?.add(e)}_handleDerivedRecomputed(t,e){if(!this._isIncluded(t))return;let n=this.changedObservablesSets.get(t);n&&(console.log(...this.textToConsoleArgs([hr("derived recomputed"),lt(t.debugName,{color:"BlueViolet"}),...this.formatInfo(e),this.formatChanges(n),{data:[{fn:t._debugNameData.referenceFn??t._computeFn}]}])),n.clear())}handleDerivedCleared(t){this._isIncluded(t)&&console.log(...this.textToConsoleArgs([hr("derived cleared"),lt(t.debugName,{color:"BlueViolet"})]))}handleFromEventObservableTriggered(t,e){this._isIncluded(t)&&console.log(...this.textToConsoleArgs([hr("observable from event triggered"),lt(t.debugName,{color:"BlueViolet"}),...this.formatInfo(e),{data:[{fn:t._getValue}]}]))}handleAutorunCreated(t){this._isIncluded(t)&&this.changedObservablesSets.set(t,new Set)}handleAutorunDisposed(t){}handleAutorunDependencyChanged(t,e,n){this._isIncluded(t)&&this.changedObservablesSets.get(t).add(e)}handleAutorunStarted(t){let e=this.changedObservablesSets.get(t);e&&(this._isIncluded(t)&&console.log(...this.textToConsoleArgs([hr("autorun"),lt(t.debugName,{color:"BlueViolet"}),this.formatChanges(e),{data:[{fn:t._debugNameData.referenceFn??t._runFn}]}])),e.clear(),this.indentation++)}handleAutorunFinished(t){this.indentation--}handleBeginTransaction(t){let e=t.getDebugName();e===void 0&&(e=""),this._isIncluded(t)&&console.log(...this.textToConsoleArgs([hr("transaction"),lt(e,{color:"BlueViolet"}),{data:[{fn:t._fn}]}])),this.indentation++}handleEndTransaction(){this.indentation--}};function Ah(i){let t=new Array,e=[],n="";function r(s){if("length"in s)for(let a of s)a&&r(a);else"text"in s?(n+=`%c${s.text}`,t.push(s.style),s.data&&e.push(...s.data)):"data"in s&&e.push(...s.data)}r(i);let o=[n,...t];return o.push(...e),o}function mr(i){return lt(i,{color:"black"})}function hr(i){return lt(Lh(`${i}: `,10),{color:"black",bold:!0})}function lt(i,t={color:"black"}){function e(r){return Object.entries(r).reduce((o,[s,a])=>`${o}${s}:${a};`,"")}let n={color:t.color};return t.strikeThrough&&(n["text-decoration"]="line-through"),t.bold&&(n["font-weight"]="bold"),{text:i,style:e(n)}}function et(i,t){switch(typeof i){case"number":return""+i;case"string":return i.length+2<=t?`"${i}"`:`"${i.substr(0,t-7)}"+...`;case"boolean":return i?"true":"false";case"undefined":return"undefined";case"object":return i===null?"null":Array.isArray(i)?kh(i,t):Dh(i,t);case"symbol":return i.toString();case"function":return`[[Function${i.name?" "+i.name:""}]]`;default:return""+i}}function kh(i,t){let e="[ ",n=!0;for(let r of i){if(n||(e+=", "),e.length-5>t){e+="...";break}n=!1,e+=`${et(r,t-e.length)}`}return e+=" ]",e}function Dh(i,t){if(typeof i.toString=="function"&&i.toString!==Object.prototype.toString){let o=i.toString();return o.length<=t?o:o.substring(0,t-3)+"..."}let e=bl(i),n=e?e+"(":"{ ",r=!0;for(let[o,s]of Object.entries(i)){if(r||(n+=", "),n.length-5>t){n+="...";break}r=!1,n+=`${o}: ${et(s,t-n.length)}`}return n+=e?")":" }",n}function Oh(i,t){let e="";for(let n=1;n<=t;n++)e+=i;return e}function Lh(i,t){for(;i.length<t;)i+=" ";return i}var jo=class i{constructor(t,e){this._channelFactory=t;this._getHandler=e;this._channel=this._channelFactory({handleNotification:o=>{let s=o,a=this._getHandler().notifications[s[0]];if(!a)throw new Error(`Unknown notification "${s[0]}"!`);a(...s[1])},handleRequest:o=>{let s=o;try{return{type:"result",value:this._getHandler().requests[s[0]](...s[1])}}catch(a){return{type:"error",value:a}}}});let n=new Proxy({},{get:(o,s)=>async(...a)=>{let l=await this._channel.sendRequest([s,a]);if(l.type==="error")throw l.value;return l.value}}),r=new Proxy({},{get:(o,s)=>(...a)=>{this._channel.sendNotification([s,a])}});this.api={notifications:r,requests:n}}static createHost(t,e){return new i(t,e)}static createClient(t,e){return new i(t,e)}};function Yu(i,t){let e=globalThis,n=[],r,{channel:o,handler:s}=Fh({sendNotification:l=>{r?r.sendNotification(l):n.push(l)}}),a;return(e.$$debugValueEditor_debugChannels??(e.$$debugValueEditor_debugChannels={}))[i]=l=>{a=t(),r=l;for(let c of n)l.sendNotification(c);return n=[],s},jo.createClient(o,()=>{if(!a)throw new Error("Not supported");return a})}function Fh(i){let t;return{channel:n=>(t=n,{sendNotification:r=>{i.sendNotification(r)},sendRequest:r=>{throw new Error("not supported")}}),handler:{handleRequest:n=>n.type==="notification"?t?.handleNotification(n.data):t?.handleRequest(n.data)}}}var Ho=class{constructor(){this._timeout=void 0}throttle(t,e){this._timeout===void 0&&(this._timeout=setTimeout(()=>{this._timeout=void 0,t()},e))}dispose(){this._timeout!==void 0&&clearTimeout(this._timeout)}};function Rl(i,t){for(let e in t)i[e]&&typeof i[e]=="object"&&t[e]&&typeof t[e]=="object"?Rl(i[e],t[e]):i[e]=t[e]}function wl(i,t){for(let e in t)t[e]===null?delete i[e]:i[e]&&typeof i[e]=="object"&&t[e]&&typeof t[e]=="object"?wl(i[e],t[e]):i[e]=t[e]}var Go=class i{constructor(){this._declarationId=0;this._instanceId=0;this._declarations=new Map;this._instanceInfos=new WeakMap;this._aliveInstances=new Map;this._activeTransactions=new Set;this._channel=Yu("observableDevTools",()=>({notifications:{setDeclarationIdFilter:t=>{},logObservableValue:t=>{console.log("logObservableValue",t)},flushUpdates:()=>{this._flushUpdates()},resetUpdates:()=>{this._pendingChanges=null,this._channel.api.notifications.handleChange(this._fullState,!0)}},requests:{getDeclarations:()=>{let t={};for(let e of this._declarations.values())t[e.id]=e;return{decls:t}},getSummarizedInstances:()=>null,getObservableValueInfo:t=>({observers:[...this._aliveInstances.get(t).debugGetObservers()].map(n=>this._formatObserver(n)).filter(jn)}),getDerivedInfo:t=>{let e=this._aliveInstances.get(t);return{dependencies:[...e.debugGetState().dependencies].map(n=>this._formatObservable(n)).filter(jn),observers:[...e.debugGetObservers()].map(n=>this._formatObserver(n)).filter(jn)}},getAutorunInfo:t=>({dependencies:[...this._aliveInstances.get(t).debugGetState().dependencies].map(n=>this._formatObservable(n)).filter(jn)}),getTransactionState:()=>this.getTransactionState(),setValue:(t,e)=>{let n=this._aliveInstances.get(t);if(n instanceof De)n.debugSetValue(e);else if(n instanceof Mt)n.debugSetValue(e);else if(n instanceof at)n.debugSetValue(e);else throw new ae("Observable is not supported");let r=[...n.debugGetObservers()];for(let o of r)o.beginUpdate(n);for(let o of r)o.handleChange(n,void 0);for(let o of r)o.endUpdate(n)},getValue:t=>{let e=this._aliveInstances.get(t);if(e instanceof De)return et(e.debugGetState().value,200);if(e instanceof Mt)return et(e.debugGetState().value,200)},logValue:t=>{let e=this._aliveInstances.get(t);if(e&&"get"in e)console.log("Logged Value:",e.get());else throw new ae("Observable is not supported")},rerun:t=>{let e=this._aliveInstances.get(t);if(e instanceof De)e.debugRecompute();else if(e instanceof Wt)e.debugRerun();else throw new ae("Observable is not supported")}}}));this._pendingChanges=null;this._changeThrottler=new Ho;this._fullState={};this._flushUpdates=()=>{this._pendingChanges!==null&&(this._channel.api.notifications.handleChange(this._pendingChanges,!1),this._pendingChanges=null)};xe.enable()}static{this._instance=void 0}static getInstance(){return i._instance===void 0&&(i._instance=new i),i._instance}getTransactionState(){let t=[],e=[...this._activeTransactions];if(e.length===0)return;let n=e.flatMap(o=>o.debugGetUpdatingObservers()??[]).map(o=>o.observer),r=new Set;for(;n.length>0;){let o=n.shift();if(r.has(o))continue;r.add(o);let s=this._getInfo(o,a=>{r.has(a)||n.push(a)});s&&t.push(s)}return{names:e.map(o=>o.getDebugName()??"tx"),affected:t}}_getObservableInfo(t){let e=this._instanceInfos.get(t);if(!e){fe(new ae("No info found"));return}return e}_getAutorunInfo(t){let e=this._instanceInfos.get(t);if(!e){fe(new ae("No info found"));return}return e}_getInfo(t,e){if(t instanceof De){let n=[...t.debugGetObservers()];for(let l of n)e(l);let r=this._getObservableInfo(t);if(!r)return;let o=t.debugGetState(),s={name:t.debugName,instanceId:r.instanceId,updateCount:o.updateCount},a=[...r.changedObservables].map(l=>this._instanceInfos.get(l)?.instanceId).filter(jn);if(o.isComputing)return{...s,type:"observable/derived",state:"updating",changedDependencies:a,initialComputation:!1};switch(o.state){case 0:return{...s,type:"observable/derived",state:"noValue"};case 3:return{...s,type:"observable/derived",state:"upToDate"};case 2:return{...s,type:"observable/derived",state:"stale",changedDependencies:a};case 1:return{...s,type:"observable/derived",state:"possiblyStale"}}}else if(t instanceof Wt){let n=this._getAutorunInfo(t);if(!n)return;let r={name:t.debugName,instanceId:n.instanceId,updateCount:n.updateCount},o=[...n.changedObservables].map(s=>this._instanceInfos.get(s).instanceId);if(t.debugGetState().isRunning)return{...r,type:"autorun",state:"updating",changedDependencies:o};switch(t.debugGetState().state){case 3:return{...r,type:"autorun",state:"upToDate"};case 2:return{...r,type:"autorun",state:"stale",changedDependencies:o};case 1:return{...r,type:"autorun",state:"possiblyStale"}}}}_formatObservable(t){let e=this._getObservableInfo(t);if(e)return{name:t.debugName,instanceId:e.instanceId}}_formatObserver(t){if(t instanceof De)return{name:t.toString(),instanceId:this._getObservableInfo(t)?.instanceId};let e=this._getAutorunInfo(t);if(e)return{name:t.toString(),instanceId:e.instanceId}}_handleChange(t){wl(this._fullState,t),this._pendingChanges===null?this._pendingChanges=t:Rl(this._pendingChanges,t),this._changeThrottler.throttle(this._flushUpdates,10)}_getDeclarationId(t,e){if(!e)return-1;let n=this._declarations.get(e.id);return n===void 0&&(n={id:this._declarationId++,type:t,url:e.fileName,line:e.line,column:e.column},this._declarations.set(e.id,n),this._handleChange({decls:{[n.id]:n}})),n.id}handleObservableCreated(t,e){let r={declarationId:this._getDeclarationId("observable/value",e),instanceId:this._instanceId++,listenerCount:0,lastValue:void 0,updateCount:0,changedObservables:new Set};this._instanceInfos.set(t,r)}handleOnListenerCountChanged(t,e){let n=this._getObservableInfo(t);if(n){if(n.listenerCount===0&&e>0){let r=t instanceof De?"observable/derived":"observable/value";this._aliveInstances.set(n.instanceId,t),this._handleChange({instances:{[n.instanceId]:{instanceId:n.instanceId,declarationId:n.declarationId,formattedValue:n.lastValue,type:r,name:t.debugName}}})}else n.listenerCount>0&&e===0&&(this._handleChange({instances:{[n.instanceId]:null}}),this._aliveInstances.delete(n.instanceId));n.listenerCount=e}}handleObservableUpdated(t,e){if(t instanceof De){this._handleDerivedRecomputed(t,e);return}let n=this._getObservableInfo(t);n&&e.didChange&&(n.lastValue=et(e.newValue,30),n.listenerCount>0&&this._handleChange({instances:{[n.instanceId]:{formattedValue:n.lastValue}}}))}handleAutorunCreated(t,e){let r={declarationId:this._getDeclarationId("autorun",e),instanceId:this._instanceId++,updateCount:0,changedObservables:new Set};this._instanceInfos.set(t,r),this._aliveInstances.set(r.instanceId,t),r&&this._handleChange({instances:{[r.instanceId]:{instanceId:r.instanceId,declarationId:r.declarationId,runCount:0,type:"autorun",name:t.debugName}}})}handleAutorunDisposed(t){let e=this._getAutorunInfo(t);e&&(this._handleChange({instances:{[e.instanceId]:null}}),this._instanceInfos.delete(t),this._aliveInstances.delete(e.instanceId))}handleAutorunDependencyChanged(t,e,n){let r=this._getAutorunInfo(t);r&&r.changedObservables.add(e)}handleAutorunStarted(t){}handleAutorunFinished(t){let e=this._getAutorunInfo(t);e&&(e.changedObservables.clear(),e.updateCount++,this._handleChange({instances:{[e.instanceId]:{runCount:e.updateCount}}}))}handleDerivedDependencyChanged(t,e,n){let r=this._getObservableInfo(t);r&&r.changedObservables.add(e)}_handleDerivedRecomputed(t,e){let n=this._getObservableInfo(t);if(!n)return;let r=et(e.newValue,30);n.updateCount++,n.changedObservables.clear(),n.lastValue=r,n.listenerCount>0&&this._handleChange({instances:{[n.instanceId]:{formattedValue:r,recomputationCount:n.updateCount}}})}handleDerivedCleared(t){let e=this._getObservableInfo(t);e&&(e.lastValue=void 0,e.changedObservables.clear(),e.listenerCount>0&&this._handleChange({instances:{[e.instanceId]:{formattedValue:void 0}}}))}handleBeginTransaction(t){this._activeTransactions.add(t)}handleEndTransaction(t){this._activeTransactions.delete(t)}};function Xu(i,t){let e=t?.debugNamePostProcessor??(o=>o),n=Fn.from(i,e);if(!n)return"";let r=new Set;return t.type==="observers"?ep(n,0,r,t).trim():Zu(n,0,r,t).trim()}function Zu(i,t,e,n){let r="		".repeat(t),o=[];if(e.has(i.sourceObj))return o.push(`${r}* ${i.type} ${i.name} (already listed)`),o.join(`
`);if(e.add(i.sourceObj),o.push(`${r}* ${i.type} ${i.name}:`),o.push(`${r}  value: ${et(i.value,50)}`),o.push(`${r}  state: ${i.state}`),i.dependencies.length>0){o.push(`${r}  dependencies:`);for(let a of i.dependencies){let l=Fn.from(a,n.debugNamePostProcessor??(c=>c))??Fn.unknown(a);o.push(Zu(l,t+1,e,n))}}return o.join(`
`)}function ep(i,t,e,n){let r="		".repeat(t),o=[];if(e.has(i.sourceObj))return o.push(`${r}* ${i.type} ${i.name} (already listed)`),o.join(`
`);if(e.add(i.sourceObj),o.push(`${r}* ${i.type} ${i.name}:`),o.push(`${r}  value: ${et(i.value,50)}`),o.push(`${r}  state: ${i.state}`),i.observers.length>0){o.push(`${r}  observers:`);for(let a of i.observers){let l=Fn.from(a,n.debugNamePostProcessor??(c=>c))??Fn.unknown(a);o.push(ep(l,t+1,e,n))}}return o.join(`
`)}var Fn=class i{constructor(t,e,n,r,o,s,a){this.sourceObj=t;this.name=e;this.type=n;this.value=r;this.state=o;this.dependencies=s;this.observers=a}static from(t,e){if(t instanceof Wt){let n=t.debugGetState();return new i(t,e(t.debugName),"autorun",void 0,n.stateStr,Array.from(n.dependencies),[])}else if(t instanceof De){let n=t.debugGetState();return new i(t,e(t.debugName),"derived",n.value,n.stateStr,Array.from(n.dependencies),Array.from(t.debugGetObservers()))}else if(t instanceof Mt){let n=t.debugGetState();return new i(t,e(t.debugName),"observableValue",n.value,"upToDate",[],Array.from(t.debugGetObservers()))}else if(t instanceof at){let n=t.debugGetState();return new i(t,e(t.debugName),"fromEvent",n.value,n.hasValue?"upToDate":"initial",[],Array.from(t.debugGetObservers()))}}static unknown(t){return new i(t,"(unknown)","unknown",void 0,"unknown",[],[])}};zu(Xu);Mu(Qu);var Uh=!1;Uh&&Ti(new _i);be&&be.VSCODE_DEV_DEBUG_OBSERVABLES&&Ti(Go.getInstance());var Pl=class{constructor(){this._value="";this._pos=0}reset(t){return this._value=t,this._pos=0,this}next(){return this._pos+=1,this}hasNext(){return this._pos<this._value.length-1}cmp(t){let e=t.charCodeAt(0),n=this._value.charCodeAt(this._pos);return e-n}value(){return this._value[this._pos]}},Al=class{constructor(t=!0){this._caseSensitive=t}reset(t){return this._value=t,this._from=0,this._to=0,this.next()}hasNext(){return this._to<this._value.length}next(){this._from=this._to;let t=!0;for(;this._to<this._value.length;this._to++)if(this._value.charCodeAt(this._to)===46)if(t)this._from++;else break;else t=!1;return this}cmp(t){return this._caseSensitive?So(t,this._value,0,t.length,this._from,this._to):En(t,this._value,0,t.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}},Jo=class{constructor(t=!0,e=!0){this._splitOnBackslash=t;this._caseSensitive=e}reset(t){this._from=0,this._to=0,this._value=t,this._valueLen=t.length;for(let e=t.length-1;e>=0;e--,this._valueLen--){let n=this._value.charCodeAt(e);if(!(n===47||this._splitOnBackslash&&n===92))break}return this.next()}hasNext(){return this._to<this._valueLen}next(){this._from=this._to;let t=!0;for(;this._to<this._valueLen;this._to++){let e=this._value.charCodeAt(this._to);if(e===47||this._splitOnBackslash&&e===92)if(t)this._from++;else break;else t=!1}return this}cmp(t){return this._caseSensitive?So(t,this._value,0,t.length,this._from,this._to):En(t,this._value,0,t.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}};var kl=class{constructor(t,e){this._ignorePathCasing=t;this._ignoreQueryAndFragment=e;this._states=[];this._stateIdx=0}reset(t){return this._value=t,this._states=[],this._value.scheme&&this._states.push(1),this._value.authority&&this._states.push(2),this._value.path&&(this._pathIterator=new Jo(!1,!this._ignorePathCasing(t)),this._pathIterator.reset(t.path),this._pathIterator.value()&&this._states.push(3)),this._ignoreQueryAndFragment(t)||(this._value.query&&this._states.push(4),this._value.fragment&&this._states.push(5)),this._stateIdx=0,this}next(){return this._states[this._stateIdx]===3&&this._pathIterator.hasNext()?this._pathIterator.next():this._stateIdx+=1,this}hasNext(){return this._states[this._stateIdx]===3&&this._pathIterator.hasNext()||this._stateIdx<this._states.length-1}cmp(t){if(this._states[this._stateIdx]===1)return Ka(t,this._value.scheme);if(this._states[this._stateIdx]===2)return Ka(t,this._value.authority);if(this._states[this._stateIdx]===3)return this._pathIterator.cmp(t);if(this._states[this._stateIdx]===4)return ai(t,this._value.query);if(this._states[this._stateIdx]===5)return ai(t,this._value.fragment);throw new Error}value(){if(this._states[this._stateIdx]===1)return this._value.scheme;if(this._states[this._stateIdx]===2)return this._value.authority;if(this._states[this._stateIdx]===3)return this._pathIterator.value();if(this._states[this._stateIdx]===4)return this._value.query;if(this._states[this._stateIdx]===5)return this._value.fragment;throw new Error}},Bt=class i{static{this.Val=Symbol("undefined_placeholder")}static wrap(t){return t===void 0?i.Val:t}static unwrap(t){return t===i.Val?void 0:t}},vr=class{constructor(){this.height=1;this.value=void 0;this.key=void 0;this.left=void 0;this.mid=void 0;this.right=void 0}isEmpty(){return!this.left&&!this.mid&&!this.right&&this.value===void 0}rotateLeft(){let t=this.right;return this.right=t.left,t.left=this,this.updateHeight(),t.updateHeight(),t}rotateRight(){let t=this.left;return this.left=t.right,t.right=this,this.updateHeight(),t.updateHeight(),t}updateHeight(){this.height=1+Math.max(this.heightLeft,this.heightRight)}balanceFactor(){return this.heightRight-this.heightLeft}get heightLeft(){return this.left?.height??0}get heightRight(){return this.right?.height??0}};var ln=class i{static forUris(t=()=>!1,e=()=>!1){return new i(new kl(t,e))}static forPaths(t=!1){return new i(new Jo(void 0,!t))}static forStrings(){return new i(new Pl)}static forConfigKeys(){return new i(new Al)}constructor(t){this._iter=t}clear(){this._root=void 0}fill(t,e){if(e){let n=e.slice(0);xa(n);for(let r of n)this.set(r,t)}else{let n=t.slice(0);xa(n);for(let r of n)this.set(r[0],r[1])}}set(t,e){let n=this._iter.reset(t),r;this._root||(this._root=new vr,this._root.segment=n.value());let o=[];for(r=this._root;;){let a=n.cmp(r.segment);if(a>0)r.left||(r.left=new vr,r.left.segment=n.value()),o.push([-1,r]),r=r.left;else if(a<0)r.right||(r.right=new vr,r.right.segment=n.value()),o.push([1,r]),r=r.right;else if(n.hasNext())n.next(),r.mid||(r.mid=new vr,r.mid.segment=n.value()),o.push([0,r]),r=r.mid;else break}let s=Bt.unwrap(r.value);r.value=Bt.wrap(e),r.key=t;for(let a=o.length-1;a>=0;a--){let l=o[a][1];l.updateHeight();let c=l.balanceFactor();if(c<-1||c>1){let p=o[a][0],u=o[a+1][0];if(p===1&&u===1)o[a][1]=l.rotateLeft();else if(p===-1&&u===-1)o[a][1]=l.rotateRight();else if(p===1&&u===-1)l.right=o[a+1][1]=o[a+1][1].rotateRight(),o[a][1]=l.rotateLeft();else if(p===-1&&u===1)l.left=o[a+1][1]=o[a+1][1].rotateLeft(),o[a][1]=l.rotateRight();else throw new Error;if(a>0)switch(o[a-1][0]){case-1:o[a-1][1].left=o[a][1];break;case 1:o[a-1][1].right=o[a][1];break;case 0:o[a-1][1].mid=o[a][1];break}else this._root=o[0][1]}}return s}get(t){return Bt.unwrap(this._getNode(t)?.value)}_getNode(t){let e=this._iter.reset(t),n=this._root;for(;n;){let r=e.cmp(n.segment);if(r>0)n=n.left;else if(r<0)n=n.right;else if(e.hasNext())e.next(),n=n.mid;else break}return n}has(t){let e=this._getNode(t);return!(e?.value===void 0&&e?.mid===void 0)}delete(t){return this._delete(t,!1)}deleteSuperstr(t){return this._delete(t,!0)}_delete(t,e){let n=this._iter.reset(t),r=[],o=this._root;for(;o;){let s=n.cmp(o.segment);if(s>0)r.push([-1,o]),o=o.left;else if(s<0)r.push([1,o]),o=o.right;else if(n.hasNext())n.next(),r.push([0,o]),o=o.mid;else break}if(o){if(e?(o.left=void 0,o.mid=void 0,o.right=void 0,o.height=1):(o.key=void 0,o.value=void 0),!o.mid&&!o.value)if(o.left&&o.right){let s=[[1,o]],a=this._min(o.right,s);if(a.key){o.key=a.key,o.value=a.value,o.segment=a.segment;let l=a.right;if(s.length>1){let[p,u]=s[s.length-1];switch(p){case-1:u.left=l;break;case 0:oo(!1);case 1:oo(!1)}}else o.right=l;let c=this._balanceByStack(s);if(r.length>0){let[p,u]=r[r.length-1];switch(p){case-1:u.left=c;break;case 0:u.mid=c;break;case 1:u.right=c;break}}else this._root=c}}else{let s=o.left??o.right;if(r.length>0){let[a,l]=r[r.length-1];switch(a){case-1:l.left=s;break;case 0:l.mid=s;break;case 1:l.right=s;break}}else this._root=s}this._root=this._balanceByStack(r)??this._root}}_min(t,e){for(;t.left;)e.push([-1,t]),t=t.left;return t}_balanceByStack(t){for(let e=t.length-1;e>=0;e--){let n=t[e][1];n.updateHeight();let r=n.balanceFactor();if(r>1?(n.right.balanceFactor()>=0||(n.right=n.right.rotateRight()),t[e][1]=n.rotateLeft()):r<-1&&(n.left.balanceFactor()<=0||(n.left=n.left.rotateLeft()),t[e][1]=n.rotateRight()),e>0)switch(t[e-1][0]){case-1:t[e-1][1].left=t[e][1];break;case 1:t[e-1][1].right=t[e][1];break;case 0:t[e-1][1].mid=t[e][1];break}else return t[0][1]}}findSubstr(t){let e=this._iter.reset(t),n=this._root,r;for(;n;){let o=e.cmp(n.segment);if(o>0)n=n.left;else if(o<0)n=n.right;else if(e.hasNext())e.next(),r=Bt.unwrap(n.value)||r,n=n.mid;else break}return n&&Bt.unwrap(n.value)||r}findSuperstr(t){return this._findSuperstrOrElement(t,!1)}_findSuperstrOrElement(t,e){let n=this._iter.reset(t),r=this._root;for(;r;){let o=n.cmp(r.segment);if(o>0)r=r.left;else if(o<0)r=r.right;else if(n.hasNext())n.next(),r=r.mid;else return r.mid?this._entries(r.mid):e?Bt.unwrap(r.value):void 0}}hasElementOrSubtree(t){return this._findSuperstrOrElement(t,!0)!==void 0}forEach(t){for(let[e,n]of this)t(n,e)}*[Symbol.iterator](){yield*this._entries(this._root)}_entries(t){let e=[];return this._dfsEntries(t,e),e[Symbol.iterator]()}_dfsEntries(t,e){t&&(t.left&&this._dfsEntries(t.left,e),t.value!==void 0&&e.push([t.key,Bt.unwrap(t.value)]),t.mid&&this._dfsEntries(t.mid,e),t.right&&this._dfsEntries(t.right,e))}_isBalanced(){let t=e=>{if(!e)return!0;let n=e.balanceFactor();return n<-1||n>1?!1:t(e.left)&&t(e.right)};return t(this._root)}};var tt=re("fileService");function Vt(i){return i.create===!0}function nt(i){return!!(i.capabilities&2)}function tp(i){return!!(i.capabilities&524288)}function Dl(i){return!!(i.capabilities&8)}function np(i){return!!(i.capabilities&131072)}function rp(i){return!!(i.capabilities&262144)}function qt(i){return!!(i.capabilities&4)}function Xo(i){return!!(i.capabilities&16)}function Zo(i){return nt(i)?!!(i.capabilities&16384):!1}function Ol(i){return nt(i)?!!(i.capabilities&32768):!1}function ip(i){return!!(i.capabilities&65536)}var br=class i extends Error{constructor(e,n){super(e);this.code=n}static create(e,n){let r=new i(e.toString(),n);return Nh(r,n),r}};function Y(i,t){return br.create(i,t)}function Kt(i){return i||Y(g(2124,null),"Unknown")}function Nh(i,t){return i.name=t?`${t} (FileSystemError)`:"FileSystemError",i}function xt(i){if(!i)return"Unknown";if(i instanceof br)return i.code;let t=/^(.+) \(FileSystemError\)$/.exec(i.name);if(!t)return"Unknown";switch(t[1]){case"EntryExists":return"EntryExists";case"EntryIsADirectory":return"EntryIsADirectory";case"EntryNotADirectory":return"EntryNotADirectory";case"EntryNotFound":return"EntryNotFound";case"EntryTooLarge":return"EntryTooLarge";case"EntryWriteLocked":return"EntryWriteLocked";case"NoPermissions":return"NoPermissions";case"Unavailable":return"Unavailable"}return"Unknown"}function Ll(i){if(i instanceof Ce)return i.fileOperationResult;switch(xt(i)){case"EntryNotFound":return 1;case"EntryIsADirectory":return 0;case"EntryNotADirectory":return 9;case"EntryWriteLocked":return 5;case"NoPermissions":return 6;case"EntryExists":return 4;case"EntryTooLarge":return 7;default:return 10}}var $t=class{constructor(t,e,n){this.resource=t;this.operation=e;this.target=n}isOperation(t){return this.operation===t}};var Qo=class i{constructor(t,e){this.ignorePathCasing=e;this.correlationId=void 0;this.added=new He(()=>{let t=ln.forUris(()=>this.ignorePathCasing);return t.fill(this.rawAdded.map(e=>[e,!0])),t});this.updated=new He(()=>{let t=ln.forUris(()=>this.ignorePathCasing);return t.fill(this.rawUpdated.map(e=>[e,!0])),t});this.deleted=new He(()=>{let t=ln.forUris(()=>this.ignorePathCasing);return t.fill(this.rawDeleted.map(e=>[e,!0])),t});this.rawAdded=[];this.rawUpdated=[];this.rawDeleted=[];for(let n of t){switch(n.type){case 1:this.rawAdded.push(n.resource);break;case 0:this.rawUpdated.push(n.resource);break;case 2:this.rawDeleted.push(n.resource);break}this.correlationId!==i.MIXED_CORRELATION&&(typeof n.cId=="number"?this.correlationId===void 0?this.correlationId=n.cId:this.correlationId!==n.cId&&(this.correlationId=i.MIXED_CORRELATION):this.correlationId!==void 0&&(this.correlationId=i.MIXED_CORRELATION))}}static{this.MIXED_CORRELATION=null}contains(t,...e){return this.doContains(t,{includeChildren:!1},...e)}affects(t,...e){return this.doContains(t,{includeChildren:!0},...e)}doContains(t,e,...n){if(!t)return!1;let r=n.length>0;return!!((!r||n.includes(1))&&(this.added.value.get(t)||e.includeChildren&&this.added.value.findSuperstr(t))||(!r||n.includes(0))&&(this.updated.value.get(t)||e.includeChildren&&this.updated.value.findSuperstr(t))||(!r||n.includes(2))&&(this.deleted.value.findSubstr(t)||e.includeChildren&&this.deleted.value.findSuperstr(t)))}gotAdded(){return this.rawAdded.length>0}gotDeleted(){return this.rawDeleted.length>0}gotUpdated(){return this.rawUpdated.length>0}correlates(t){return this.correlationId===t}hasCorrelation(){return typeof this.correlationId=="number"}};function op(i,t,e){return!i||!t||i===t||t.length>i.length?!1:(t.charAt(t.length-1)!==Se&&(t+=Se),e?tn(i,t):i.indexOf(t)===0)}var Ce=class extends Error{constructor(e,n,r){super(e);this.fileOperationResult=n;this.options=r}},yr=class extends Ce{constructor(e,n,r,o){super(e,n,o);this.fileOperationResult=n;this.size=r}},Ir=class extends Ce{constructor(e,n,r){super(e,2,r);this.stat=n}};var es="";function Fl(i){if(!(typeof i.size!="number"||typeof i.mtime!="number"))return i.mtime.toString(29)+i.size.toString(31)}var Yo=class i{static{this.KB=1024}static{this.MB=i.KB*i.KB}static{this.GB=i.MB*i.KB}static{this.TB=i.GB*i.KB}static formatSize(t){return Yr(t)||(t=0),t<i.KB?g(2119,null,t.toFixed(0)):t<i.MB?g(2121,null,(t/i.KB).toFixed(2)):t<i.GB?g(2122,null,(t/i.MB).toFixed(2)):t<i.TB?g(2120,null,(t/i.GB).toFixed(2)):g(2123,null,(t/i.TB).toFixed(2))}};function sp(i){return i.type.startsWith("root/")}function Sr(i){return i.type.startsWith("session/")}function ts(i){return i.type.startsWith("terminal/")}var Oe={SessionNotFound:-32001,ProviderNotFound:-32002,SessionAlreadyExists:-32003,TurnInProgress:-32004,UnsupportedProtocolVersion:-32005,ContentNotFound:-32006,AuthRequired:-32007,NotFound:-32008,PermissionDenied:-32009,AlreadyExists:-32010};var lp=-32700,Tr=-32603,cn=-32001,cp=-32002;var dp=-32005;var ns=-32007;function up(i){return"method"in i&&"id"in i}function pp(i){return"method"in i&&!("id"in i)}var H=class extends Error{constructor(e,n,r){super(n);this.code=e;this.data=r}};var os="agenthost:/root";function mp(i){if(!i.content||i.content.length===0)return[];let t=[];for(let e of i.content)We(e,{type:!0})&&e.type==="fileEdit"&&t.push(e);return t}function Ei(i,t){return`${i.endsWith("/")?i.slice(0,-1):i}/subagent/${t}`}function ss(i){let t=i.lastIndexOf("/subagent/");if(t<0)return;let e=i.substring(t+10);if(e)return{parentSession:i.substring(0,t),toolCallId:e}}function hp(){return{agents:[],activeSessions:0}}function Bl(i){return{summary:i,lifecycle:"creating",turns:[],activeTurn:void 0}}var _r="**",vp="/",as="[/\\\\]",ls="[^/\\\\]",Kh=/\//g;function bp(i,t){switch(i){case 0:return"";case 1:return`${ls}*?`;default:return`(?:${as}|${ls}+${as}${t?`|${as}${ls}+`:""})*?`}}function yp(i,t){if(!i)return[];let e=[],n=!1,r=!1,o="";for(let s of i){switch(s){case t:if(!n&&!r){e.push(o),o="";continue}break;case"{":n=!0;break;case"}":n=!1;break;case"[":r=!0;break;case"]":r=!1;break}o+=s}return o&&e.push(o),e}function _p(i){if(!i)return"";let t="",e=yp(i,vp);if(e.every(n=>n===_r))t=".*";else{let n=!1;e.forEach((r,o)=>{if(r===_r){if(n)return;t+=bp(2,o===e.length-1)}else{let s=!1,a="",l=!1,c="";for(let p of r){if(p!=="}"&&s){a+=p;continue}if(l&&(p!=="]"||!c)){let u;p==="-"?u=p:(p==="^"||p==="!")&&!c?u="^":p===vp?u="":u=Dt(p),c+=u;continue}switch(p){case"{":s=!0;continue;case"[":l=!0;continue;case"}":{let f=`(?:${yp(a,",").map(m=>_p(m)).join("|")})`;t+=f,s=!1,a="";break}case"]":{t+="["+c+"]",l=!1,c="";break}case"?":t+=ls;continue;case"*":t+=bp(1);continue;default:t+=Dt(p)}}o<e.length-1&&(e[o+1]!==_r||o+2<e.length)&&(t+=as)}n=r===_r})}return t}var zh=/^\*\*\/\*\.[\w\.-]+$/,jh=/^\*\*\/([\w\.-]+)\/?$/,Hh=/^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/,Gh=/^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/,Jh=/^\*\*((\/[\w\.-]+)+)\/?$/,Qh=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,Ip=new bt(1e4),Sp=function(){return!1},_t=function(){return null};function Vl(i,t){if(!i)return _t;let e;typeof i!="string"?e=i.pattern:e=i,e=e.trim();let n=t.ignoreCase??!1,r={...t,equals:n?Cn:(l,c)=>l===c,endsWith:n?Ud:(l,c)=>l.endsWith(c),isEqualOrParent:(l,c)=>Ot(l,c,t.ignoreCase??!ve)},o=`${n?e.toLowerCase():e}_${!!t.trimForExclusions}_${n}`,s=Ip.get(o);if(s)return Tp(s,i,r);let a;return zh.test(e)?s=Yh(e.substring(4),e,r):(a=jh.exec($l(e,r)))?s=Xh(a[1],e,r):(t.trimForExclusions?Gh:Hh).test(e)?s=Zh(e,r):(a=Jh.exec($l(e,r)))?s=xp(a[1].substring(1),e,!0,r):(a=Qh.exec($l(e,r)))?s=xp(a[1],e,!1,r):s=ev(e,r),Ip.set(o,s),Tp(s,i,r)}function Tp(i,t,e){if(typeof t=="string")return i;let n=function(r,o){return e.isEqualOrParent(r,t.base)?i(qa(r.substring(t.base.length),Se),o):null};return n.allBasenames=i.allBasenames,n.allPaths=i.allPaths,n.basenames=i.basenames,n.patterns=i.patterns,n}function $l(i,t){return t.trimForExclusions&&i.endsWith("/**")?i.substring(0,i.length-2):i}function Yh(i,t,e){return function(n,r){return typeof n=="string"&&e.endsWith(n,i)?t:null}}function Xh(i,t,e){let n=`/${i}`,r=`\\${i}`,o=function(a,l){return typeof a!="string"?null:l?e.equals(l,i)?t:null:e.equals(a,i)||e.endsWith(a,n)||e.endsWith(a,r)?t:null},s=[i];return o.basenames=s,o.patterns=[t],o.allBasenames=s,o}function Zh(i,t){let e=Cp(i.slice(1,-1).split(",").map(a=>Vl(a,t)).filter(a=>a!==_t),i),n=e.length;if(!n)return _t;if(n===1)return e[0];let r=function(a,l){for(let c=0,p=e.length;c<p;c++)if(e[c](a,l))return i;return null},o=e.find(a=>!!a.allBasenames);o&&(r.allBasenames=o.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(r.allPaths=s),r}function xp(i,t,e,n){let r=Se===z.sep,o=r?i:i.replace(Kh,Se),s=Se+o,a=z.sep+i,l;return e?l=function(c,p){return typeof c=="string"&&(n.equals(c,o)||n.endsWith(c,s)||!r&&(n.equals(c,i)||n.endsWith(c,a)))?t:null}:l=function(c,p){return typeof c=="string"&&(n.equals(c,o)||!r&&n.equals(c,i))?t:null},l.allPaths=[(e?"*/":"./")+i],l}function ev(i,t){try{let e=new RegExp(`^${_p(i)}$`,t.ignoreCase?"i":void 0);return function(n){return e.lastIndex=0,typeof n=="string"&&e.test(n)?i:null}}catch{return _t}}function Ep(i,t,e){return!i||typeof t!="string"?!1:ql(i,e)(t)}function ql(i,t={}){if(!i)return Sp;if(typeof i=="string"||tv(i)){let e=Vl(i,t);if(e===_t)return Sp;let n=function(r,o){return!!e(r,o)};return e.allBasenames&&(n.allBasenames=e.allBasenames),e.allPaths&&(n.allPaths=e.allPaths),n}return nv(i,t)}function tv(i){let t=i;return t?typeof t.base=="string"&&typeof t.pattern=="string":!1}function nv(i,t){let e=Cp(Object.getOwnPropertyNames(i).map(a=>rv(a,i[a],t)).filter(a=>a!==_t)),n=e.length;if(!n)return _t;if(!e.some(a=>!!a.requiresSiblings)){if(n===1)return e[0];let a=function(p,u){let f;for(let m=0,v=e.length;m<v;m++){let h=e[m](p,u);if(typeof h=="string")return h;wo(h)&&(f||(f=[]),f.push(h))}return f?(async()=>{for(let m of f){let v=await m;if(typeof v=="string")return v}return null})():null},l=e.find(p=>!!p.allBasenames);l&&(a.allBasenames=l.allBasenames);let c=e.reduce((p,u)=>u.allPaths?p.concat(u.allPaths):p,[]);return c.length&&(a.allPaths=c),a}let r=function(a,l,c){let p,u;for(let f=0,m=e.length;f<m;f++){let v=e[f];v.requiresSiblings&&c&&(l||(l=Te(a)),p||(p=l.substring(0,l.length-Pd(a).length)));let h=v(a,l,p,c);if(typeof h=="string")return h;wo(h)&&(u||(u=[]),u.push(h))}return u?(async()=>{for(let f of u){let m=await f;if(typeof m=="string")return m}return null})():null},o=e.find(a=>!!a.allBasenames);o&&(r.allBasenames=o.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(r.allPaths=s),r}function rv(i,t,e){if(t===!1)return _t;let n=Vl(i,e);if(n===_t)return _t;if(typeof t=="boolean")return n;if(t){let r=t.when;if(typeof r=="string"){let o=(s,a,l,c)=>{if(!c||!n(s,a))return null;let p=r.replace("$(basename)",()=>l),u=c(p);return wo(u)?u.then(f=>f?i:null):u?i:null};return o.requiresSiblings=!0,o}}return n}function Cp(i,t){let e=i.filter(a=>!!a.basenames);if(e.length<2)return i;let n=e.reduce((a,l)=>{let c=l.basenames;return c?a.concat(c):a},[]),r;if(t){r=[];for(let a=0,l=n.length;a<l;a++)r.push(t)}else r=e.reduce((a,l)=>{let c=l.patterns;return c?a.concat(c):a},[]);let o=function(a,l){if(typeof a!="string")return null;if(!l){let p;for(p=a.length;p>0;p--){let u=a.charCodeAt(p-1);if(u===47||u===92)break}l=a.substring(p)}let c=n.indexOf(l);return c!==-1?r[c]:null};o.basenames=n,o.patterns=r,o.allBasenames=n;let s=i.filter(a=>!a.basenames);return s.push(o),s}function Kl(i,t){return Jr(i,t,(e,n)=>typeof e=="string"&&typeof n=="string"?e===n:typeof e!="string"&&typeof n!="string"?e.base===n.base&&e.pattern===n.pattern:!1)}var cs=class{constructor(){this._currentMarkdownPartId=new Map;this._currentReasoningPartId=new Map}reset(t){this._currentMarkdownPartId.delete(t),this._currentReasoningPartId.delete(t)}mapProgressEventToActions(t,e,n){switch(t.type){case"delta":{let r=t,o=this._currentMarkdownPartId.get(e);if(!o){let s=ne();return this._currentMarkdownPartId.set(e,s),{type:"session/responsePart",session:e,turnId:n,part:{kind:"markdown",id:s,content:r.content}}}return{type:"session/delta",session:e,turnId:n,partId:o,content:r.content}}case"tool_start":{this._currentMarkdownPartId.delete(e);let r=t,o={toolKind:r.toolKind,language:r.language};r.subagentDescription&&(o.subagentDescription=r.subagentDescription),r.subagentAgentName&&(o.subagentAgentName=r.subagentAgentName);let s={type:"session/toolCallStart",session:e,turnId:n,toolCallId:r.toolCallId,toolName:r.toolName,displayName:r.displayName,toolClientId:r.toolClientId,_meta:o};if(r.toolClientId)return s;let a={type:"session/toolCallReady",session:e,turnId:n,toolCallId:r.toolCallId,invocationMessage:r.invocationMessage,toolInput:r.toolInput,confirmed:"not-needed"};return[s,a]}case"tool_ready":{let r=t;return{type:"session/toolCallReady",session:e,turnId:n,toolCallId:r.toolCallId,invocationMessage:r.invocationMessage,toolInput:r.toolInput,confirmationTitle:r.confirmationTitle,edits:r.edits,...r.confirmationTitle?{}:{confirmed:"not-needed"}}}case"tool_complete":{let r=t;return{type:"session/toolCallComplete",session:e,turnId:n,toolCallId:r.toolCallId,result:r.result}}case"tool_content_changed":{let r=t;return{type:"session/toolCallContentChanged",session:e,turnId:n,toolCallId:r.toolCallId,content:r.content}}case"idle":return{type:"session/turnComplete",session:e,turnId:n};case"error":{let r=t;return{type:"session/error",session:e,turnId:n,error:{errorType:r.errorType,message:r.message,stack:r.stack}}}case"usage":{let r=t;return{type:"session/usage",session:e,turnId:n,usage:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,model:r.model,cacheReadTokens:r.cacheReadTokens}}}case"title_changed":return{type:"session/titleChanged",session:e,title:t.title};case"reasoning":{let r=t,o=this._currentReasoningPartId.get(e);if(!o){let s=ne();return this._currentReasoningPartId.set(e,s),{type:"session/responsePart",session:e,turnId:n,part:{kind:"reasoning",id:s,content:r.content}}}return{type:"session/reasoning",session:e,turnId:n,partId:o,content:r.content}}case"message":{let r=t;if(r.role!=="assistant"||!r.content||this._currentMarkdownPartId.get(e))return;let s=ne();return this._currentMarkdownPartId.set(e,s),{type:"session/responsePart",session:e,turnId:n,part:{kind:"markdown",id:s,content:r.content}}}case"user_input_request":{let r=t;return{type:"session/inputRequested",session:e,request:r.request}}default:return}}};import*as wp from"fs";var iv=/&&|\|\||[;|]|`|\$\(/,zl=/(?!.*)/,Rp=/^[A-Z_][A-Z0-9_]*=/i,ds=class extends L{constructor(e){super();this._logService=e;this._initPromise=this._initTreeSitter()}initialize(){return this._initPromise}shouldAutoApprove(e){let n=e.trimStart();if(n.length===0)return"approved";this._ensureRules();let r=this._extractSubCommands(n);return r&&r.length>0?this._matchSubCommands(r):iv.test(n)?(this._logService.trace("[CommandAutoApprover] Compound command without tree-sitter, requiring confirmation"),"noMatch"):this._matchCommandLine(n)}_matchSubCommands(e){let n=!0;for(let r of e){if(Rp.test(r))return"denied";let o=this._matchSingleCommand(r);if(o==="denied")return"denied";o!=="approved"&&(n=!1)}return n?"approved":"noMatch"}_matchCommandLine(e){return Rp.test(e)?"denied":this._matchSingleCommand(e)}_matchSingleCommand(e){for(let n of this._denyRules)if(n.regex.test(e))return"denied";for(let n of this._allowRules)if(n.regex.test(e))return"approved";return"noMatch"}_extractSubCommands(e){if(!(!this._parser||!this._bashLanguage||!this._queryClass))try{this._parser.setLanguage(this._bashLanguage);let n=this._parser.parse(e);if(!n)return;try{let r=new this._queryClass(this._bashLanguage,"(command) @command"),s=r.captures(n.rootNode).map(a=>a.node.text);return r.delete(),s.length>0?s:void 0}finally{n.delete()}}catch(n){this._logService.warn("[CommandAutoApprover] Tree-sitter parsing failed",n);return}}async _initTreeSitter(){try{let{default:e}=await import("@vscode/tree-sitter-wasm");if(this._store.isDisposed)return;let n=b.joinPath(Xe.asFileUri(""),"..","node_modules","@vscode","tree-sitter-wasm","wasm"),r=b.joinPath(n,"tree-sitter.wasm").fsPath;if(await e.Parser.init({locateFile(){return r}}),this._store.isDisposed)return;let o=new e.Parser;this._register(w(()=>{try{o.delete()}catch{}}));let s=b.joinPath(n,"tree-sitter-bash.wasm").fsPath,a=await wp.promises.readFile(s);if(this._store.isDisposed)return;let l=await e.Language.load(new Uint8Array(a.buffer,a.byteOffset,a.byteLength));if(this._store.isDisposed)return;this._parser=o,this._bashLanguage=l,this._queryClass=e.Query,this._logService.info("[CommandAutoApprover] Tree-sitter initialized successfully")}catch(e){this._logService.warn("[CommandAutoApprover] Failed to initialize tree-sitter",e)}}_ensureRules(){if(this._allowRules&&this._denyRules)return;let e=[],n=[];for(let[r,o]of Object.entries(sv)){let s=ov(r);o===!0?e.push({regex:s}):o===!1&&n.push({regex:s})}this._allowRules=e,this._denyRules=n}};function ov(i){let t=i.match(/^\/(?<pattern>.+)\/(?<flags>[dgimsuvy]*)$/),e=t?.groups?.pattern;if(e){let r=t.groups?.flags;if(r&&(r=r.replaceAll("g","")),e===".*")return new RegExp(e);try{let o=new RegExp(e,r||void 0);return Fd(o)?zl:o}catch{return zl}}if(i==="")return zl;let n;if(i.includes("/")||i.includes("\\")){let r=i.replace(/[/\\]/g,"%%PATH_SEP%%");r=Dt(r),r=r.replace(/%%PATH_SEP%%*/g,"[/\\\\]"),n=`^(?:\\.[/\\\\])?${r}`}else n=Dt(i);return new RegExp(`^${n}\\b`)}var sv={cd:!0,echo:!0,ls:!0,dir:!0,pwd:!0,cat:!0,head:!0,tail:!0,findstr:!0,wc:!0,tr:!0,cut:!0,cmp:!0,which:!0,basename:!0,dirname:!0,realpath:!0,readlink:!0,stat:!0,file:!0,od:!0,du:!0,df:!0,sleep:!0,nl:!0,grep:!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+status\\b/":!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+log\\b/":!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+log\\b.*\\s--output(=|\\s|$)/":!1,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+show\\b/":!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+diff\\b/":!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+ls-files\\b/":!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+grep\\b/":!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+branch\\b/":!0,"/^git(\\s+(-C\\s+\\S+|--no-pager))*\\s+branch\\b.*\\s-(d|D|m|M|-delete|-force)\\b/":!1,"/^docker\\s+(ps|images|info|version|inspect|logs|top|stats|port|diff|search|events)\\b/":!0,"/^docker\\s+(container|image|network|volume|context|system)\\s+(ls|ps|inspect|history|show|df|info)\\b/":!0,"/^docker\\s+compose\\s+(ps|ls|top|logs|images|config|version|port|events)\\b/":!0,"Get-ChildItem":!0,"Get-Content":!0,"Get-Date":!0,"Get-Random":!0,"Get-Location":!0,"Set-Location":!0,"Write-Host":!0,"Write-Output":!0,"Out-String":!0,"Split-Path":!0,"Join-Path":!0,"Start-Sleep":!0,"Where-Object":!0,"/^Select-[a-z0-9]/i":!0,"/^Measure-[a-z0-9]/i":!0,"/^Compare-[a-z0-9]/i":!0,"/^Format-[a-z0-9]/i":!0,"/^Sort-[a-z0-9]/i":!0,"/^npm\\s+(ls|list|outdated|view|info|show|explain|why|root|prefix|bin|search|doctor|fund|repo|bugs|docs|home|help(-search)?)\\b/":!0,"/^npm\\s+config\\s+(list|get)\\b/":!0,"/^npm\\s+pkg\\s+get\\b/":!0,"/^npm\\s+audit$/":!0,"/^npm\\s+cache\\s+verify\\b/":!0,"/^yarn\\s+(list|outdated|info|why|bin|help|versions)\\b/":!0,"/^yarn\\s+licenses\\b/":!0,"/^yarn\\s+audit\\b(?!.*\\bfix\\b)/":!0,"/^yarn\\s+config\\s+(list|get)\\b/":!0,"/^yarn\\s+cache\\s+dir\\b/":!0,"/^pnpm\\s+(ls|list|outdated|why|root|bin|doctor)\\b/":!0,"/^pnpm\\s+licenses\\b/":!0,"/^pnpm\\s+audit\\b(?!.*\\bfix\\b)/":!0,"/^pnpm\\s+config\\s+(list|get)\\b/":!0,"npm ci":!0,"/^yarn\\s+install\\s+--frozen-lockfile\\b/":!0,"/^pnpm\\s+install\\s+--frozen-lockfile\\b/":!0,column:!0,"/^column\\b.*\\s-c\\s+[0-9]{4,}/":!1,date:!0,"/^date\\b.*\\s(-s|--set)\\b/":!1,find:!0,"/^find\\b.*\\s-(delete|exec|execdir|fprint|fprintf|fls|ok|okdir)\\b/":!1,rg:!0,"/^rg\\b.*\\s(--pre|--hostname-bin)\\b/":!1,sed:!0,"/^sed\\b.*\\s(-[a-zA-Z]*(e|f)[a-zA-Z]*|--expression|--file)\\b/":!1,"/^sed\\b.*s\\/.*\\/.*\\/[ew]/":!1,"/^sed\\b.*;W/":!1,sort:!0,"/^sort\\b.*\\s-(o|S)\\b/":!1,tree:!0,"/^tree\\b.*\\s-o\\b/":!1,"/^xxd$/":!0,"/^xxd\\b(\\s+-\\S+)*\\s+[^-\\s]\\S*$/":!0,rm:!1,rmdir:!1,del:!1,"Remove-Item":!1,ri:!1,rd:!1,erase:!1,dd:!1,kill:!1,ps:!1,top:!1,"Stop-Process":!1,spps:!1,taskkill:!1,"taskkill.exe":!1,curl:!1,wget:!1,"Invoke-RestMethod":!1,"Invoke-WebRequest":!1,irm:!1,iwr:!1,chmod:!1,chown:!1,"Set-ItemProperty":!1,sp:!1,"Set-Acl":!1,jq:!1,xargs:!1,eval:!1,"Invoke-Expression":!1,iex:!1};import{Worker as Ev}from"worker_threads";function Er(i){return Hl(i,0)}function Hl(i,t){switch(typeof i){case"object":return i===null?zt(349,t):Array.isArray(i)?lv(i,t):cv(i,t);case"string":return Ap(i,t);case"boolean":return av(i,t);case"number":return zt(i,t);case"undefined":return zt(937,t);default:return zt(617,t)}}function zt(i,t){return(t<<5)-t+i|0}function av(i,t){return zt(i?433:863,t)}function Ap(i,t){t=zt(149417,t);for(let e=0,n=i.length;e<n;e++)t=zt(i.charCodeAt(e),t);return t}function lv(i,t){return t=zt(104579,t),i.reduce((e,n)=>Hl(n,e),t)}function cv(i,t){return t=zt(181387,t),Object.keys(i).sort().reduce((e,n)=>(e=Ap(n,e),Hl(i[n],e)),t)}function jl(i,t,e=32){let n=e-t,r=~((1<<n)-1);return(i<<t|(r&i)>>>n)>>>0}function Ci(i,t=32){return i instanceof ArrayBuffer?sn(_.wrap(new Uint8Array(i))):(i>>>0).toString(16).padStart(t/4,"0")}var Pp=class i{constructor(){this._h0=1732584193;this._h1=4023233417;this._h2=2562383102;this._h3=271733878;this._h4=3285377520;this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}static{this._bigBlock32=new DataView(new ArrayBuffer(320))}update(t){let e=t.length;if(e===0)return;let n=this._buff,r=this._buffLen,o=this._leftoverHighSurrogate,s,a;for(o!==0?(s=o,a=-1,o=0):(s=t.charCodeAt(0),a=0);;){let l=s;if(Nd(s))if(a+1<e){let c=t.charCodeAt(a+1);ja(c)?(a++,l=Md(s,c)):l=65533}else{o=s;break}else ja(s)&&(l=65533);if(r=this._push(n,r,l),a++,a<e)s=t.charCodeAt(a);else break}this._buffLen=r,this._leftoverHighSurrogate=o}_push(t,e,n){return n<128?t[e++]=n:n<2048?(t[e++]=192|(n&1984)>>>6,t[e++]=128|(n&63)>>>0):n<65536?(t[e++]=224|(n&61440)>>>12,t[e++]=128|(n&4032)>>>6,t[e++]=128|(n&63)>>>0):(t[e++]=240|(n&1835008)>>>18,t[e++]=128|(n&258048)>>>12,t[e++]=128|(n&4032)>>>6,t[e++]=128|(n&63)>>>0),e>=64&&(this._step(),e-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),e}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),Ci(this._h0)+Ci(this._h1)+Ci(this._h2)+Ci(this._h3)+Ci(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,this._buff.subarray(this._buffLen).fill(0),this._buffLen>56&&(this._step(),this._buff.fill(0));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=i._bigBlock32,e=this._buffDV;for(let u=0;u<64;u+=4)t.setUint32(u,e.getUint32(u,!1),!1);for(let u=64;u<320;u+=4)t.setUint32(u,jl(t.getUint32(u-12,!1)^t.getUint32(u-32,!1)^t.getUint32(u-56,!1)^t.getUint32(u-64,!1),1),!1);let n=this._h0,r=this._h1,o=this._h2,s=this._h3,a=this._h4,l,c,p;for(let u=0;u<80;u++)u<20?(l=r&o|~r&s,c=1518500249):u<40?(l=r^o^s,c=1859775393):u<60?(l=r&o|r&s|o&s,c=2400959708):(l=r^o^s,c=3395469782),p=jl(n,5)+l+a+c+t.getUint32(u*4,!1)&4294967295,a=s,s=o,o=jl(r,30),r=n,n=p;this._h0=this._h0+n&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+o&4294967295,this._h3=this._h3+s&4294967295,this._h4=this._h4+a&4294967295}};function Gl(...i){switch(i.length){case 1:return g(1922,null,i[0]);case 2:return g(1923,null,i[0],i[1]);case 3:return g(1924,null,i[0],i[1],i[2]);default:return}}var dv=g(1921,null),uv=g(1920,null),dn=class i{constructor(){this._input="";this._start=0;this._current=0;this._tokens=[];this._errors=[];this.stringRe=/[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy}static getLexeme(t){switch(t.type){case 0:return"(";case 1:return")";case 2:return"!";case 3:return t.isTripleEq?"===":"==";case 4:return t.isTripleEq?"!==":"!=";case 5:return"<";case 6:return"<=";case 7:return">=";case 8:return">=";case 9:return"=~";case 10:return t.lexeme;case 11:return"true";case 12:return"false";case 13:return"in";case 14:return"not";case 15:return"&&";case 16:return"||";case 17:return t.lexeme;case 18:return t.lexeme;case 19:return t.lexeme;case 20:return"EOF";default:throw to(`unhandled token type: ${JSON.stringify(t)}; have you forgotten to add a case?`)}}static{this._regexFlags=new Set(["i","g","s","m","y","u"].map(t=>t.charCodeAt(0)))}static{this._keywords=new Map([["not",14],["in",13],["false",12],["true",11]])}get errors(){return this._errors}reset(t){return this._input=t,this._start=0,this._current=0,this._tokens=[],this._errors=[],this}scan(){for(;!this._isAtEnd();)switch(this._start=this._current,this._advance()){case 40:this._addToken(0);break;case 41:this._addToken(1);break;case 33:if(this._match(61)){let e=this._match(61);this._tokens.push({type:4,offset:this._start,isTripleEq:e})}else this._addToken(2);break;case 39:this._quotedString();break;case 47:this._regex();break;case 61:if(this._match(61)){let e=this._match(61);this._tokens.push({type:3,offset:this._start,isTripleEq:e})}else this._match(126)?this._addToken(9):this._error(Gl("==","=~"));break;case 60:this._addToken(this._match(61)?6:5);break;case 62:this._addToken(this._match(61)?8:7);break;case 38:this._match(38)?this._addToken(15):this._error(Gl("&&"));break;case 124:this._match(124)?this._addToken(16):this._error(Gl("||"));break;case 32:case 13:case 9:case 10:case 160:break;default:this._string()}return this._start=this._current,this._addToken(20),Array.from(this._tokens)}_match(t){return this._isAtEnd()||this._input.charCodeAt(this._current)!==t?!1:(this._current++,!0)}_advance(){return this._input.charCodeAt(this._current++)}_peek(){return this._isAtEnd()?0:this._input.charCodeAt(this._current)}_addToken(t){this._tokens.push({type:t,offset:this._start})}_error(t){let e=this._start,n=this._input.substring(this._start,this._current),r={type:19,offset:this._start,lexeme:n};this._errors.push({offset:e,lexeme:n,additionalInfo:t}),this._tokens.push(r)}_string(){this.stringRe.lastIndex=this._start;let t=this.stringRe.exec(this._input);if(t){this._current=this._start+t[0].length;let e=this._input.substring(this._start,this._current),n=i._keywords.get(e);n?this._addToken(n):this._tokens.push({type:17,lexeme:e,offset:this._start})}}_quotedString(){for(;this._peek()!==39&&!this._isAtEnd();)this._advance();if(this._isAtEnd()){this._error(dv);return}this._advance(),this._tokens.push({type:18,lexeme:this._input.substring(this._start+1,this._current-1),offset:this._start+1})}_regex(){let t=this._current,e=!1,n=!1;for(;;){if(t>=this._input.length){this._current=t,this._error(uv);return}let o=this._input.charCodeAt(t);if(e)e=!1;else if(o===47&&!n){t++;break}else o===91?n=!0:o===92?e=!0:o===93&&(n=!1);t++}for(;t<this._input.length&&i._regexFlags.has(this._input.charCodeAt(t));)t++;this._current=t;let r=this._input.substring(this._start,this._current);this._tokens.push({type:10,lexeme:r,offset:this._start})}_isAtEnd(){return this._current>=this._input.length}};var Re=new Map;Re.set("false",!1);Re.set("true",!0);Re.set("isMac",Je);Re.set("isLinux",ve);Re.set("isWindows",B);Re.set("isWeb",In);Re.set("isMacNative",Je&&!In);Re.set("isEdge",Id);Re.set("isFirefox",bd);Re.set("isChrome",Oa);Re.set("isSafari",yd);var fv=Object.prototype.hasOwnProperty;var gv={regexParsingWithErrorRecovery:!0},mv=g(1901,null),hv=g(1902,null),vv=g(1904,null),kp=g(1900,null),bv=g(1907,null),yv=g(1908,null),Iv=g(1905,null),Sv=g(1906,null),Jl=class i{constructor(t=gv){this._config=t;this._scanner=new dn;this._tokens=[];this._current=0;this._parsingErrors=[];this._flagsGYRe=/g|y/g}static{this._parseError=new Error}get lexingErrors(){return this._scanner.errors}get parsingErrors(){return this._parsingErrors}parse(t){if(t===""){this._parsingErrors.push({message:mv,offset:0,lexeme:"",additionalInfo:hv});return}this._tokens=this._scanner.reset(t).scan(),this._current=0,this._parsingErrors=[];try{let e=this._expr();if(!this._isAtEnd()){let n=this._peek(),r=n.type===17?yv:void 0;throw this._parsingErrors.push({message:bv,offset:n.offset,lexeme:dn.getLexeme(n),additionalInfo:r}),i._parseError}return e}catch(e){if(e!==i._parseError)throw e;return}}_expr(){return this._or()}_or(){let t=[this._and()];for(;this._matchOne(16);){let e=this._and();t.push(e)}return t.length===1?t[0]:Le.or(...t)}_and(){let t=[this._term()];for(;this._matchOne(15);){let e=this._term();t.push(e)}return t.length===1?t[0]:Le.and(...t)}_term(){if(this._matchOne(2)){let t=this._peek();switch(t.type){case 11:return this._advance(),$e.INSTANCE;case 12:return this._advance(),je.INSTANCE;case 0:{this._advance();let e=this._expr();return this._consume(1,kp),e?.negate()}case 17:return this._advance(),Mn.create(t.lexeme);default:throw this._errExpectedButGot("KEY | true | false | '(' expression ')'",t)}}return this._primary()}_primary(){let t=this._peek();switch(t.type){case 11:return this._advance(),Le.true();case 12:return this._advance(),Le.false();case 0:{this._advance();let e=this._expr();return this._consume(1,kp),e}case 17:{let e=t.lexeme;if(this._advance(),this._matchOne(9)){let r=this._peek();if(!this._config.regexParsingWithErrorRecovery){if(this._advance(),r.type!==10)throw this._errExpectedButGot("REGEX",r);let o=r.lexeme,s=o.lastIndexOf("/"),a=s===o.length-1?void 0:this._removeFlagsGY(o.substring(s+1)),l;try{l=new RegExp(o.substring(1,s),a)}catch{throw this._errExpectedButGot("REGEX",r)}return Oi.create(e,l)}switch(r.type){case 10:case 19:{let o=[r.lexeme];this._advance();let s=this._peek(),a=0;for(let f=0;f<r.lexeme.length;f++)r.lexeme.charCodeAt(f)===40?a++:r.lexeme.charCodeAt(f)===41&&a--;for(;!this._isAtEnd()&&s.type!==15&&s.type!==16;){switch(s.type){case 0:a++;break;case 1:a--;break;case 10:case 18:for(let f=0;f<s.lexeme.length;f++)s.lexeme.charCodeAt(f)===40?a++:r.lexeme.charCodeAt(f)===41&&a--}if(a<0)break;o.push(dn.getLexeme(s)),this._advance(),s=this._peek()}let l=o.join(""),c=l.lastIndexOf("/"),p=c===l.length-1?void 0:this._removeFlagsGY(l.substring(c+1)),u;try{u=new RegExp(l.substring(1,c),p)}catch{throw this._errExpectedButGot("REGEX",r)}return Le.regex(e,u)}case 18:{let o=r.lexeme;this._advance();let s=null;if(!Ld(o)){let a=o.indexOf("/"),l=o.lastIndexOf("/");if(a!==l&&a>=0){let c=o.slice(a+1,l),p=o[l+1]==="i"?"i":"";try{s=new RegExp(c,p)}catch{throw this._errExpectedButGot("REGEX",r)}}}if(s===null)throw this._errExpectedButGot("REGEX",r);return Oi.create(e,s)}default:throw this._errExpectedButGot("REGEX",this._peek())}}if(this._matchOne(14)){this._consume(13,vv);let r=this._value();return Le.notIn(e,r)}switch(this._peek().type){case 3:{this._advance();let r=this._value();if(this._previous().type===18)return Le.equals(e,r);switch(r){case"true":return Le.has(e);case"false":return Le.not(e);default:return Le.equals(e,r)}}case 4:{this._advance();let r=this._value();if(this._previous().type===18)return Le.notEquals(e,r);switch(r){case"true":return Le.not(e);case"false":return Le.has(e);default:return Le.notEquals(e,r)}}case 5:return this._advance(),ki.create(e,this._value());case 6:return this._advance(),Di.create(e,this._value());case 7:return this._advance(),Cr.create(e,this._value());case 8:return this._advance(),Ai.create(e,this._value());case 13:return this._advance(),Le.in(e,this._value());default:return Le.has(e)}}case 20:throw this._parsingErrors.push({message:Iv,offset:t.offset,lexeme:"",additionalInfo:Sv}),i._parseError;default:throw this._errExpectedButGot(`true | false | KEY 
	| KEY '=~' REGEX 
	| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`,this._peek())}}_value(){let t=this._peek();switch(t.type){case 17:case 18:return this._advance(),t.lexeme;case 11:return this._advance(),"true";case 12:return this._advance(),"false";case 13:return this._advance(),"in";default:return""}}_removeFlagsGY(t){return t.replaceAll(this._flagsGYRe,"")}_previous(){return this._tokens[this._current-1]}_matchOne(t){return this._check(t)?(this._advance(),!0):!1}_advance(){return this._isAtEnd()||this._current++,this._previous()}_consume(t,e){if(this._check(t))return this._advance();throw this._errExpectedButGot(e,this._peek())}_errExpectedButGot(t,e,n){let r=g(1903,null,t,dn.getLexeme(e)),o=e.offset,s=dn.getLexeme(e);return this._parsingErrors.push({message:r,offset:o,lexeme:s,additionalInfo:n}),i._parseError}_check(t){return this._peek().type===t}_peek(){return this._tokens[this._current]}_isAtEnd(){return this._peek().type===20}},Le=class{static false(){return $e.INSTANCE}static true(){return je.INSTANCE}static has(t){return Nn.create(t)}static equals(t,e){return wi.create(t,e)}static notEquals(t,e){return Pi.create(t,e)}static regex(t,e){return Oi.create(t,e)}static in(t,e){return us.create(t,e)}static notIn(t,e){return ps.create(t,e)}static not(t){return Mn.create(t)}static and(...t){return fs.create(t,null,!0)}static or(...t){return Li.create(t,null,!0)}static greater(t,e){return Cr.create(t,e)}static greaterEquals(t,e){return Ai.create(t,e)}static smaller(t,e){return ki.create(t,e)}static smallerEquals(t,e){return Di.create(t,e)}static{this._parser=new Jl({regexParsingWithErrorRecovery:!1})}static deserialize(t){return t==null?void 0:this._parser.parse(t)}};function Ri(i,t){return i.cmp(t)}var $e=class i{constructor(){this.type=0}static{this.INSTANCE=new i}cmp(t){return this.type-t.type}equals(t){return t.type===this.type}substituteConstants(){return this}evaluate(t){return!1}serialize(){return"false"}keys(){return[]}map(t){return this}negate(){return je.INSTANCE}},je=class i{constructor(){this.type=1}static{this.INSTANCE=new i}cmp(t){return this.type-t.type}equals(t){return t.type===this.type}substituteConstants(){return this}evaluate(t){return!0}serialize(){return"true"}keys(){return[]}map(t){return this}negate(){return $e.INSTANCE}},Nn=class i{constructor(t,e){this.key=t;this.negated=e;this.type=2}static create(t,e=null){let n=Re.get(t);return typeof n=="boolean"?n?je.INSTANCE:$e.INSTANCE:new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:Lp(this.key,t.key)}equals(t){return t.type===this.type?this.key===t.key:!1}substituteConstants(){let t=Re.get(this.key);return typeof t=="boolean"?t?je.INSTANCE:$e.INSTANCE:this}evaluate(t){return!!t.getValue(this.key)}serialize(){return this.key}keys(){return[this.key]}map(t){return t.mapDefined(this.key)}negate(){return this.negated||(this.negated=Mn.create(this.key,this)),this.negated}},wi=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=4}static create(t,e,n=null){if(typeof e=="boolean")return e?Nn.create(t,n):Mn.create(t,n);let r=Re.get(t);return typeof r=="boolean"?e===(r?"true":"false")?je.INSTANCE:$e.INSTANCE:new i(t,e,n)}cmp(t){return t.type!==this.type?this.type-t.type:Wn(this.key,this.value,t.key,t.value)}equals(t){return t.type===this.type?this.key===t.key&&this.value===t.value:!1}substituteConstants(){let t=Re.get(this.key);if(typeof t=="boolean"){let e=t?"true":"false";return this.value===e?je.INSTANCE:$e.INSTANCE}return this}evaluate(t){return t.getValue(this.key)==this.value}serialize(){return`${this.key} == '${this.value}'`}keys(){return[this.key]}map(t){return t.mapEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Pi.create(this.key,this.value,this)),this.negated}},us=class i{constructor(t,e){this.key=t;this.valueKey=e;this.type=10;this.negated=null}static create(t,e){return new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:Wn(this.key,this.valueKey,t.key,t.valueKey)}equals(t){return t.type===this.type?this.key===t.key&&this.valueKey===t.valueKey:!1}substituteConstants(){return this}evaluate(t){let e=t.getValue(this.valueKey),n=t.getValue(this.key);if(Array.isArray(e)){if(e.includes(n))return!0;if(B&&typeof n=="string"&&n.startsWith("file:///")){let r=n.toLowerCase();return e.some(o=>typeof o=="string"&&o.toLowerCase()===r)}return!1}if(typeof n=="string"&&typeof e=="object"&&e!==null){if(fv.call(e,n))return!0;if(B&&n.startsWith("file:///")){let r=n.toLowerCase();return Object.keys(e).some(o=>o.toLowerCase()===r)}return!1}return!1}serialize(){return`${this.key} in '${this.valueKey}'`}keys(){return[this.key,this.valueKey]}map(t){return t.mapIn(this.key,this.valueKey)}negate(){return this.negated||(this.negated=ps.create(this.key,this.valueKey)),this.negated}},ps=class i{constructor(t,e){this.key=t;this.valueKey=e;this.type=11;this._negated=us.create(t,e)}static create(t,e){return new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:this._negated.cmp(t._negated)}equals(t){return t.type===this.type?this._negated.equals(t._negated):!1}substituteConstants(){return this}evaluate(t){return!this._negated.evaluate(t)}serialize(){return`${this.key} not in '${this.valueKey}'`}keys(){return this._negated.keys()}map(t){return t.mapNotIn(this.key,this.valueKey)}negate(){return this._negated}},Pi=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=5}static create(t,e,n=null){if(typeof e=="boolean")return e?Mn.create(t,n):Nn.create(t,n);let r=Re.get(t);return typeof r=="boolean"?e===(r?"true":"false")?$e.INSTANCE:je.INSTANCE:new i(t,e,n)}cmp(t){return t.type!==this.type?this.type-t.type:Wn(this.key,this.value,t.key,t.value)}equals(t){return t.type===this.type?this.key===t.key&&this.value===t.value:!1}substituteConstants(){let t=Re.get(this.key);if(typeof t=="boolean"){let e=t?"true":"false";return this.value===e?$e.INSTANCE:je.INSTANCE}return this}evaluate(t){return t.getValue(this.key)!=this.value}serialize(){return`${this.key} != '${this.value}'`}keys(){return[this.key]}map(t){return t.mapNotEquals(this.key,this.value)}negate(){return this.negated||(this.negated=wi.create(this.key,this.value,this)),this.negated}},Mn=class i{constructor(t,e){this.key=t;this.negated=e;this.type=3}static create(t,e=null){let n=Re.get(t);return typeof n=="boolean"?n?$e.INSTANCE:je.INSTANCE:new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:Lp(this.key,t.key)}equals(t){return t.type===this.type?this.key===t.key:!1}substituteConstants(){let t=Re.get(this.key);return typeof t=="boolean"?t?$e.INSTANCE:je.INSTANCE:this}evaluate(t){return!t.getValue(this.key)}serialize(){return`!${this.key}`}keys(){return[this.key]}map(t){return t.mapNot(this.key)}negate(){return this.negated||(this.negated=Nn.create(this.key,this)),this.negated}};function ms(i,t){if(typeof i=="string"){let e=parseFloat(i);isNaN(e)||(i=e)}return typeof i=="string"||typeof i=="number"?t(i):$e.INSTANCE}var Cr=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=12}static create(t,e,n=null){return ms(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Wn(this.key,this.value,t.key,t.value)}equals(t){return t.type===this.type?this.key===t.key&&this.value===t.value:!1}substituteConstants(){return this}evaluate(t){return typeof this.value=="string"?!1:parseFloat(t.getValue(this.key))>this.value}serialize(){return`${this.key} > ${this.value}`}keys(){return[this.key]}map(t){return t.mapGreater(this.key,this.value)}negate(){return this.negated||(this.negated=Di.create(this.key,this.value,this)),this.negated}},Ai=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=13}static create(t,e,n=null){return ms(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Wn(this.key,this.value,t.key,t.value)}equals(t){return t.type===this.type?this.key===t.key&&this.value===t.value:!1}substituteConstants(){return this}evaluate(t){return typeof this.value=="string"?!1:parseFloat(t.getValue(this.key))>=this.value}serialize(){return`${this.key} >= ${this.value}`}keys(){return[this.key]}map(t){return t.mapGreaterEquals(this.key,this.value)}negate(){return this.negated||(this.negated=ki.create(this.key,this.value,this)),this.negated}},ki=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=14}static create(t,e,n=null){return ms(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Wn(this.key,this.value,t.key,t.value)}equals(t){return t.type===this.type?this.key===t.key&&this.value===t.value:!1}substituteConstants(){return this}evaluate(t){return typeof this.value=="string"?!1:parseFloat(t.getValue(this.key))<this.value}serialize(){return`${this.key} < ${this.value}`}keys(){return[this.key]}map(t){return t.mapSmaller(this.key,this.value)}negate(){return this.negated||(this.negated=Ai.create(this.key,this.value,this)),this.negated}},Di=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=15}static create(t,e,n=null){return ms(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Wn(this.key,this.value,t.key,t.value)}equals(t){return t.type===this.type?this.key===t.key&&this.value===t.value:!1}substituteConstants(){return this}evaluate(t){return typeof this.value=="string"?!1:parseFloat(t.getValue(this.key))<=this.value}serialize(){return`${this.key} <= ${this.value}`}keys(){return[this.key]}map(t){return t.mapSmallerEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Cr.create(this.key,this.value,this)),this.negated}},Oi=class i{constructor(t,e){this.key=t;this.regexp=e;this.type=7;this.negated=null}static create(t,e){return new i(t,e)}cmp(t){if(t.type!==this.type)return this.type-t.type;if(this.key<t.key)return-1;if(this.key>t.key)return 1;let e=this.regexp?this.regexp.source:"",n=t.regexp?t.regexp.source:"";return e<n?-1:e>n?1:0}equals(t){if(t.type===this.type){let e=this.regexp?this.regexp.source:"",n=t.regexp?t.regexp.source:"";return this.key===t.key&&e===n}return!1}substituteConstants(){return this}evaluate(t){let e=t.getValue(this.key);return this.regexp?this.regexp.test(e):!1}serialize(){let t=this.regexp?`/${this.regexp.source}/${this.regexp.flags}`:"/invalid/";return`${this.key} =~ ${t}`}keys(){return[this.key]}map(t){return t.mapRegex(this.key,this.regexp)}negate(){return this.negated||(this.negated=Ql.create(this)),this.negated}},Ql=class i{constructor(t){this._actual=t;this.type=8}static create(t){return new i(t)}cmp(t){return t.type!==this.type?this.type-t.type:this._actual.cmp(t._actual)}equals(t){return t.type===this.type?this._actual.equals(t._actual):!1}substituteConstants(){return this}evaluate(t){return!this._actual.evaluate(t)}serialize(){return`!(${this._actual.serialize()})`}keys(){return this._actual.keys()}map(t){return new i(this._actual.map(t))}negate(){return this._actual}};function Op(i){let t=null;for(let e=0,n=i.length;e<n;e++){let r=i[e].substituteConstants();if(i[e]!==r&&t===null){t=[];for(let o=0;o<e;o++)t[o]=i[o]}t!==null&&(t[e]=r)}return t===null?i:t}var fs=class i{constructor(t,e){this.expr=t;this.negated=e;this.type=6}static create(t,e,n){return i._normalizeArr(t,e,n)}cmp(t){if(t.type!==this.type)return this.type-t.type;if(this.expr.length<t.expr.length)return-1;if(this.expr.length>t.expr.length)return 1;for(let e=0,n=this.expr.length;e<n;e++){let r=Ri(this.expr[e],t.expr[e]);if(r!==0)return r}return 0}equals(t){if(t.type===this.type){if(this.expr.length!==t.expr.length)return!1;for(let e=0,n=this.expr.length;e<n;e++)if(!this.expr[e].equals(t.expr[e]))return!1;return!0}return!1}substituteConstants(){let t=Op(this.expr);return t===this.expr?this:i.create(t,this.negated,!1)}evaluate(t){for(let e=0,n=this.expr.length;e<n;e++)if(!this.expr[e].evaluate(t))return!1;return!0}static _normalizeArr(t,e,n){let r=[],o=!1;for(let s of t)if(s){if(s.type===1){o=!0;continue}if(s.type===0)return $e.INSTANCE;if(s.type===6){r.push(...s.expr);continue}r.push(s)}if(r.length===0&&o)return je.INSTANCE;if(r.length!==0){if(r.length===1)return r[0];r.sort(Ri);for(let s=1;s<r.length;s++)r[s-1].equals(r[s])&&(r.splice(s,1),s--);if(r.length===1)return r[0];for(;r.length>1;){let s=r[r.length-1];if(s.type!==9)break;r.pop();let a=r.pop(),l=r.length===0,c=Li.create(s.expr.map(p=>i.create([p,a],null,n)),null,l);c&&(r.push(c),r.sort(Ri))}if(r.length===1)return r[0];if(n){for(let s=0;s<r.length;s++)for(let a=s+1;a<r.length;a++)if(r[s].negate().equals(r[a]))return $e.INSTANCE;if(r.length===1)return r[0]}return new i(r,e)}}serialize(){return this.expr.map(t=>t.serialize()).join(" && ")}keys(){let t=[];for(let e of this.expr)t.push(...e.keys());return t}map(t){return new i(this.expr.map(e=>e.map(t)),null)}negate(){if(!this.negated){let t=[];for(let e of this.expr)t.push(e.negate());this.negated=Li.create(t,this,!0)}return this.negated}},Li=class i{constructor(t,e){this.expr=t;this.negated=e;this.type=9}static create(t,e,n){return i._normalizeArr(t,e,n)}cmp(t){if(t.type!==this.type)return this.type-t.type;if(this.expr.length<t.expr.length)return-1;if(this.expr.length>t.expr.length)return 1;for(let e=0,n=this.expr.length;e<n;e++){let r=Ri(this.expr[e],t.expr[e]);if(r!==0)return r}return 0}equals(t){if(t.type===this.type){if(this.expr.length!==t.expr.length)return!1;for(let e=0,n=this.expr.length;e<n;e++)if(!this.expr[e].equals(t.expr[e]))return!1;return!0}return!1}substituteConstants(){let t=Op(this.expr);return t===this.expr?this:i.create(t,this.negated,!1)}evaluate(t){for(let e=0,n=this.expr.length;e<n;e++)if(this.expr[e].evaluate(t))return!0;return!1}static _normalizeArr(t,e,n){let r=[],o=!1;if(t){for(let s=0,a=t.length;s<a;s++){let l=t[s];if(l){if(l.type===0){o=!0;continue}if(l.type===1)return je.INSTANCE;if(l.type===9){r=r.concat(l.expr);continue}r.push(l)}}if(r.length===0&&o)return $e.INSTANCE;r.sort(Ri)}if(r.length!==0){if(r.length===1)return r[0];for(let s=1;s<r.length;s++)r[s-1].equals(r[s])&&(r.splice(s,1),s--);if(r.length===1)return r[0];if(n){for(let s=0;s<r.length;s++)for(let a=s+1;a<r.length;a++)if(r[s].negate().equals(r[a]))return je.INSTANCE;if(r.length===1)return r[0]}return new i(r,e)}}serialize(){return this.expr.map(t=>t.serialize()).join(" || ")}keys(){let t=[];for(let e of this.expr)t.push(...e.keys());return t}map(t){return new i(this.expr.map(e=>e.map(t)),null)}negate(){if(!this.negated){let t=[];for(let e of this.expr)t.push(e.negate());for(;t.length>1;){let e=t.shift(),n=t.shift(),r=[];for(let o of Dp(e))for(let s of Dp(n))r.push(fs.create([o,s],null,!1));t.unshift(i.create(r,null,!1))}this.negated=i.create(t,this,!0)}return this.negated}},gs=class i extends Nn{static{this._info=[]}static all(){return i._info.values()}constructor(t,e,n){super(t,null),this._defaultValue=e,typeof n=="object"?i._info.push({...n,key:t}):n!==!0&&i._info.push({key:t,description:n,type:e!=null?typeof e:void 0})}bindTo(t){return t.createKey(this.key,this._defaultValue)}getValue(t){return t.getContextKeyValue(this.key)}toNegated(){return this.negate()}isEqualTo(t){return wi.create(this.key,t)}notEqualsTo(t){return Pi.create(this.key,t)}greater(t){return Cr.create(this.key,t)}},EC=re("contextKeyService");function Lp(i,t){return i<t?-1:i>t?1:0}function Wn(i,t,e,n){return i<e?-1:i>e?1:t<n?-1:t>n?1:0}function Dp(i){return i.type===9?i.expr:[i]}var ue=re("logService"),$C=re("loggerService");function Yl(i){return Yr(i)}var Fp=3;function Tv(i,t){return i!==0&&i<=t}function Rr(i,t=!1){let e="";for(let n=0;n<i.length;n++){let r=i[n];if(r instanceof Error&&(r=kn(r,t)),typeof r=="object")try{r=JSON.stringify(r)}catch{}e+=(n>0?" ":"")+r}return e}var hs=class extends L{constructor(){super(...arguments);this.level=Fp;this._onDidChangeLogLevel=this._register(new x)}get onDidChangeLogLevel(){return this._onDidChangeLogLevel.event}setLevel(e){this.level!==e&&(this.level=e,this._onDidChangeLogLevel.fire(this.level))}getLevel(){return this.level}checkLogLevel(e){return Tv(this.level,e)}canLog(e){return this._store.isDisposed?!1:this.checkLogLevel(e)}},Fi=class extends hs{constructor(e){super();this.logAlways=e}checkLogLevel(e){return this.logAlways||super.checkLogLevel(e)}trace(e,...n){this.canLog(1)&&this.log(1,Rr([e,...n],!0))}debug(e,...n){this.canLog(2)&&this.log(2,Rr([e,...n]))}info(e,...n){this.canLog(3)&&this.log(3,Rr([e,...n]))}warn(e,...n){this.canLog(4)&&this.log(4,Rr([e,...n]))}error(e,...n){if(this.canLog(5))if(e instanceof Error){let r=Array.prototype.slice.call(arguments);r[0]=e.stack,this.log(5,Rr(r))}else this.log(5,Rr([e,...n]))}flush(){}};var vs=class extends hs{constructor(e){super();this.loggers=e;e.length&&this.setLevel(e[0].getLevel())}setLevel(e){for(let n of this.loggers)n.setLevel(e);super.setLevel(e)}trace(e,...n){for(let r of this.loggers)r.trace(e,...n)}debug(e,...n){for(let r of this.loggers)r.debug(e,...n)}info(e,...n){for(let r of this.loggers)r.info(e,...n)}warn(e,...n){for(let r of this.loggers)r.warn(e,...n)}error(e,...n){for(let r of this.loggers)r.error(e,...n)}flush(){for(let e of this.loggers)e.flush()}dispose(){for(let e of this.loggers)e.dispose();super.dispose()}},Ui=class extends L{constructor(e,n,r){super();this.logLevel=e;this.logsHome=n;this._loggers=new ut;this._onDidChangeLoggers=this._register(new x);this.onDidChangeLoggers=this._onDidChangeLoggers.event;this._onDidChangeLogLevel=this._register(new x);this.onDidChangeLogLevel=this._onDidChangeLogLevel.event;this._onDidChangeVisibility=this._register(new x);this.onDidChangeVisibility=this._onDidChangeVisibility.event;if(r)for(let o of r)this._loggers.set(o.resource,{logger:void 0,info:o})}getLoggerEntry(e){return Me(e)?[...this._loggers.values()].find(n=>n.info.id===e):this._loggers.get(e)}getLogger(e){return this.getLoggerEntry(e)?.logger}createLogger(e,n){let r=this.toResource(e),o=Me(e)?e:n?.id??Er(r.toString()).toString(16),s=this._loggers.get(r)?.logger,a=n?.logLevel==="always"?1:n?.logLevel;s||(s=this.doCreateLogger(r,a??this.getLogLevel(r)??this.logLevel,{...n,id:o}));let l={logger:s,info:{resource:r,id:o,logLevel:a,name:n?.name,hidden:n?.hidden,group:n?.group,extensionId:n?.extensionId,when:n?.when}};return this.registerLogger(l.info),this._loggers.set(r,l),s}toResource(e){return Me(e)?te(this.logsHome,`${e.replace(/[\\/:\*\?"<>\|]/g,"")}.log`):e}setLogLevel(e,n){if(b.isUri(e)){let r=e,o=n,s=this._loggers.get(r);s&&o!==s.info.logLevel&&(s.info.logLevel=o===this.logLevel?void 0:o,s.logger?.setLevel(o),this._loggers.set(s.info.resource,s),this._onDidChangeLogLevel.fire([r,o]))}else{this.logLevel=e;for(let[r,o]of this._loggers.entries())this._loggers.get(r)?.info.logLevel===void 0&&o.logger?.setLevel(this.logLevel);this._onDidChangeLogLevel.fire(this.logLevel)}}setVisibility(e,n){let r=this.getLoggerEntry(e);r&&n!==!r.info.hidden&&(r.info.hidden=!n,this._loggers.set(r.info.resource,r),this._onDidChangeVisibility.fire([r.info.resource,n]))}getLogLevel(e){let n;return e&&(n=this._loggers.get(e)?.info.logLevel),n??this.logLevel}registerLogger(e){let n=this._loggers.get(e.resource);n?n.info.hidden!==e.hidden&&this.setVisibility(e.resource,!e.hidden):(this._loggers.set(e.resource,{info:e,logger:void 0}),this._onDidChangeLoggers.fire({added:[e],removed:[]}))}deregisterLogger(e){let n=this.toResource(e),r=this._loggers.get(n);r&&(r.logger&&r.logger.dispose(),this._loggers.delete(n),this._onDidChangeLoggers.fire({added:[],removed:[r.info]}))}*getRegisteredLoggers(){for(let e of this._loggers.values())yield e.info}getRegisteredLogger(e){return this._loggers.get(e)?.info}dispose(){this._loggers.forEach(e=>e.logger?.dispose()),this._loggers.clear(),super.dispose()}};function Up(i){if(i.verbose)return 1;if(typeof i.logLevel=="string"){let t=_v(i.logLevel.toLowerCase());if(t!==void 0)return t}return Fp}function xv(i){switch(i){case 1:return"trace";case 2:return"debug";case 3:return"info";case 4:return"warn";case 5:return"error";case 0:return"off"}}function _v(i){switch(i){case"trace":return 1;case"debug":return 2;case"info":return 3;case"warn":return 4;case"error":return 5;case"critical":return 5;case"off":return 0}}var VC=new gs("logLevel",xv(3));var bs=re("diffComputeService"),Np=5e3;var un=class extends L{constructor(e){super();this._logService=e;this._workerFailures=0;this._nextId=1;this._pending=new Map}async computeDiffCounts(e,n,r=Np){let o=this._ensureWorker(),s=this._nextId++;return new Promise((a,l)=>{this._pending.set(s,{resolve:a,reject:l});try{o.postMessage({id:s,fn:"computeDiffCounts",args:[e,n,r]})}catch(c){this._pending.delete(s),l(c instanceof Error?c:new Error(String(c)))}})}_ensureWorker(){if(this._workerFailures>=3)throw new Error("Diff compute worker failed too many times");if(!this._worker){let e=Xe.asFileUri("vs/platform/agentHost/node/diffWorkerMain.js").fsPath,n=new Ev(e,{name:"Diff compute worker"});n.on("message",r=>{let o=this._pending.get(r.id);if(o)if(this._pending.delete(r.id),r.err){let s=new Error(r.err.message);r.err.stack&&(s.stack=r.err.stack),o.reject(s)}else o.resolve(r.res)}),n.on("error",r=>{this._logService.error("[DiffComputeService] Worker error",r);for(let[,o]of this._pending)o.reject(r);this._pending.clear(),this._worker=void 0,this._workerFailures++}),this._worker=n}return this._worker}dispose(){this._worker&&(this._worker.terminate(),this._worker=void 0);for(let[,e]of this._pending)e.reject(new Error("DiffComputeService disposed"));this._pending.clear(),super.dispose()}};un=O([K(0,ue)],un);var Mp="session-db";function pn(i,t,e,n){return b.from({scheme:Mp,authority:sn(_.fromString(i)).toString(),path:`/${encodeURIComponent(t)}/${sn(_.fromString(e))}/${n}`}).toString()}function Wp(i){let t=b.parse(i);if(t.scheme!==Mp)return;let[,e,n,r]=t.path.split("/");if(!(!e||!n||r!=="before"&&r!=="after"))try{return{sessionUri:dl(t.authority).toString(),toolCallId:decodeURIComponent(e),filePath:dl(n).toString(),part:r}}catch{return}}var wr=class{constructor(t,e,n,r,o){this._sessionUri=t;this._db=e;this._fileService=n;this._logService=r;this._diffComputeService=o;this._pendingEdits=new Map;this._completedEdits=new Map}async trackEditStart(t){let e=this._readFile(t),n={beforeContent:_.fromString(""),snapshotDone:e.then(r=>{n.beforeContent=r})};this._pendingEdits.set(t,n),await n.snapshotDone}async completeEdit(t){let e=this._pendingEdits.get(t);if(!e)return;this._pendingEdits.delete(t),await e.snapshotDone;let n=await this._readFile(t);this._completedEdits.set(t,{beforeContent:e.beforeContent,afterContent:n})}async takeCompletedEdit(t,e,n){let r=this._completedEdits.get(n);if(!r)return;this._completedEdits.delete(n);let o=r.beforeContent.buffer,s=r.afterContent.buffer,a=r.beforeContent.toString(),l=r.afterContent.toString(),c,p;try{let u=await this._diffComputeService.computeDiffCounts(a,l);c=u.added,p=u.removed}catch(u){this._logService.warn(`[FileEditTracker] Failed to compute diff counts: ${n}`,u)}try{await this._db.storeFileEdit({turnId:t,toolCallId:e,filePath:n,kind:"edit",beforeContent:o,afterContent:s,addedLines:c,removedLines:p})}catch(u){this._logService.warn(`[FileEditTracker] Failed to persist file edit to database: ${n}`,u)}return{type:"fileEdit",before:{uri:b.file(n).toString(),content:{uri:pn(this._sessionUri,e,n,"before")}},after:{uri:b.file(n).toString(),content:{uri:pn(this._sessionUri,e,n,"after")}},diff:c!==void 0?{added:c,removed:p}:void 0}}async _readFile(t){try{return(await this._fileService.readFile(b.file(t))).value}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${t}`,e),_.fromString("")}}};wr=O([K(2,tt),K(3,ue),K(4,bs)],wr);function Bp(i){return i.after?.uri??i.before?.uri}function Rv(i,t,e,n){let r=t.firstKind!=="create",o=t.lastKind!=="delete";return{...r?{before:{uri:b.file(t.firstFilePath).toString(),content:{uri:pn(i,t.firstToolCallId,t.firstFilePath,"before")}}}:{},...o?{after:{uri:b.file(t.terminalPath).toString(),content:{uri:pn(i,t.lastToolCallId,t.lastFilePath,"after")}}}:{},diff:{added:e,removed:n}}}async function $p(i,t,e,n){let r,o=!1;if(n){let f=await t.getFileEditsByTurn(n.changedTurnId);if(f.length===0)return[...n.previousDiffs];let m=new Set(n.previousDiffs.map(Bp));f.some(h=>h.kind==="rename"||m.has(b.file(h.filePath).toString()))?r=await t.getAllFileEdits():(r=f,o=!0)}else r=await t.getAllFileEdits();if(r.length===0)return[];let s=new Map,a=new Map,l=n&&!o?new Set:void 0;for(let f of r){let m;f.kind==="rename"&&f.originalPath?(m=s.get(f.originalPath)??f.originalPath,s.set(f.filePath,m),s.delete(f.originalPath)):(m=s.get(f.filePath)??f.filePath,s.set(f.filePath,m)),l&&f.turnId===n.changedTurnId&&l.add(m);let v=a.get(m);v?(v.terminalPath=f.filePath,v.lastToolCallId=f.toolCallId,v.lastFilePath=f.filePath,v.lastKind=f.kind):a.set(m,{terminalPath:f.filePath,firstToolCallId:f.toolCallId,firstFilePath:f.kind==="rename"&&f.originalPath?f.originalPath:f.filePath,firstKind:f.kind,lastToolCallId:f.toolCallId,lastFilePath:f.filePath,lastKind:f.kind})}let c=n&&!o?new Map(n.previousDiffs.map(f=>[Bp(f),f])):void 0,p=[],u=[];for(let[f,m]of a){if(l&&!l.has(f)){let v=b.file(m.terminalPath).toString(),h=c.get(v);h&&p.push(h);continue}u.push((async()=>{let v;if(m.firstKind==="create")v="";else{let y=await t.readFileEditContent(m.firstToolCallId,m.firstFilePath);v=y?.beforeContent?new TextDecoder().decode(y.beforeContent):""}let h;if(m.lastKind==="delete")h="";else{let y=await t.readFileEditContent(m.lastToolCallId,m.lastFilePath);h=y?.afterContent?new TextDecoder().decode(y.afterContent):""}if(v===h)return;let I=await e.computeDiffCounts(v,h);p.push(Rv(i,m,I.added,I.removed))})())}return await Promise.allSettled(u),o&&p.push(...n.previousDiffs),p}var ys=class i extends L{constructor(e,n,r){super();this._stateManager=e;this._options=n;this._logService=r;this._toolCallAgents=new Map;this._eventMappers=new Map;this._diffComputationSequencer=new St;this._lastAgentInfos=[];this._debouncedDiffTimers=this._register(new it);this._subagentSessions=new Map;this._pendingSubagentEvents=new Map;this._commandAutoApprover=this._register(new ds(this._logService)),this._diffComputeService=this._register(new un(this._logService)),this._register(xi(o=>{let s=this._options.agents.read(o);this._publishAgentInfos(s,o)}))}static{this._DIFF_DEBOUNCE_MS=5e3}_publishAgentInfos(e,n){let r=e.map(o=>{let s=o.getDescriptor(),a=o.getProtectedResources();return{provider:s.provider,displayName:s.displayName,description:s.description,models:o.models.read(n).map(l=>({id:l.id,provider:l.provider,name:l.name,maxContextWindow:l.maxContextWindow,supportsVision:l.supportsVision,policyState:l.policyState,configSchema:l.configSchema})),protectedResources:a.length>0?a:void 0}});An(this._lastAgentInfos,r)||(this._lastAgentInfos=r,this._stateManager.dispatchServerAction({type:"root/agentsChanged",agents:r}))}static{this._DEFAULT_EDIT_AUTO_APPROVE_PATTERNS={"**/*":!0,"**/.vscode/*.json":!1,"**/.git/**":!1,"**/{package.json,server.xml,build.rs,web.config,.gitattributes,.env}":!1,"**/*.{code-workspace,csproj,fsproj,vbproj,vcxproj,proj,targets,props}":!1,"**/*.lock":!1,"**/*-lock.{yaml,json}":!1}}_shouldAutoApproveEdit(e){let n=i._DEFAULT_EDIT_AUTO_APPROVE_PATTERNS,r=!0;for(let[o,s]of Object.entries(n))s!==r&&Ep(o,e)&&(r=s);return r}initialize(){return this._commandAutoApprover.initialize()}_tryAutoApproveToolReady(e,n,r){let o=this._stateManager.getSessionState(n),s=ss(n),a=s?this._stateManager.getSessionState(s.parentSession):void 0,l=o?.config?.values?.autoApprove??a?.config?.values?.autoApprove,c=o?.summary.workingDirectory??a?.summary.workingDirectory;if(l==="autoApprove"||l==="autopilot")return this._logService.trace(`[AgentSideEffects] Auto-approving tool call (session autoApprove=${l})`),this._toolCallAgents.delete(`${n}:${e.toolCallId}`),r.respondToPermissionRequest(e.toolCallId,!0),!0;if(e.permissionKind==="read"&&e.permissionPath){let p=c?b.parse(c):void 0;return p&&It.isEqualOrParent(Ft(b.file(e.permissionPath)),p)?(this._logService.trace(`[AgentSideEffects] Auto-approving read of ${e.permissionPath}`),this._toolCallAgents.delete(`${n}:${e.toolCallId}`),r.respondToPermissionRequest(e.toolCallId,!0),!0):!1}if(e.permissionKind==="write"&&e.permissionPath){let p=c?b.parse(c):void 0;return p&&It.isEqualOrParent(Ft(b.file(e.permissionPath)),p)&&this._shouldAutoApproveEdit(e.permissionPath)?(this._logService.trace(`[AgentSideEffects] Auto-approving write to ${e.permissionPath}`),this._toolCallAgents.delete(`${n}:${e.toolCallId}`),r.respondToPermissionRequest(e.toolCallId,!0),!0):!1}if(e.permissionKind==="shell"&&e.toolInput){let p=this._commandAutoApprover.shouldAutoApprove(e.toolInput);return p==="approved"?(this._logService.trace("[AgentSideEffects] Auto-approving shell command"),this._toolCallAgents.delete(`${n}:${e.toolCallId}`),r.respondToPermissionRequest(e.toolCallId,!0),!0):(p==="denied"&&this._logService.trace("[AgentSideEffects] Shell command denied by rule"),!1)}return!1}registerProgressListener(e){let n=new N,r=this._eventMappers.get(e.id);r||(r=new cs,this._eventMappers.set(e.id,r));let o=r;return n.add(e.onDidSessionProgress(s=>{this._handleAgentProgress(e,o,s)})),n}_handleAgentProgress(e,n,r){let o=r.session.toString();if(r.type==="tool_start"&&!this._getParentToolCallId(r)&&this._toolCallAgents.set(`${o}:${r.toolCallId}`,e.id),r.type==="subagent_started"){this._handleSubagentStarted(o,r.toolCallId,r.agentName,r.agentDisplayName,r.agentDescription),this._drainPendingSubagentEvents(o,r.toolCallId);return}let s=this._getParentToolCallId(r);if(s){let l=`${o}:${s}`,c=this._subagentSessions.get(l);if(c){r.type==="tool_start"&&this._toolCallAgents.set(`${c}:${r.toolCallId}`,e.id);let u=this._stateManager.getActiveTurnId(c);if(u){if(r.type==="tool_ready"&&this._tryAutoApproveToolReady(r,c,e))return;this._dispatchProgressActions(n,r,c,u)}return}this._logService.trace(`[AgentSideEffects] Buffering ${r.type} for pending subagent ${l}`);let p=this._pendingSubagentEvents.get(l);p||(p=[],this._pendingSubagentEvents.set(l,p)),p.push({event:r,agent:e,agentMapper:n});return}if(r.type==="tool_ready"){let l=this._findSubagentSessionForToolCall(o,r.toolCallId);if(l){let c=this._stateManager.getActiveTurnId(l);if(c){if(this._tryAutoApproveToolReady(r,l,e))return;this._dispatchProgressActions(n,r,l,c)}return}}let a=this._stateManager.getActiveTurnId(o);if(a){if(r.type==="tool_ready"&&this._tryAutoApproveToolReady(r,o,e))return;if(r.type==="tool_complete"){let l=`${o}:${r.toolCallId}`;if(this._subagentSessions.get(l)){let p=this._stateManager.getSessionState(o),f=this._getRunningToolCallContent(p,a,r.toolCallId).find(m=>We(m,{type:!0})&&m.type==="subagent");if(f){let m=[...r.result.content??[],f];r={...r,result:{...r.result,content:m}}}}}this._dispatchProgressActions(n,r,o,a),r.type==="tool_complete"&&(this.completeSubagentSession(o,r.toolCallId),mp(r.result).length>0&&this._scheduleDebouncedDiffComputation(o,a))}r.type==="idle"&&(this._cancelDebouncedDiffComputation(o),this._computeSessionDiffs(o,a),this._tryConsumeNextQueuedMessage(o)),r.type==="steering_consumed"&&this._stateManager.dispatchServerAction({type:"session/pendingMessageRemoved",session:o,kind:"steering",id:r.id})}_drainPendingSubagentEvents(e,n){let r=`${e}:${n}`,o=this._pendingSubagentEvents.get(r);if(o){this._pendingSubagentEvents.delete(r),this._logService.trace(`[AgentSideEffects] Draining ${o.length} buffered event(s) for subagent ${r}`);for(let{event:s,agent:a,agentMapper:l}of o)this._handleAgentProgress(a,l,s)}}_handleSubagentStarted(e,n,r,o,s){let a=Ei(e,n),l=`${e}:${n}`;if(this._subagentSessions.has(l))return;this._logService.info(`[AgentSideEffects] Creating subagent session: ${a} (parent=${e}, toolCallId=${n})`);let c=this._stateManager.getSessionState(e);this._stateManager.restoreSession({resource:a,provider:"subagent",title:o,status:1,createdAt:Date.now(),modifiedAt:Date.now(),...c?.summary.project?{project:c.summary.project}:{}},[]);let p=ne();this._stateManager.dispatchServerAction({type:"session/turnStarted",session:a,turnId:p,userMessage:{text:""}}),this._subagentSessions.set(l,a);let u=this._stateManager.getActiveTurnId(e);if(u){let f=this._stateManager.getSessionState(e),v=[...this._getRunningToolCallContent(f,u,n),{type:"subagent",resource:a,title:o,agentName:r,description:s}];this._stateManager.dispatchServerAction({type:"session/toolCallContentChanged",session:e,turnId:u,toolCallId:n,content:v})}}_getRunningToolCallContent(e,n,r){if(!e?.activeTurn||e.activeTurn.id!==n)return[];for(let o of e.activeTurn.responseParts)if(o.kind==="toolCall"&&o.toolCall.toolCallId===r&&o.toolCall.status==="running")return o.toolCall.content?[...o.toolCall.content]:[];return[]}cancelSubagentSessions(e){for(let[n,r]of this._subagentSessions)if(n.startsWith(`${e}:`)){let o=this._stateManager.getActiveTurnId(r);o&&this._stateManager.dispatchServerAction({type:"session/turnCancelled",session:r,turnId:o}),this._subagentSessions.delete(n)}for(let n of[...this._pendingSubagentEvents.keys()])n.startsWith(`${e}:`)&&this._pendingSubagentEvents.delete(n)}completeSubagentSession(e,n){let r=`${e}:${n}`;this._pendingSubagentEvents.delete(r);let o=this._subagentSessions.get(r);if(!o)return;let s=this._stateManager.getActiveTurnId(o);s&&this._stateManager.dispatchServerAction({type:"session/turnComplete",session:o,turnId:s}),this._subagentSessions.delete(r)}removeSubagentSessions(e){let n=[];for(let[o,s]of this._subagentSessions)o.startsWith(`${e}:`)&&(this._stateManager.removeSession(s),n.push(o));for(let o of n)this._subagentSessions.delete(o);let r=`${e}/subagent/`;for(let o of this._stateManager.getSessionUrisWithPrefix(r))this._stateManager.removeSession(o);for(let o of[...this._pendingSubagentEvents.keys()])o.startsWith(`${e}:`)&&this._pendingSubagentEvents.delete(o)}_getParentToolCallId(e){switch(e.type){case"delta":case"message":case"tool_start":case"tool_complete":return e.parentToolCallId;default:return}}_findSubagentSessionForToolCall(e,n){let r=`${e}:`;for(let[o,s]of this._subagentSessions)if(o.startsWith(r)&&this._toolCallAgents.has(`${s}:${n}`))return s}_dispatchProgressActions(e,n,r,o){let s=e.mapProgressEventToActions(n,r,o);if(s)if(Array.isArray(s))for(let a of s)this._stateManager.dispatchServerAction(a);else this._stateManager.dispatchServerAction(s)}handleAction(e){switch(e.type){case"session/turnStarted":{for(let a of this._eventMappers.values())a.reset(e.session);let n=this._stateManager.getSessionState(e.session),r=e.userMessage.text.trim().replace(/\s+/g," ").slice(0,200);n&&n.turns.length===0&&!n.summary.title&&r.length>0&&this._stateManager.dispatchServerAction({type:"session/titleChanged",session:e.session,title:r});let o=this._options.getAgent(e.session);if(!o){this._stateManager.dispatchServerAction({type:"session/error",session:e.session,turnId:e.turnId,error:{errorType:"noAgent",message:"No agent found for session"}});return}let s=e.userMessage.attachments?.map(a=>({type:a.type,path:a.path,displayName:a.displayName}));o.sendMessage(b.parse(e.session),e.userMessage.text,s,e.turnId).catch(a=>{this._logService.error("[AgentSideEffects] sendMessage failed",a),this._stateManager.dispatchServerAction({type:"session/error",session:e.session,turnId:e.turnId,error:{errorType:"sendFailed",message:String(a)}})});break}case"session/toolCallConfirmed":{let n=`${e.session}:${e.toolCallId}`,r=this._toolCallAgents.get(n);r?(this._toolCallAgents.delete(n),this._options.agents.get().find(s=>s.id===r)?.respondToPermissionRequest(e.toolCallId,e.approved)):this._logService.warn(`[AgentSideEffects] No agent for tool call confirmation: ${e.toolCallId}`);break}case"session/inputCompleted":{this._options.getAgent(e.session)?.respondToUserInputRequest(e.requestId,e.response,e.answers);break}case"session/turnCancelled":{this.cancelSubagentSessions(e.session),this._options.getAgent(e.session)?.abortSession(b.parse(e.session)).catch(r=>{this._logService.error("[AgentSideEffects] abortSession failed",r)});break}case"session/modelChanged":{this._options.getAgent(e.session)?.changeModel?.(b.parse(e.session),e.model).catch(r=>{this._logService.error("[AgentSideEffects] changeModel failed",r)});break}case"session/titleChanged":{this._persistTitle(e.session,e.title);break}case"session/pendingMessageSet":case"session/pendingMessageRemoved":case"session/queuedMessagesReordered":{this._syncPendingMessages(e.session);break}case"session/truncated":{this._options.getAgent(e.session)?.truncateSession?.(b.parse(e.session),e.turnId).catch(r=>{this._logService.error("[AgentSideEffects] truncateSession failed",r)}),this._computeSessionDiffs(e.session);break}case"session/activeClientChanged":{let n=this._options.getAgent(e.session);if(!n)break;let r=e.activeClient?.clientId??"";n.setClientTools(b.parse(e.session),r,e.activeClient?.tools??[]);let o=e.activeClient?.customizations;if(!o?.length)break;let s=o.map(a=>({customization:a,enabled:!0,status:"loading"}));this._stateManager.dispatchServerAction({type:"session/customizationsChanged",session:e.session,customizations:s}),n.setClientCustomizations(e.activeClient.clientId,o,a=>{let l=a.map(c=>c.customization);this._stateManager.dispatchServerAction({type:"session/customizationsChanged",session:e.session,customizations:l})}).then(a=>{let l=a.map(c=>c.customization);this._stateManager.dispatchServerAction({type:"session/customizationsChanged",session:e.session,customizations:l})}).catch(a=>{this._logService.error("[AgentSideEffects] setClientCustomizations failed",a)});break}case"session/activeClientToolsChanged":{let n=this._options.getAgent(e.session);if(n){let o=this._stateManager.getSessionState(e.session)?.activeClient?.clientId;o&&n.setClientTools(b.parse(e.session),o,e.tools)}break}case"session/customizationToggled":{this._options.getAgent(e.session)?.setCustomizationEnabled?.(e.uri,e.enabled);break}case"session/isReadChanged":{this._persistSessionFlag(e.session,"isRead",e.isRead?"true":"");break}case"session/isDoneChanged":{this._persistSessionFlag(e.session,"isDone",e.isDone?"true":"");break}case"session/configChanged":{let r=this._stateManager.getSessionState(e.session)?.config?.values;r&&this._persistSessionFlag(e.session,"configValues",JSON.stringify(r));break}case"session/toolCallComplete":{this._options.getAgent(e.session)?.onClientToolCallComplete(b.parse(e.session),e.toolCallId,e.result);break}}}_persistTitle(e,n){let r=this._options.sessionDataService.openDatabase(b.parse(e));r.object.setMetadata("customTitle",n).catch(o=>{this._logService.warn("[AgentSideEffects] Failed to persist session title",o)}).finally(()=>{r.dispose()})}_persistSessionFlag(e,n,r){let o=this._options.sessionDataService.openDatabase(b.parse(e));o.object.setMetadata(n,r).catch(s=>{this._logService.warn(`[AgentSideEffects] Failed to persist ${n}`,s)}).finally(()=>{o.dispose()})}_syncPendingMessages(e){let n=this._stateManager.getSessionState(e);if(!n)return;this._options.getAgent(e)?.setPendingMessages?.(b.parse(e),n.steeringMessage,[]),this._tryConsumeNextQueuedMessage(e)}_tryConsumeNextQueuedMessage(e){if(this._stateManager.getActiveTurnId(e))return;let n=this._stateManager.getSessionState(e);if(!n?.queuedMessages?.length)return;let r=n.queuedMessages[0],o=ne();for(let l of this._eventMappers.values())l.reset(e);this._stateManager.dispatchServerAction({type:"session/turnStarted",session:e,turnId:o,userMessage:r.userMessage,queuedMessageId:r.id});let s=this._options.getAgent(e);if(!s){this._stateManager.dispatchServerAction({type:"session/error",session:e,turnId:o,error:{errorType:"noAgent",message:"No agent found for session"}});return}let a=r.userMessage.attachments?.map(l=>({type:l.type,path:l.path,displayName:l.displayName}));s.sendMessage(b.parse(e),r.userMessage.text,a,o).catch(l=>{this._logService.error("[AgentSideEffects] sendMessage failed (queued)",l),this._stateManager.dispatchServerAction({type:"session/error",session:e,turnId:o,error:{errorType:"sendFailed",message:String(l)}})})}_scheduleDebouncedDiffComputation(e,n){this._debouncedDiffTimers.set(e,ou(()=>{this._debouncedDiffTimers.deleteAndDispose(e),this._computeSessionDiffs(e,n)},i._DIFF_DEBOUNCE_MS))}_cancelDebouncedDiffComputation(e){this._debouncedDiffTimers.deleteAndDispose(e)}_computeSessionDiffs(e,n){this._diffComputationSequencer.queue(e,()=>this._doComputeSessionDiffs(e,n))}async _doComputeSessionDiffs(e,n){let r;try{r=this._options.sessionDataService.openDatabase(b.parse(e))}catch(o){this._logService.warn(`[AgentSideEffects] Failed to open session database for diff computation: ${e}`,o);return}try{let o;if(n){let a=this._stateManager.getSessionState(e)?.summary.diffs;a&&(o={changedTurnId:n,previousDiffs:a})}let s=await $p(e,r.object,this._diffComputeService,o);this._stateManager.dispatchServerAction({type:"session/diffsChanged",session:e,diffs:s}),r.object.setMetadata("diffs",JSON.stringify(s)).catch(a=>{this._logService.warn("[AgentSideEffects] Failed to persist session diffs",a)})}catch(o){this._logService.warn("[AgentSideEffects] Failed to compute session diffs",o)}finally{r.dispose()}}dispose(){this._toolCallAgents.clear(),super.dispose()}};import*as Rs from"fs";var Vp=re("productService");import*as Pr from"os";var Xl=class{constructor(){this.data=new Map}add(t,e){io(Me(t)),io(so(e)),io(!this.data.has(t),"There is already an extension with this id"),this.data.set(t,e)}knows(t){return this.data.has(t)}as(t){return this.data.get(t)||null}dispose(){this.data.forEach(t=>{Zr(t.dispose)&&t.dispose()}),this.data.clear()}},qp=new Xl;var NR=re("ptyService");var wv={Backend:"workbench.contributions.terminal.processBackend"},Zl=class{constructor(){this._backends=new Map}get backends(){return this._backends}registerTerminalBackend(t){let e=this._sanitizeRemoteAuthority(t.remoteAuthority);if(this._backends.has(e))throw new Error(`A terminal backend with remote authority '${e}' was already registered.`);this._backends.set(e,t)}getTerminalBackend(t){return this._backends.get(this._sanitizeRemoteAuthority(t))}_sanitizeRemoteAuthority(t){return t?.toLowerCase()??""}};qp.add(wv.Backend,new Zl);var MR=re("localPtyService"),WR=re("terminalLogService");function Pv(i){return new Map(i)}function Av(i){return new Map(i??[])}function Kp(i){return new Map(i.map(t=>[t[0],{map:Pv(t[1]),descriptionMap:Av(t[2])}]))}var Dv=new Map([[2,"APPEND"],[3,"PREPEND"],[1,"REPLACE"]]),Ov=/^VSCODE_PYTHON_(PWSH|ZSH|BASH|FISH)_ACTIVATE/,Lv="ms-python.vscode-python-envs",Is=class{constructor(t){this.collections=t;this.map=new Map;this.descriptionMap=new Map;t.forEach((e,n)=>{this.populateDescriptionMap(e,n);let r=e.map.entries(),o=r.next();for(;!o.done;){let s=o.value[1],a=o.value[0];if(this.blockPythonActivationVar(a,n)){o=r.next();continue}let l=this.map.get(a);if(l||(l=[],this.map.set(a,l)),l.length>0&&l[0].type===1){o=r.next();continue}let c={extensionIdentifier:n,value:s.value,type:s.type,scope:s.scope,variable:s.variable,options:s.options};c.scope||delete c.scope,l.unshift(c),o=r.next()}})}async applyToProcessEnvironment(t,e,n){let r;B&&(r={},Object.keys(t).forEach(o=>r[o.toLowerCase()]=o));for(let[o,s]of this.getVariableMap(e)){let a=B&&r[o.toLowerCase()]||o;for(let l of s){let c=n?await n(l.value):l.value;if(!this.blockPythonActivationVar(l.variable,l.extensionIdentifier)){if(l.options?.applyAtProcessCreation??!0)switch(l.type){case 2:t[a]=(t[a]||"")+c;break;case 3:t[a]=c+(t[a]||"");break;case 1:t[a]=c;break}if(l.options?.applyAtShellIntegration??!1){let p=`VSCODE_ENV_${Dv.get(l.type)}`;t[p]=(t[p]?t[p]+":":"")+o+"="+this._encodeColons(c)}}}}}_encodeColons(t){return t.replaceAll(":","\\x3a")}blockPythonActivationVar(t,e){return!!(Ov.test(t)&&Lv!==e)}diff(t,e){let n=new Map,r=new Map,o=new Map;if(t.getVariableMap(e).forEach((s,a)=>{let l=this.getVariableMap(e).get(a),c=jp(s,l);c&&n.set(a,c)}),this.getVariableMap(e).forEach((s,a)=>{let l=t.getVariableMap(e).get(a),c=jp(s,l);c&&o.set(a,c)}),this.getVariableMap(e).forEach((s,a)=>{let l=t.getVariableMap(e).get(a),c=Fv(s,l);c&&r.set(a,c)}),!(n.size===0&&r.size===0&&o.size===0))return{added:n,changed:r,removed:o}}getVariableMap(t){let e=new Map;for(let n of this.map.values()){let r=n.filter(o=>zp(o,t));r.length>0&&e.set(r[0].variable,r)}return e}getDescriptionMap(t){let e=new Map;for(let n of this.descriptionMap.values()){let r=n.filter(o=>zp(o,t,!0));for(let o of r)e.set(o.extensionIdentifier,o.description)}return e}populateDescriptionMap(t,e){if(!t.descriptionMap)return;let n=t.descriptionMap.entries(),r=n.next();for(;!r.done;){let o=r.value[1],s=r.value[0],a=this.descriptionMap.get(s);a||(a=[],this.descriptionMap.set(s,a));let l={extensionIdentifier:e,scope:o.scope,description:o.description};l.scope||delete l.scope,a.push(l),r=n.next()}}};function zp(i,t,e=!1){return i.scope?!!(i.scope.workspaceFolder&&t?.workspaceFolder&&i.scope.workspaceFolder.index===t.workspaceFolder.index):e?t===i.scope:!0}function jp(i,t){if(!t)return i;let e=new Set;t.forEach(r=>e.add(r.extensionIdentifier));let n=[];return i.forEach(r=>{e.has(r.extensionIdentifier)||n.push(r)}),n.length===0?void 0:n}function Fv(i,t){if(!t)return;let e=new Map;t.forEach(r=>e.set(r.extensionIdentifier,r));let n=[];return i.forEach(r=>{let o=e.get(r.extensionIdentifier);o&&(r.type!==o.type||r.value!==o.value||r.scope?.workspaceFolder?.index!==o.scope?.workspaceFolder?.index)&&n.push(o)}),n.length===0?void 0:n}import{chmod as Gp,realpathSync as Mv,mkdirSync as Wv}from"fs";import{promisify as Jp}from"util";import*as Ss from"os";var Ni;async function Uv(){if(Ni)return;if(!B){Ni={release:Ss.release(),buildNumber:0};return}let i,t;try{let e=await import("@vscode/windows-registry"),n="SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",r=e.GetStringRegKey("HKEY_LOCAL_MACHINE",n,"CurrentBuild");r!==void 0&&(i=parseInt(r,10),isNaN(i)&&(i=void 0));let o=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",n,"CurrentMajorVersionNumber"),s=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",n,"CurrentMinorVersionNumber");o!==void 0&&s!==void 0&&r!==void 0&&(t=`${o}.${s}.${r}`)}catch{}finally{Ni={release:t||Ss.release(),buildNumber:i||Nv()}}}async function Hp(){return Ni||await Uv(),Ni.buildNumber}function Nv(){let i=/(\d+)\.(\d+)\.(\d+)/g.exec(Ss.release());return i&&i.length===4?parseInt(i[3],10):0}async function Zp(i,t,e,n,r,o=!1){if(!t.shellIntegration.enabled)return{type:"failure",reason:"injectionSettingDisabled"};if(!i.executable)return{type:"failure",reason:"noExecutable"};if(i.isFeatureTerminal&&!i.forceShellIntegration)return{type:"failure",reason:"featureTerminal"};if(i.ignoreShellIntegration)return{type:"failure",reason:"ignoreShellIntegrationFlag"};let s=B?await Hp():0;if(B&&s<18309)return{type:"failure",reason:"unsupportedWindowsBuild"};let a=i.args,l=go==="win32"?Te(i.executable).toLowerCase():Te(i.executable),c=me(Xe.asFileUri("").fsPath),p="injection",u,f={VSCODE_INJECTION:"1"};t.shellIntegration.nonce&&(f.VSCODE_NONCE=t.shellIntegration.nonce);let m=["PATH","VIRTUAL_ENV","HOME","SHELL","PWD"];if(i.shellIntegrationEnvironmentReporting&&(B?(t.windowsUseConptyDll||s>=22631&&l!=="bash.exe")&&(f.VSCODE_SHELL_ENV_REPORTING=m.join(",")):f.VSCODE_SHELL_ENV_REPORTING=m.join(",")),B)return l==="pwsh.exe"||l==="powershell.exe"?(f.VSCODE_A11Y_MODE=t.isScreenReaderOptimized?"1":"0",!a||Xp(a)?u=pe.get("windows-pwsh"):Yp(a)&&(u=pe.get("windows-pwsh-login")),u?(u=[...u],u[u.length-1]=_n(u[u.length-1],c,""),f.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:p,newArgs:u,envMixin:f}):{type:"failure",reason:"unsupportedArgs"}):l==="bash.exe"?(!a||a.length===0?u=pe.get("bash"):_s(a)&&(f.VSCODE_SHELL_LOGIN="1",Ts(t,f,l),u=pe.get("bash")),u?(u=[...u],u[u.length-1]=_n(u[u.length-1],c),f.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:p,newArgs:u,envMixin:f}):{type:"failure",reason:"unsupportedArgs"}):(n.warn(`Shell integration cannot be enabled for executable "${i.executable}" and args`,i.args),{type:"failure",reason:"unsupportedShell"});switch(l){case"bash":return!a||a.length===0?u=pe.get("bash"):_s(a)&&(f.VSCODE_SHELL_LOGIN="1",Ts(t,f,l),u=pe.get("bash")),u?(u=[...u],u[u.length-1]=_n(u[u.length-1],c),f.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:p,newArgs:u,envMixin:f}):{type:"failure",reason:"unsupportedArgs"};case"fish":return!a||a.length===0?u=pe.get("fish"):_s(a)?u=pe.get("fish-login"):(a===pe.get("fish")||a===pe.get("fish-login"))&&(u=a),u?(Ts(t,f,l),u=[...u],u[u.length-1]=_n(u[u.length-1],c),{type:p,newArgs:u,envMixin:f}):{type:"failure",reason:"unsupportedArgs"};case"pwsh":return!a||Xp(a)?u=pe.get("pwsh"):Yp(a)&&(u=pe.get("pwsh-login")),u?(u=[...u],u[u.length-1]=_n(u[u.length-1],c,""),f.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:p,newArgs:u,envMixin:f}):{type:"failure",reason:"unsupportedArgs"};case"zsh":{if(!a||a.length===0?u=pe.get("zsh"):_s(a)?(u=pe.get("zsh-login"),Ts(t,f,l)):(a===pe.get("zsh")||a===pe.get("zsh-login"))&&(u=a),!u)return{type:"failure",reason:"unsupportedArgs"};u=[...u],u[u.length-1]=_n(u[u.length-1],c);let v;try{v=Pr.userInfo().username}catch{v="unknown"}let h=Mv(Pr.tmpdir()),I=q(h,`${v}-${r.applicationName}-zsh`);if(!o)try{await Jp(Gp)(I,960)}catch(C){if(C.message.includes("ENOENT")){try{Wv(I)}catch(X){return n.error(`Failed to create zdotdir at ${I}: ${X}`),{type:"failure",reason:"failedToCreateTmpDir"}}try{await Jp(Gp)(I,960)}catch{return n.error(`Failed to set sticky bit on ${I}: ${C}`),{type:"failure",reason:"failedToSetStickyBit"}}}return n.error(`Failed to set sticky bit on ${I}: ${C}`),{type:"failure",reason:"failedToSetStickyBit"}}f.ZDOTDIR=I;let y=e?.ZDOTDIR??Pr.homedir()??"~";f.USER_ZDOTDIR=y;let S=[];return S.push({source:q(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-rc.zsh"),dest:q(I,".zshrc")}),S.push({source:q(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-profile.zsh"),dest:q(I,".zprofile")}),S.push({source:q(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-env.zsh"),dest:q(I,".zshenv")}),S.push({source:q(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-login.zsh"),dest:q(I,".zlogin")}),{type:p,newArgs:u,envMixin:f,filesToCopy:S}}}return n.warn(`Shell integration cannot be enabled for executable "${i.executable}" and args`,i.args),{type:"failure",reason:"unsupportedShell"}}function Ts(i,t,e){if((Je||e==="fish")&&i.environmentVariableCollections){let n=Kp(i.environmentVariableCollections),o=new Is(n).getVariableMap({workspaceFolder:i.workspaceFolder}).get("PATH"),s=[];if(o)for(let a of o)a.type===3&&s.push(a.value);s.length>0&&(t.VSCODE_PATH_PREFIX=s.join(""))}}var pe=new Map;pe.set("windows-pwsh",["-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);pe.set("windows-pwsh-login",["-l","-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);pe.set("pwsh",["-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"{1}']);pe.set("pwsh-login",["-l","-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"']);pe.set("zsh",["-i"]);pe.set("zsh-login",["-il"]);pe.set("bash",["--init-file","{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh"]);pe.set("fish",["--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);pe.set("fish-login",["-l","--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);var xs=["-login","-l"],Qp=["--login","-l"],Bv=["-i","--interactive"],Es=["-nol","-nologo"];function Yp(i){return Me(i)?xs.includes(i.toLowerCase()):i.length===1&&xs.includes(i[0].toLowerCase())||i.length===2&&(xs.includes(i[0].toLowerCase())||xs.includes(i[1].toLowerCase()))&&(Es.includes(i[0].toLowerCase())||Es.includes(i[1].toLowerCase()))}function Xp(i){return Me(i)?Es.includes(i.toLowerCase()):i.length===0||i?.length===1&&Es.includes(i[0].toLowerCase())}function _s(i){return Me(i)||(i=i.filter(t=>!Bv.includes(t.toLowerCase()))),Me(i)&&Qp.includes(i.toLowerCase())||!Me(i)&&i.length===1&&Qp.includes(i[0].toLowerCase())}function ef(i){return i.indexOf("\\")===-1?i:i.replaceAll(/\\(\\|x([0-9a-f]{2}))/gi,(t,e,n)=>n?String.fromCharCode(parseInt(n,16)):e)}function $v(i){let t=i.indexOf(";");if((t===-1?i.length:t)!==1)return;let e=i[0],n=t===-1?"":i.substring(t+1);switch(e){case"A":return{type:0};case"B":return{type:1};case"C":return{type:2};case"D":{let r=n.length>0?parseInt(n,10):void 0;return{type:3,exitCode:r!==void 0&&!isNaN(r)?r:void 0}}case"E":{let r=n.indexOf(";"),o=ef(r===-1?n:n.substring(0,r)),s=r===-1?void 0:n.substring(r+1);return{type:4,commandLine:o,nonce:s}}case"P":{let r=ef(n),o=r.indexOf("=");return o===-1?void 0:{type:5,key:r.substring(0,o),value:r.substring(o+1)}}default:return}}var nc="\x1B",ec=nc+"]",tc="\x07",tf=nc+"\\",Cs=class{constructor(){this._pendingOsc="";this._inOsc=!1;this._pendingEscInOsc=!1}parse(t){let e=[];if(!this._inOsc&&t.indexOf(ec)===-1)return{cleanedData:t,events:e};let n="",r=0;for(;r<t.length;){if(this._inOsc){if(this._pendingEscInOsc){if(this._pendingEscInOsc=!1,t[r]==="\\"){r++,this._inOsc=!1;let c=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(c,e,{value:n,append(p){n=p}},tf);continue}this._inOsc=!1;let l=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(l,e,{value:n,append(c){n=c}});continue}let a=this._consumeOscBody(t,r);if(r=a.nextIndex,a.complete){this._inOsc=!1;let l=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(l,e,{value:n,append(c){n=c}},a.terminator)}else a.pendingEsc&&(this._pendingEscInOsc=!0);continue}let o=t.indexOf(ec,r);if(o===-1){n+=t.substring(r),r=t.length;continue}n+=t.substring(r,o),r=o+2,this._pendingOsc="",this._inOsc=!0;let s=this._consumeOscBody(t,r);if(r=s.nextIndex,s.complete){this._inOsc=!1;let a=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(a,e,{value:n,append(l){n=l}},s.terminator)}else s.pendingEsc&&(this._pendingEscInOsc=!0)}return{cleanedData:n,events:e}}_consumeOscBody(t,e){let n=t.indexOf(tc,e),r=t.indexOf(nc,e);return n!==-1&&(r===-1||n<r)?(this._pendingOsc+=t.substring(e,n),{nextIndex:n+1,complete:!0,terminator:tc}):r!==-1?r+1>=t.length?(this._pendingOsc+=t.substring(e,r),{nextIndex:t.length,complete:!1,pendingEsc:!0}):(this._pendingOsc+=t.substring(e,r),t[r+1]==="\\"?{nextIndex:r+2,complete:!0,terminator:tf}:{nextIndex:r,complete:!0}):(this._pendingOsc+=t.substring(e),{nextIndex:t.length,complete:!1})}_handleOscPayload(t,e,n,r=tc){if(t.startsWith("633;")){let o=t.substring(4),s=$v(o);s&&e.push(s)}else n&&n.append(n.value+ec+t+r)}};var qv=1e4,kr=re("agentHostTerminalManager"),rc;async function Kv(){return rc||(rc=await import("node-pty")),rc}var Ar=class extends L{constructor(e,n,r){super();this._stateManager=e;this._logService=n;this._productService=r;this._terminals=new Map;this._register(this._stateManager.onDidEmitEnvelope(o=>{let s=o.action;if(ts(s))switch(s.type){case"terminal/input":this._writeInput(s.terminal,s.data);break;case"terminal/resized":this._resize(s.terminal,s.cols,s.rows);break;case"terminal/claimed":this._setClaim(s.terminal,s.claim);break;case"terminal/titleChanged":this._setTitle(s.terminal,s.title);break;case"terminal/cleared":this._clearContent(s.terminal);break}}))}getTerminalInfos(){return[...this._terminals.values()].map(e=>({resource:e.uri,title:e.title,claim:e.claim,exitCode:e.exitCode}))}getTerminalState(e){let n=this._terminals.get(e);if(n)return{title:n.title,cwd:n.cwd,cols:n.cols,rows:n.rows,content:n.content,exitCode:n.exitCode,claim:n.claim,supportsCommandDetection:n.commandTracker?.detectionAvailableEmitted}}async createTerminal(e,n){let r=e.terminal;if(this._terminals.has(r))throw new Error(`Terminal already exists: ${r}`);let o=await Kv(),s=await this._resolveCwd(e.cwd,r),a=e.cols??80,l=e.rows??24,c=n?.shell??this._getDefaultShell(),p=B?"cmd":"xterm-256color";this._logService.info(`[TerminalManager] Creating terminal ${r}: shell=${c}, cwd=${s}, cols=${a}, rows=${l}`);let u=ne(),f={...process.env};n?.preventShellHistory&&(f.VSCODE_PREVENT_SHELL_HISTORY="1");let m=[],v=await Zp({executable:c,args:[],forceShellIntegration:!0},{shellIntegration:{enabled:!0,suggestEnabled:!1,nonce:u},windowsUseConptyDll:!1,environmentVariableCollections:void 0,workspaceFolder:void 0,isScreenReaderOptimized:!1},void 0,this._logService,this._productService),h;if(v.type==="injection"){if(this._logService.info(`[TerminalManager] Shell integration injected for ${r}`),v.envMixin)for(let[ie,Ue]of Object.entries(v.envMixin))Ue!==void 0&&(f[ie]=Ue);if(v.newArgs&&(m=v.newArgs),v.filesToCopy)for(let ie of v.filesToCopy)try{await Rs.promises.mkdir(me(ie.dest),{recursive:!0}),await Rs.promises.copyFile(ie.source,ie.dest)}catch{}h={parser:new Cs,nonce:u,commandCounter:0,detectionAvailableEmitted:!1}}else this._logService.info(`[TerminalManager] Shell integration not available for ${r}: ${v.reason}`);let I=o.spawn(c,m,{name:p,cwd:s,env:f,cols:a,rows:l}),y=new N,S=e.claim??{kind:"client",clientId:""},C=y.add(new x),X=y.add(new x),Fe=y.add(new x),rt=y.add(new x),P={uri:r,store:y,pty:I,onDataEmitter:C,onExitEmitter:X,onClaimChangedEmitter:Fe,onCommandFinishedEmitter:rt,title:e.name??c,cwd:s,cols:a,rows:l,content:[],contentSize:0,claim:S,commandTracker:h};this._terminals.set(r,P),y.add(w(()=>{try{I.kill()}catch{}}));let F=new Be,A=I.onData(ie=>{this._handlePtyData(P,ie),F.complete()});y.add(w(()=>A.dispose()));let Z=I.onExit(ie=>{P.exitCode=ie.exitCode,P.onExitEmitter.fire(ie.exitCode),F.complete(),this._stateManager.dispatchServerAction({type:"terminal/exited",terminal:r,exitCode:ie.exitCode}),this._broadcastTerminalList()});if(y.add(w(()=>Z.dispose())),!B){let ie=setInterval(()=>{let Ue=I.process;Ue&&Ue!==P.title&&(P.title=Ue,this._stateManager.dispatchServerAction({type:"terminal/titleChanged",terminal:r,title:Ue}),this._broadcastTerminalList())},200);y.add(w(()=>clearInterval(ie)))}await iu([F.p,Ut(qv)]),this._broadcastTerminalList()}_writeInput(e,n){this.writeInput(e,n)}writeInput(e,n){let r=this._terminals.get(e);r&&r.exitCode===void 0&&r.pty.write(n)}onData(e,n){let r=this._terminals.get(e);return r?r.onDataEmitter.event(n):w(()=>{})}onExit(e,n){let r=this._terminals.get(e);return r?r.onExitEmitter.event(n):w(()=>{})}onClaimChanged(e,n){let r=this._terminals.get(e);return r?r.onClaimChangedEmitter.event(n):w(()=>{})}onCommandFinished(e,n){let r=this._terminals.get(e);return r?r.onCommandFinishedEmitter.event(n):w(()=>{})}getContent(e){let n=this._terminals.get(e);if(n)return n.content.map(r=>r.type==="command"?r.output:r.value).join("")}getClaim(e){return this._terminals.get(e)?.claim}hasTerminal(e){return this._terminals.has(e)}supportsCommandDetection(e){return this._terminals.get(e)?.commandTracker?.detectionAvailableEmitted??!1}getExitCode(e){return this._terminals.get(e)?.exitCode}_resize(e,n,r){let o=this._terminals.get(e);o&&o.exitCode===void 0&&(o.cols=n,o.rows=r,o.pty.resize(n,r))}_setClaim(e,n){let r=this._terminals.get(e);r&&(r.claim=n,r.onClaimChangedEmitter.fire(n),this._broadcastTerminalList())}_setTitle(e,n){let r=this._terminals.get(e);r&&(r.title=n,this._broadcastTerminalList())}_clearContent(e){let n=this._terminals.get(e);n&&(n.content=[],n.contentSize=0)}_handlePtyData(e,n){let r=e.commandTracker,o;if(r){let s=r.parser.parse(n);o=s.cleanedData;for(let a of s.events)this._handleOsc633Event(e,r,a)}else o=n;o.length>0&&this._appendToContent(e,o),this._trimContent(e),o.length>0&&(e.onDataEmitter.fire(o),this._stateManager.dispatchServerAction({type:"terminal/data",terminal:e.uri,data:o}))}_handleOsc633Event(e,n,r){switch(n.detectionAvailableEmitted||(n.detectionAvailableEmitted=!0,this._stateManager.dispatchServerAction({type:"terminal/commandDetectionAvailable",terminal:e.uri})),r.type){case 4:{r.nonce===n.nonce&&(n.pendingCommandLine=r.commandLine);break}case 2:{let o=`cmd-${++n.commandCounter}`,s=n.pendingCommandLine??"",a=Date.now();n.pendingCommandLine=void 0,n.activeCommandId=o,n.activeCommandTimestamp=a,e.content.push({type:"command",commandId:o,commandLine:s,output:"",timestamp:a,isComplete:!1}),this._stateManager.dispatchServerAction({type:"terminal/commandExecuted",terminal:e.uri,commandId:o,commandLine:s,timestamp:a});break}case 3:{let o=n.activeCommandId;if(!o)break;let s=n.activeCommandTimestamp!==void 0?Date.now()-n.activeCommandTimestamp:void 0,a="",l="";for(let c of e.content)if(c.type==="command"&&c.commandId===o){c.isComplete=!0,c.exitCode=r.exitCode,c.durationMs=s,a=c.commandLine,l=c.output;break}n.activeCommandId=void 0,n.activeCommandTimestamp=void 0,e.onCommandFinishedEmitter.fire({commandId:o,exitCode:r.exitCode,command:a,output:l}),this._stateManager.dispatchServerAction({type:"terminal/commandFinished",terminal:e.uri,commandId:o,exitCode:r.exitCode,durationMs:s});break}case 5:{r.key==="Cwd"&&(e.cwd=r.value,this._stateManager.dispatchServerAction({type:"terminal/cwdChanged",terminal:e.uri,cwd:r.value}));break}}}_appendToContent(e,n){let r=e.content.length>0?e.content[e.content.length-1]:void 0;r&&r.type==="command"&&!r.isComplete?(r.output+=n,e.contentSize+=n.length):r&&r.type==="unclassified"?(r.value+=n,e.contentSize+=n.length):(e.content.push({type:"unclassified",value:n}),e.contentSize+=n.length)}_getContentPartSize(e){return e.type==="command"?e.output.length:e.value.length}_trimContent(e){if(!(e.contentSize<=1e5)){for(;e.contentSize>8e4&&e.content.length>1;){let o=e.content.shift();e.contentSize-=this._getContentPartSize(o)}if(e.contentSize>8e4&&e.content.length>0){let o=e.content[0],s=e.contentSize-8e4;o.type==="command"?o.output=o.output.slice(s):o.value=o.value.slice(s),e.contentSize-=s}}}disposeTerminal(e){let n=this._terminals.get(e);n&&(this._terminals.delete(e),n.store.dispose(),this._broadcastTerminalList())}_getDefaultShell(){return B?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/sh"}async _resolveCwd(e,n){let r=e;if(e){let s=b.parse(e);s.scheme==="file"&&s.fsPath&&s.fsPath!=="/"?r=s.fsPath:this._logService.warn(`[TerminalManager] Ignoring non-file cwd for ${n}: ${e}`)}try{if(r&&(await Rs.promises.stat(r)).isDirectory())return r}catch{}let o=process.env.HOME||process.env.USERPROFILE||process.cwd();return this._logService.warn(`[TerminalManager] cwd '${r}' is not accessible, falling back to ${o}`),o}_broadcastTerminalList(){this._stateManager.dispatchServerAction({type:"root/terminalsChanged",terminals:this.getTerminalInfos()})}dispose(){for(let e of this._terminals.values())e.store.dispose();this._terminals.clear(),super.dispose()}};Ar=O([K(1,ue),K(2,Vp)],Ar);var zv={"root/agentsChanged":!1,"root/activeSessionsChanged":!1,"root/terminalsChanged":!1,"session/ready":!1,"session/creationFailed":!1,"session/turnStarted":!0,"session/delta":!1,"session/responsePart":!1,"session/toolCallStart":!1,"session/toolCallDelta":!1,"session/toolCallReady":!1,"session/toolCallConfirmed":!0,"session/toolCallComplete":!0,"session/toolCallResultConfirmed":!0,"session/toolCallContentChanged":!0,"session/turnComplete":!1,"session/turnCancelled":!0,"session/error":!1,"session/titleChanged":!0,"session/usage":!1,"session/reasoning":!1,"session/modelChanged":!0,"session/serverToolsChanged":!1,"session/activeClientChanged":!0,"session/activeClientToolsChanged":!0,"session/pendingMessageSet":!0,"session/pendingMessageRemoved":!0,"session/queuedMessagesReordered":!0,"session/inputRequested":!1,"session/inputAnswerChanged":!0,"session/inputCompleted":!0,"session/customizationsChanged":!1,"session/customizationToggled":!0,"session/truncated":!0,"session/isReadChanged":!0,"session/isDoneChanged":!0,"session/diffsChanged":!1,"session/configChanged":!0,"terminal/data":!1,"terminal/input":!0,"terminal/resized":!0,"terminal/claimed":!0,"terminal/titleChanged":!0,"terminal/cwdChanged":!1,"terminal/exited":!1,"terminal/cleared":!0,"terminal/commandDetectionAvailable":!1,"terminal/commandExecuted":!1,"terminal/commandFinished":!1};function oc(i,t){let e=`Unhandled action type: ${JSON.stringify(i)}`;(t??console.warn)(e)}function Mi(i){return{toolCallId:i.toolCallId,toolName:i.toolName,displayName:i.displayName,toolClientId:i.toolClientId,_meta:i._meta}}function jv(i){return i.activeTurn?i.activeTurn.responseParts.some(t=>t.kind==="toolCall"&&(t.toolCall.status==="pending-confirmation"||t.toolCall.status==="pending-result-confirmation")):!1}function Or(i,t){return t||((i.inputRequests?.length??0)>0||jv(i)?24:i.activeTurn?8:1)}function ws(i){let t=Or(i);return t===i.summary.status?i:{...i,summary:{...i.summary,status:t}}}function ic(i,t,e,n,r){if(!i.activeTurn||i.activeTurn.id!==t)return i;let o=i.activeTurn,s=o.responseParts.map(c=>{if(c.kind!=="toolCall")return c;let p=c.toolCall;return p.status==="completed"||p.status==="cancelled"?c:{kind:"toolCall",toolCall:{status:"cancelled",...Mi(p),invocationMessage:p.status==="streaming"?p.invocationMessage??"":p.invocationMessage,toolInput:p.status==="streaming"?void 0:p.toolInput,reason:"skipped"}}}),a={id:o.id,userMessage:o.userMessage,responseParts:s,usage:o.usage,state:e,error:r},l={...i,turns:[...i.turns,a],activeTurn:void 0,summary:{...i.summary,modifiedAt:Date.now()}};return delete l.inputRequests,{...l,summary:{...l.summary,status:Or(l,n)}}}function Hv(i,t){let e=i.inputRequests??[],n=e.findIndex(s=>s.id===t.id),r=[...e];if(n>=0){let s=t.answers??r[n].answers;r[n]={...t,answers:s}}else r.push(t);let o={...i,inputRequests:r};return{...o,summary:{...o.summary,status:Or(o),modifiedAt:Date.now(),isRead:!1}}}function Dr(i,t,e,n){let r=i.activeTurn;if(!r||r.id!==t)return i;let o=!1,s=r.responseParts.map(a=>{if(a.kind==="toolCall"&&a.toolCall.toolCallId===e){let l=n(a.toolCall);return l===a.toolCall?a:(o=!0,{...a,toolCall:l})}return a});return o?{...i,activeTurn:{...r,responseParts:s}}:i}function nf(i,t,e,n){let r=i.activeTurn;if(!r||r.id!==t)return i;let o=!1,s=r.responseParts.map(a=>!o&&(a.kind==="toolCall"?a.toolCall.toolCallId:"id"in a?a.id:void 0)===e?(o=!0,n(a)):a);return o?{...i,activeTurn:{...r,responseParts:s}}:i}function sc(i,t,e){switch(t.type){case"root/agentsChanged":return{...i,agents:t.agents};case"root/activeSessionsChanged":return{...i,activeSessions:t.activeSessions};case"root/terminalsChanged":return{...i,terminals:t.terminals};default:return oc(t,e),i}}function ac(i,t,e){switch(t.type){case"session/ready":return{...i,lifecycle:"ready",summary:{...i.summary,status:1}};case"session/creationFailed":return{...i,lifecycle:"creationFailed",creationError:t.error};case"session/turnStarted":{let n={...i,activeTurn:{id:t.turnId,userMessage:t.userMessage,responseParts:[],usage:void 0}};if(n={...n,summary:{...n.summary,status:Or(n),modifiedAt:Date.now(),isRead:!1}},t.queuedMessageId&&(n.steeringMessage?.id===t.queuedMessageId&&(n={...n,steeringMessage:void 0}),n.queuedMessages)){let r=n.queuedMessages.filter(o=>o.id!==t.queuedMessageId);n={...n,queuedMessages:r.length>0?r:void 0}}return n}case"session/delta":return nf(i,t.turnId,t.partId,n=>n.kind==="markdown"?{...n,content:n.content+t.content}:n);case"session/responsePart":return!i.activeTurn||i.activeTurn.id!==t.turnId?i:{...i,activeTurn:{...i.activeTurn,responseParts:[...i.activeTurn.responseParts,t.part]}};case"session/turnComplete":return ic(i,t.turnId,"complete");case"session/turnCancelled":return ic(i,t.turnId,"cancelled");case"session/error":return ic(i,t.turnId,"error",2,t.error);case"session/toolCallStart":return!i.activeTurn||i.activeTurn.id!==t.turnId?i:{...i,activeTurn:{...i.activeTurn,responseParts:[...i.activeTurn.responseParts,{kind:"toolCall",toolCall:{toolCallId:t.toolCallId,toolName:t.toolName,displayName:t.displayName,toolClientId:t.toolClientId,_meta:t._meta,status:"streaming"}}]}};case"session/toolCallDelta":return Dr(i,t.turnId,t.toolCallId,n=>n.status!=="streaming"?n:{...n,partialInput:(n.partialInput??"")+t.content,invocationMessage:t.invocationMessage??n.invocationMessage});case"session/toolCallReady":return ws(Dr(i,t.turnId,t.toolCallId,n=>{if(n.status!=="streaming"&&n.status!=="running")return n;let r=Mi(n);return t.confirmed?{status:"running",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:t.confirmed}:{status:"pending-confirmation",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmationTitle:t.confirmationTitle,edits:t.edits,editable:t.editable}}));case"session/toolCallConfirmed":return ws(Dr(i,t.turnId,t.toolCallId,n=>{if(n.status!=="pending-confirmation")return n;let r=Mi(n);return t.approved?{status:"running",...r,invocationMessage:n.invocationMessage,toolInput:t.editedToolInput??n.toolInput,confirmed:t.confirmed}:{status:"cancelled",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,reason:t.reason,reasonMessage:t.reasonMessage,userSuggestion:t.userSuggestion}}));case"session/toolCallComplete":return ws(Dr(i,t.turnId,t.toolCallId,n=>{if(n.status!=="running"&&n.status!=="pending-confirmation")return n;let r=Mi(n),o=n.status==="running"?n.confirmed:"not-needed";return t.requiresResultConfirmation?{status:"pending-result-confirmation",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:o,...t.result}:{status:"completed",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:o,...t.result}}));case"session/toolCallResultConfirmed":return ws(Dr(i,t.turnId,t.toolCallId,n=>{if(n.status!=="pending-result-confirmation")return n;let r=Mi(n);return t.approved?{status:"completed",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:n.confirmed,success:n.success,pastTenseMessage:n.pastTenseMessage,content:n.content,structuredContent:n.structuredContent,error:n.error}:{status:"cancelled",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,reason:"result-denied"}}));case"session/toolCallContentChanged":return Dr(i,t.turnId,t.toolCallId,n=>n.status!=="running"?n:{...n,content:t.content});case"session/titleChanged":return{...i,summary:{...i.summary,title:t.title,modifiedAt:Date.now()}};case"session/usage":return!i.activeTurn||i.activeTurn.id!==t.turnId?i:{...i,activeTurn:{...i.activeTurn,usage:t.usage}};case"session/reasoning":return nf(i,t.turnId,t.partId,n=>n.kind==="reasoning"?{...n,content:n.content+t.content}:n);case"session/modelChanged":return{...i,summary:{...i.summary,model:t.model,modifiedAt:Date.now()}};case"session/isReadChanged":return{...i,summary:{...i.summary,isRead:t.isRead}};case"session/isDoneChanged":return{...i,summary:{...i.summary,isDone:t.isDone}};case"session/diffsChanged":return{...i,summary:{...i.summary,diffs:t.diffs}};case"session/configChanged":return i.config?{...i,config:{...i.config,values:{...i.config.values,...t.config}},summary:{...i.summary,modifiedAt:Date.now()}}:i;case"session/serverToolsChanged":return{...i,serverTools:t.tools};case"session/activeClientChanged":return{...i,activeClient:t.activeClient??void 0};case"session/activeClientToolsChanged":return i.activeClient?{...i,activeClient:{...i.activeClient,tools:t.tools}}:i;case"session/customizationsChanged":return{...i,customizations:t.customizations};case"session/customizationToggled":{let n=i.customizations;if(!n)return i;let r=n.findIndex(s=>s.customization.uri===t.uri);if(r<0)return i;let o=[...n];return o[r]={...n[r],enabled:t.enabled},{...i,customizations:o}}case"session/truncated":{let n;if(t.turnId===void 0)n=[];else{let o=i.turns.findIndex(s=>s.id===t.turnId);if(o<0)return i;n=i.turns.slice(0,o+1)}let r={...i,turns:n,activeTurn:void 0,summary:{...i.summary,modifiedAt:Date.now()}};return delete r.inputRequests,{...r,summary:{...r.summary,status:Or(r)}}}case"session/inputRequested":return Hv(i,t.request);case"session/inputAnswerChanged":{let n=i.inputRequests,r=n?.findIndex(l=>l.id===t.requestId)??-1;if(!n||r<0)return i;let o=n[r],s={...o.answers??{}};t.answer===void 0?delete s[t.questionId]:s[t.questionId]=t.answer;let a=[...n];return a[r]={...o,answers:Object.keys(s).length>0?s:void 0},{...i,inputRequests:a,summary:{...i.summary,modifiedAt:Date.now()}}}case"session/inputCompleted":{let n=i.inputRequests;if(!n?.some(s=>s.id===t.requestId))return i;let r=n.filter(s=>s.id!==t.requestId),o={...i};return r.length>0?o.inputRequests=r:delete o.inputRequests,{...o,summary:{...o.summary,status:Or(o),modifiedAt:Date.now()}}}case"session/pendingMessageSet":{let n={id:t.id,userMessage:t.userMessage};if(t.kind==="steering")return{...i,steeringMessage:n};let r=i.queuedMessages??[],o=r.findIndex(s=>s.id===t.id);if(o>=0){let s=[...r];return s[o]=n,{...i,queuedMessages:s}}return{...i,queuedMessages:[...r,n]}}case"session/pendingMessageRemoved":{if(t.kind==="steering")return!i.steeringMessage||i.steeringMessage.id!==t.id?i:{...i,steeringMessage:void 0};let n=i.queuedMessages;if(!n)return i;let r=n.filter(o=>o.id!==t.id);return r.length===n.length?i:{...i,queuedMessages:r.length>0?r:void 0}}case"session/queuedMessagesReordered":{let n=i.queuedMessages;if(!n)return i;let r=new Map(n.map(a=>[a.id,a])),o=new Set,s=t.order.filter(a=>r.has(a)&&!o.has(a)?(o.add(a),!0):!1).map(a=>r.get(a));for(let a of n)o.has(a.id)||s.push(a);return{...i,queuedMessages:s}}default:return oc(t,e),i}}var Lr=class extends L{constructor(e){super();this._logService=e;this._serverSeq=0;this._sessionStates=new Map;this._activeTurnToSession=new Map;this._lastNotifiedSummaries=new Map;this._dirtySummaries=new Set;this._summaryNotifyScheduler=this._register(new nr(()=>this._flushSummaryNotifications(),100));this._onDidEmitEnvelope=this._register(new x);this.onDidEmitEnvelope=this._onDidEmitEnvelope.event;this._onDidEmitNotification=this._register(new x);this.onDidEmitNotification=this._onDidEmitNotification.event;this._log=e=>this._logService.warn(`[AgentHostStateManager] ${e}`);this._rootState=hp()}get hasActiveSessions(){return this._activeTurnToSession.size>0}get rootState(){return this._rootState}getSessionState(e){return this._sessionStates.get(e)}get serverSeq(){return this._serverSeq}getSessionUrisWithPrefix(e){let n=[];for(let r of this._sessionStates.keys())r.startsWith(e)&&n.push(r);return n}getSnapshot(e){if(e===os)return{resource:e,state:this._rootState,fromSeq:this._serverSeq};let n=this._sessionStates.get(e);if(n)return{resource:e,state:n,fromSeq:this._serverSeq}}createSession(e){let n=e.resource;if(this._sessionStates.has(n))return this._logService.warn(`[AgentHostStateManager] Session already exists: ${n}`),this._sessionStates.get(n);let r=Bl(e);return this._sessionStates.set(n,r),this._logService.trace(`[AgentHostStateManager] Created session: ${n}`),this._lastNotifiedSummaries.set(n,e),this._onDidEmitNotification.fire({type:"notify/sessionAdded",summary:e}),r}restoreSession(e,n){let r=e.resource;if(this._sessionStates.has(r))return this._logService.warn(`[AgentHostStateManager] Session already exists (restore): ${r}`),this._sessionStates.get(r);let o={...Bl(e),lifecycle:"ready",turns:n};return this._sessionStates.set(r,o),this._lastNotifiedSummaries.set(r,e),this._logService.trace(`[AgentHostStateManager] Restored session: ${r} (${n.length} turns)`),o}removeSession(e){let n=this._sessionStates.get(e);n&&(n.activeTurn&&this._activeTurnToSession.delete(n.activeTurn.id),this._sessionStates.delete(e),this._lastNotifiedSummaries.delete(e),this._dirtySummaries.delete(e),this._logService.trace(`[AgentHostStateManager] Removed session: ${e}`))}deleteSession(e){this.removeSession(e),this._onDidEmitNotification.fire({type:"notify/sessionRemoved",session:e})}getActiveTurnId(e){return this._sessionStates.get(e)?.activeTurn?.id}dispatchServerAction(e){this._applyAndEmit(e,void 0)}dispatchClientAction(e,n){return this._applyAndEmit(e,n)}_applyAndEmit(e,n){let r;if(sp(e)&&(this._rootState=sc(this._rootState,e,this._log),r=this._rootState),Sr(e)){let s=e,a=s.session,l=this._sessionStates.get(a);if(l){let c=ac(l,s,this._log);this._sessionStates.set(a,c),l.summary!==c.summary&&(this._dirtySummaries.add(a),this._summaryNotifyScheduler.schedule()),s.type==="session/turnStarted"?(this._activeTurnToSession.set(s.turnId,a),this.dispatchServerAction({type:"root/activeSessionsChanged",activeSessions:this._activeTurnToSession.size})):(s.type==="session/turnComplete"||s.type==="session/turnCancelled"||s.type==="session/error")&&(this._activeTurnToSession.delete(s.turnId),this.dispatchServerAction({type:"root/activeSessionsChanged",activeSessions:this._activeTurnToSession.size})),r=c}else this._logService.warn(`[AgentHostStateManager] Action for unknown session: ${a}, type=${e.type}`)}let o={action:e,serverSeq:++this._serverSeq,origin:n};return this._logService.trace(`[AgentHostStateManager] Emitting envelope: seq=${o.serverSeq}, type=${e.type}${n?`, origin=${n.clientId}:${n.clientSeq}`:""}`),this._onDidEmitEnvelope.fire(o),r}_flushSummaryNotifications(){for(let e of this._dirtySummaries){let n=this._sessionStates.get(e),r=this._lastNotifiedSummaries.get(e);if(!n||!r||n.summary===r)continue;let o=n.summary,s={};o.title!==r.title&&(s.title=o.title),o.status!==r.status&&(s.status=o.status),o.modifiedAt!==r.modifiedAt&&(s.modifiedAt=o.modifiedAt),o.project!==r.project&&(s.project=o.project),o.model!==r.model&&(s.model=o.model),o.workingDirectory!==r.workingDirectory&&(s.workingDirectory=o.workingDirectory),o.isRead!==r.isRead&&(s.isRead=o.isRead),o.isDone!==r.isDone&&(s.isDone=o.isDone),o.diffs!==r.diffs&&(s.diffs=o.diffs),this._lastNotifiedSummaries.set(e,o),Object.keys(s).length>0&&this._onDidEmitNotification.fire({type:"notify/sessionSummaryChanged",session:e,changes:s})}this._dirtySummaries.clear()}};Lr=O([K(0,ue)],Lr);function rf(i){return i?{subagentDescription:i.subagentDescription,subagentAgentName:i.subagentAgentName}:{}}var Ps=class extends L{constructor(e,n,r,o){super();this._logService=e;this._fileService=n;this._sessionDataService=r;this._productService=o;this._onDidAction=this._register(new x);this.onDidAction=this._onDidAction.event;this._onDidNotification=this._register(new x);this.onDidNotification=this._onDidNotification.event;this._providers=new Map;this._sessionToProvider=new Map;this._providerSubscriptions=this._register(new N);this._agents=Ln("agents",[]);this._logService.info("AgentService initialized"),this._stateManager=this._register(new Lr(e)),this._register(this._stateManager.onDidEmitEnvelope(s=>this._onDidAction.fire(s))),this._register(this._stateManager.onDidEmitNotification(s=>this._onDidNotification.fire(s))),this._sideEffects=this._register(new ys(this._stateManager,{getAgent:s=>this._findProviderForSession(s),sessionDataService:this._sessionDataService,agents:this._agents},this._logService)),this._terminalManager=this._register(new Ar(this._stateManager,this._logService,this._productService))}get stateManager(){return this._stateManager}get terminalManager(){return this._terminalManager}registerProvider(e){if(this._providers.has(e.id))throw new Error(`Agent provider already registered: ${e.id}`);this._logService.info(`Registering agent provider: ${e.id}`),this._providers.set(e.id,e),this._providerSubscriptions.add(this._sideEffects.registerProgressListener(e)),this._defaultProvider||(this._defaultProvider=e.id),this._updateAgents()}async authenticate(e){this._logService.trace(`[AgentService] authenticate called: resource=${e.resource}`);for(let n of this._providers.values())if(n.getProtectedResources().some(o=>o.resource===e.resource)&&await n.authenticate(e.resource,e.token))return{authenticated:!0};return{authenticated:!1}}async listSessions(){this._logService.trace("[AgentService] listSessions called");let n=(await Promise.all([...this._providers.values()].map(s=>s.listSessions()))).flat(),o=(await Promise.all(n.map(async s=>{try{let a=await this._sessionDataService.tryOpenDatabase(s.session);if(!a)return s;try{let l=await a.object.getMetadataObject({customTitle:!0,isRead:!0,isDone:!0,diffs:!0}),c=s;if(l.customTitle&&(c={...c,summary:l.customTitle}),l.isRead!==void 0&&(c={...c,isRead:l.isRead==="true"}),l.isDone!==void 0&&(c={...c,isDone:l.isDone==="true"}),l.diffs)try{c={...c,diffs:JSON.parse(l.diffs)}}catch{}return c}finally{a.dispose()}}catch(a){this._logService.warn(`[AgentService] Failed to read session metadata overlay for ${s.session}`,a)}return s}))).map(s=>{let a=this._stateManager.getSessionState(s.session.toString());return a?{...s,summary:a.summary.title||s.summary,status:a.summary.status,model:a.summary.model??s.model}:s});return this._logService.trace(`[AgentService] listSessions returned ${o.length} sessions`),o}async createSession(e){let n=e?.provider??this._defaultProvider,r=n?this._providers.get(n):void 0;if(!r)throw new Error(`No agent provider registered for: ${n??"(none)"}`);if(e?.fork){let l=this._stateManager.getSessionState(e.fork.session.toString());if(l){let c=l.turns.slice(0,e.fork.turnIndex+1),p=new Map;for(let u of c)p.set(u.id,ne());e={...e,fork:{...e.fork,turnIdMapping:p}}}}this._logService.trace("[AgentService] createSession: initializing auto-approver and creating session...");let[,o]=await Promise.all([this._sideEffects.initialize(),r.createSession(e)]),s=o.session;this._logService.trace("[AgentService] createSession: initialization complete"),this._logService.trace(`[AgentService] createSession: provider=${r.id} model=${e?.model?.id??"(default)"}`),this._sessionToProvider.set(s.toString(),r.id),this._logService.trace(`[AgentService] createSession returned: ${s.toString()}`);let a=await this._resolveCreatedSessionConfig(r,e);if(e?.fork){let l=this._stateManager.getSessionState(e.fork.session.toString()),c=[];l&&e.fork.turnIdMapping&&(c=l.turns.slice(0,e.fork.turnIndex+1).map(f=>({...f,id:e.fork.turnIdMapping.get(f.id)??ne()})));let p={resource:s.toString(),provider:r.id,title:l?.summary.title??"Forked Session",status:1,createdAt:Date.now(),modifiedAt:Date.now(),...o.project?{project:{uri:o.project.uri.toString(),displayName:o.project.displayName}}:{},model:e?.model,workingDirectory:(o.workingDirectory??e.workingDirectory)?.toString()},u=this._stateManager.createSession(p);u.config=a,u.turns=c}else{let l={resource:s.toString(),provider:r.id,title:"",status:1,createdAt:Date.now(),modifiedAt:Date.now(),...o.project?{project:{uri:o.project.uri.toString(),displayName:o.project.displayName}}:{},model:e?.model,workingDirectory:(o.workingDirectory??e?.workingDirectory)?.toString()},c=this._stateManager.createSession(l);c.config=a}return a?.values&&Object.keys(a.values).length>0&&this._persistConfigValues(s,a.values),this._stateManager.dispatchServerAction({type:"session/ready",session:s.toString()}),s}_persistConfigValues(e,n){let r;try{r=this._sessionDataService.openDatabase(e)}catch(o){this._logService.warn(`[AgentService] Failed to open session database to persist configValues for ${e.toString()}: ${kn(o)}`);return}r.object.setMetadata("configValues",JSON.stringify(n)).catch(o=>{this._logService.warn(`[AgentService] Failed to persist configValues for ${e.toString()}: ${kn(o)}`)}).finally(()=>{r.dispose()})}async _resolveCreatedSessionConfig(e,n){if(!(!n?.config&&!n?.workingDirectory))try{let r=await e.resolveSessionConfig({provider:e.id,workingDirectory:n.workingDirectory,config:n.config});return{schema:r.schema,values:r.values}}catch(r){return this._logService.error(`[AgentService] Failed to resolve created session config for provider ${e.id}`,r),n.config?{schema:{type:"object",properties:{}},values:n.config}:void 0}}async resolveSessionConfig(e){let n=e.provider??this._defaultProvider,r=n?this._providers.get(n):void 0;if(!r)throw new Error(`No agent provider registered for: ${n??"(none)"}`);return r.resolveSessionConfig(e)}async sessionConfigCompletions(e){let n=e.provider??this._defaultProvider,r=n?this._providers.get(n):void 0;if(!r)throw new Error(`No agent provider registered for: ${n??"(none)"}`);return r.sessionConfigCompletions(e)}async disposeSession(e){this._logService.trace(`[AgentService] disposeSession: ${e.toString()}`);let n=this._findProviderForSession(e);n&&(await n.disposeSession(e),this._sessionToProvider.delete(e.toString())),this._sideEffects.removeSubagentSessions(e.toString()),this._stateManager.deleteSession(e.toString())}async createTerminal(e){await this._terminalManager.createTerminal(e)}async disposeTerminal(e){this._terminalManager.disposeTerminal(e.toString())}async subscribe(e){this._logService.trace(`[AgentService] subscribe: ${e.toString()}`);let n=e.toString(),r=this._terminalManager.getTerminalState(n);if(r)return{resource:n,state:r,fromSeq:this._stateManager.serverSeq};let o=this._stateManager.getSnapshot(n);if(!o){let s=ss(n);s?await this._restoreSubagentSession(n,s.parentSession,s.toolCallId):await this.restoreSession(e),o=this._stateManager.getSnapshot(n)}if(!o)throw new Error(`Cannot subscribe to unknown resource: ${n}`);return o}unsubscribe(e){this._logService.trace(`[AgentService] unsubscribe: ${e.toString()}`)}dispatchAction(e,n,r){this._logService.trace(`[AgentService] dispatchAction: type=${e.type}, clientId=${n}, clientSeq=${r}`,e);let o={clientId:n,clientSeq:r};Sr(e)?(this._stateManager.dispatchClientAction(e,o),this._sideEffects.handleAction(e)):this._stateManager.dispatchClientAction(e,o)}async resourceList(e){let n;try{n=await this._fileService.resolve(e)}catch{throw new H(Oe.NotFound,`Directory not found: ${e.toString()}`)}if(!n.isDirectory)throw new H(Oe.NotFound,`Not a directory: ${e.toString()}`);return{entries:(n.children??[]).map(o=>({name:o.name,type:o.isDirectory?"directory":"file"}))}}async restoreSession(e){let n=e.toString();if(this._stateManager.getSessionState(n))return;let r=this._findProviderForSession(e);if(!r)throw new H(cn,`No agent for session: ${n}`);let o;try{o=await r.listSessions()}catch(y){if(y instanceof H)throw y;let S=y instanceof Error?y.message:String(y);throw new H(Tr,`Failed to list sessions for ${n}: ${S}`)}let s=o.find(y=>y.session.toString()===n);if(!s)throw new H(cn,`Session not found on backend: ${n}`);let a;try{a=await r.getSessionMessages(e)}catch(y){if(y instanceof H)throw y;let S=y instanceof Error?y.message:String(y);throw new H(Tr,`Failed to restore session ${n}: ${S}`)}let l=this._buildTurnsFromMessages(a),c=s.summary??"Session",p,u,f,m,v=this._sessionDataService.tryOpenDatabase?.(e);if(v)try{let y=await v;if(y)try{let S=await y.object.getMetadataObject({customTitle:!0,isRead:!0,isDone:!0,diffs:!0,configValues:!0});if(S.customTitle&&(c=S.customTitle),S.isRead!==void 0&&(p=S.isRead==="true"),S.isDone!==void 0&&(u=S.isDone==="true"),S.diffs)try{f=JSON.parse(S.diffs)}catch{}if(S.configValues)try{m=JSON.parse(S.configValues)}catch(C){this._logService.warn(`[AgentService] Failed to parse persisted configValues for ${n}: ${kn(C)}`)}}finally{y.dispose()}}catch{}let h={resource:n,provider:r.id,title:c,status:1,createdAt:s.startTime,modifiedAt:s.modifiedTime,...s.project?{project:{uri:s.project.uri.toString(),displayName:s.project.displayName}}:{},model:s.model,workingDirectory:s.workingDirectory?.toString(),isRead:p,isDone:u,diffs:f};this._stateManager.restoreSession(h,l);let I=await this._resolveCreatedSessionConfig(r,{workingDirectory:s.workingDirectory,config:m});if(I){let y=this._stateManager.getSessionState(n);y&&(y.config=I)}this._logService.info(`[AgentService] Restored session ${n} with ${l.length} turns`)}async resourceRead(e){let n=Wp(e.toString());if(n)return this._fetchSessionDbContent(n);try{return{data:(await this._fileService.readFile(e)).value.toString(),encoding:"utf-8",contentType:"text/plain"}}catch{throw new H(Oe.NotFound,`Content not found: ${e.toString()}`)}}async resourceWrite(e){let n=typeof e.uri=="string"?b.parse(e.uri):b.revive(e.uri),r;e.encoding==="base64"?r=Do(e.data):r=_.fromString(e.data);try{return e.createOnly?await this._fileService.createFile(n,r,{overwrite:!1}):await this._fileService.writeFile(n,r),{}}catch(o){let s=xt(o);throw s==="EntryExists"?new H(Oe.AlreadyExists,`File already exists: ${n.toString()}`):s==="NoPermissions"?new H(Oe.PermissionDenied,`Permission denied: ${n.toString()}`):new H(Oe.NotFound,`Failed to write file: ${n.toString()}`)}}async resourceCopy(e){let n=b.parse(e.source),r=b.parse(e.destination);try{return await this._fileService.copy(n,r,!e.failIfExists),{}}catch(o){let s=xt(o);throw s==="EntryExists"?new H(Oe.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new H(Oe.PermissionDenied,`Permission denied: ${n.toString()}`):new H(Oe.NotFound,`Source not found: ${n.toString()}`)}}async resourceDelete(e){let n=b.parse(e.uri);try{return await this._fileService.del(n,{recursive:e.recursive}),{}}catch(r){throw xt(r)==="NoPermissions"?new H(Oe.PermissionDenied,`Permission denied: ${n.toString()}`):new H(Oe.NotFound,`Resource not found: ${n.toString()}`)}}async resourceMove(e){let n=b.parse(e.source),r=b.parse(e.destination);try{return await this._fileService.move(n,r,!e.failIfExists),{}}catch(o){let s=xt(o);throw s==="EntryExists"?new H(Oe.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new H(Oe.PermissionDenied,`Permission denied: ${n.toString()}`):new H(Oe.NotFound,`Source not found: ${n.toString()}`)}}async shutdown(){this._logService.info("AgentService: shutting down all providers...");let e=[];for(let n of this._providers.values())e.push(n.shutdown());await Promise.all(e),this._sessionToProvider.clear()}_buildTurnsFromMessages(e){let n=[],r=new Map,o,s=(l,c)=>{n.push({id:l.id,userMessage:l.userMessage,responseParts:l.responseParts,usage:void 0,state:c})},a=(l,c)=>({id:l,userMessage:{text:c},responseParts:[],pendingTools:new Map});for(let l of e)if(l.type==="message"&&l.role==="user")o&&s(o,"cancelled"),o=a(l.messageId,l.content);else if(l.type==="message"&&l.role==="assistant"){if(l.parentToolCallId)continue;o||(o=a(l.messageId,"")),l.content&&o.responseParts.push({kind:"markdown",id:ne(),content:l.content}),(!l.toolRequests||l.toolRequests.length===0)&&(s(o,"complete"),o=void 0)}else if(l.type==="subagent_started")r.set(l.toolCallId,l);else if(l.type==="tool_start"){if(l.parentToolCallId)continue;o?.pendingTools.set(l.toolCallId,l)}else if(l.type==="tool_complete"){if(l.parentToolCallId)continue;if(o){let c=o.pendingTools.get(l.toolCallId);o.pendingTools.delete(l.toolCallId);let p=r.get(l.toolCallId),u=l.result.content?[...l.result.content]:[];if(p){let m=l.session.toString();u.push({type:"subagent",resource:Ei(m,l.toolCallId),title:p.agentDisplayName,agentName:p.agentName,description:p.agentDescription})}let f={status:"completed",toolCallId:l.toolCallId,toolName:c?.toolName??"unknown",displayName:c?.displayName??"Unknown Tool",invocationMessage:c?.invocationMessage??"Unknown tool",toolInput:c?.toolInput,success:l.result.success,pastTenseMessage:l.result.pastTenseMessage,content:u.length>0?u:void 0,error:l.result.error,confirmed:"not-needed",_meta:{toolKind:c?.toolKind,language:c?.language,...rf(c)}};o.responseParts.push({kind:"toolCall",toolCall:f})}}return o&&s(o,"cancelled"),n}_buildSubagentTurns(e,n,r){let o=new Set;for(let p of e)(p.type==="tool_start"||p.type==="tool_complete")&&p.parentToolCallId===n&&o.add(p.toolCallId);let s=new Map;for(let p of e)p.type==="subagent_started"&&o.has(p.toolCallId)&&s.set(p.toolCallId,p);let a=e.filter(p=>p.type==="tool_start"||p.type==="tool_complete"||p.type==="message"?p.parentToolCallId===n:!1);if(a.length===0)return[];let l=[],c=new Map;for(let p of a)if(p.type==="tool_start")c.set(p.toolCallId,p);else if(p.type==="tool_complete"){let u=c.get(p.toolCallId);c.delete(p.toolCallId);let f=s.get(p.toolCallId),m=p.result.content?[...p.result.content]:[];f&&m.push({type:"subagent",resource:Ei(r,p.toolCallId),title:f.agentDisplayName,agentName:f.agentName,description:f.agentDescription});let v={status:"completed",toolCallId:p.toolCallId,toolName:u?.toolName??"unknown",displayName:u?.displayName??"Unknown Tool",invocationMessage:u?.invocationMessage??"Unknown tool",toolInput:u?.toolInput,success:p.result.success,pastTenseMessage:p.result.pastTenseMessage,content:m.length>0?m:void 0,error:p.result.error,confirmed:"not-needed",_meta:{toolKind:u?.toolKind,language:u?.language,...rf(u)}};l.push({kind:"toolCall",toolCall:v})}else p.type==="message"&&p.role==="assistant"&&p.content&&l.push({kind:"markdown",id:ne(),content:p.content});return l.length===0?[]:[{id:ne(),userMessage:{text:""},responseParts:l,usage:void 0,state:"complete"}]}async _fetchSessionDbContent(e){let n=b.parse(e.sessionUri),r=this._sessionDataService.openDatabase(n);try{let o=await r.object.readFileEditContent(e.toolCallId,e.filePath);if(!o)throw new H(Oe.NotFound,`File edit not found: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);let s=e.part==="before"?o.beforeContent:o.afterContent;if(!s)throw new H(Oe.NotFound,`No ${e.part} content for: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);return{data:new TextDecoder().decode(s),encoding:"utf-8",contentType:"text/plain"}}finally{r.dispose()}}async _restoreSubagentSession(e,n,r){let o=b.parse(n);if(!this._stateManager.getSessionState(n))try{await this.restoreSession(o)}catch{this._logService.warn(`[AgentService] Cannot restore parent session for subagent: ${n}`);return}let s=this._stateManager.getSessionState(n);if(!s)return;let a=[...s.turns];s.activeTurn&&a.push(s.activeTurn);let l;for(let f of a){for(let m of f.responseParts)if(m.kind==="toolCall"){let v=m.toolCall,h=v.status==="completed"||v.status==="running"?v.content:void 0;if(h){for(let I of h)if(I.type==="subagent"&&I.resource===e){l=I;break}}}if(l)break}let c=[],p=this._findProviderForSession(o);if(p)try{let f=await p.getSessionMessages(o);c=this._buildSubagentTurns(f,r,e)}catch(f){this._logService.warn(`[AgentService] Failed to load parent messages for subagent restore: ${e}`,f)}let u=l?.title??"Subagent";this._stateManager.restoreSession({resource:e,provider:"subagent",title:u,status:1,createdAt:Date.now(),modifiedAt:Date.now(),...s?.summary.project?{project:s.summary.project}:{}},c),this._logService.info(`[AgentService] Restored subagent session: ${e} with ${c.length} turn(s)`)}_findProviderForSession(e){let n=typeof e=="string"?e:e.toString(),r=this._sessionToProvider.get(n);if(r)return this._providers.get(r);let o=ce.provider(e);if(o)return this._providers.get(o);if(this._defaultProvider)return this._providers.get(this._defaultProvider)}_updateAgents(){this._agents.set([...this._providers.values()],void 0)}dispose(){for(let e of this._providers.values())e.dispose();this._providers.clear(),super.dispose()}};import{CopilotClient as G1}from"@github/copilot-sdk";import{rgPath as J1}from"@vscode/ripgrep";import*as ji from"fs/promises";var Q4=new Uint32Array(10);var Y4=new Uint8Array([114,82,115,101,69,102,97,113,81,116,84,100,119,87,99,122,120,118,103]),X4=new Uint16Array([107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]),Z4=new Uint16Array([114,82,29810,115,30579,26483,101,102,29286,24934,29030,29798,30822,30310,26470,97,113,29809,116,84,100,119,99,122,120,118,103]),eP=new Uint16Array([114,82,29810,115,30579,26483,101,69,102,29286,24934,29030,29798,30822,30310,26470,97,113,81,29809,116,84,100,119,87,99,122,120,118,103,107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]);function sf(...i){return function(t,e){for(let n=0,r=i.length;n<r;n++){let o=i[n](t,e);if(o)return o}return null}}var cP=lf.bind(void 0,!1),af=lf.bind(void 0,!0);function lf(i,t,e){if(!e||e.length<t.length)return null;let n;return i?n=tn(e,t):n=e.indexOf(t)===0,n?t.length>0?[{start:0,end:t.length}]:[]:null}function Gv(i,t){if(i.length>t.length)return null;let e=t.toLowerCase().indexOf(i.toLowerCase());return e===-1?null:[{start:e,end:e+i.length}]}function Jv(i,t){return i.length>t.length?null:lc(i.toLowerCase(),t.toLowerCase(),0,0)}function lc(i,t,e,n){if(e===i.length)return[];if(n===t.length)return null;if(i[e]===t[n]){let r=null;return(r=lc(i,t,e+1,n+1))?df({start:n,end:n+1},r):null}return lc(i,t,e,n+1)}function dc(i){return 97<=i&&i<=122}function ks(i){return 65<=i&&i<=90}function uc(i){return 48<=i&&i<=57}function Qv(i){return i===32||i===9||i===10||i===13}var Yv=new Set;"()[]{}<>`'\"-/;:,.?!".split("").forEach(i=>Yv.add(i.charCodeAt(0)));function cf(i){return dc(i)||ks(i)||uc(i)}function df(i,t){return t.length===0?t=[i]:i.end===t[0].start?t[0].start=i.start:t.unshift(i),t}function uf(i,t){for(let e=t;e<i.length;e++){let n=i.charCodeAt(e);if(ks(n)||uc(n)||e>0&&!cf(i.charCodeAt(e-1)))return e}return i.length}function cc(i,t,e,n){if(e===i.length)return[];if(n===t.length)return null;if(i[e]!==t[n].toLowerCase())return null;{let r=null,o=n+1;for(r=cc(i,t,e+1,n+1);!r&&(o=uf(t,o))<t.length;)r=cc(i,t,e+1,o),o++;return r===null?null:df({start:n,end:n+1},r)}}function Xv(i){let t=0,e=0,n=0,r=0,o=0;for(let p=0;p<i.length;p++)o=i.charCodeAt(p),ks(o)&&t++,dc(o)&&e++,cf(o)&&n++,uc(o)&&r++;let s=t/i.length,a=e/i.length,l=n/i.length,c=r/i.length;return{upperPercent:s,lowerPercent:a,alphaPercent:l,numericPercent:c}}function Zv(i){let{upperPercent:t,lowerPercent:e}=i;return e===0&&t>.6}function e1(i){let{upperPercent:t,lowerPercent:e,alphaPercent:n,numericPercent:r}=i;return e>.2&&t<.8&&n>.6&&r<.2}function t1(i){let t=0,e=0,n=0,r=0;for(let o=0;o<i.length;o++)n=i.charCodeAt(o),ks(n)&&t++,dc(n)&&e++,Qv(n)&&r++;return(t===0||e===0)&&r===0?i.length<=30:t<=5}function pf(i,t){if(!t||(t=t.trim(),t.length===0)||!t1(i))return null;t.length>60&&(t=t.substring(0,60));let e=Xv(t);if(!e1(e)){if(!Zv(e))return null;t=t.toLowerCase()}let n=null,r=0;for(i=i.toLowerCase();r<t.length&&(n=cc(i,t,0,r))===null;)r=uf(t,r+1);return n}var dP=sf(af,pf,Gv),uP=sf(af,pf,Jv),pP=new bt(1e4);var As=128;function pc(){let i=[],t=[];for(let e=0;e<=As;e++)t[e]=0;for(let e=0;e<=As;e++)i.push(t.slice(0));return i}function ff(i){let t=[];for(let e=0;e<=i;e++)t[e]=0;return t}var fP=ff(2*As),gP=ff(2*As),mP=pc(),hP=pc(),vP=pc();var n1;(e=>{e.Default=[-100,0];function t(n){return!n||n.length===2&&n[0]===-100&&n[1]===0}e.isDefault=t})(n1||={});var of=class{constructor(t,e){this.firstMatchCanBeWeak=t;this.boostFullMatch=e}static{this.default={boostFullMatch:!0,firstMatchCanBeWeak:!1}}};var gf=Object.create(null);function d(i,t){if(Me(t)){let e=gf[t];if(e===void 0)throw new Error(`${i} references an unknown codicon: ${t}`);t=e}return gf[i]=t,{id:i}}var mf={add:d("add",6e4),plus:d("plus",6e4),gistNew:d("gist-new",6e4),repoCreate:d("repo-create",6e4),lightbulb:d("lightbulb",60001),lightBulb:d("light-bulb",60001),repo:d("repo",60002),repoDelete:d("repo-delete",60002),gistFork:d("gist-fork",60003),repoForked:d("repo-forked",60003),gitPullRequest:d("git-pull-request",60004),gitPullRequestAbandoned:d("git-pull-request-abandoned",60004),recordKeys:d("record-keys",60005),keyboard:d("keyboard",60005),tag:d("tag",60006),gitPullRequestLabel:d("git-pull-request-label",60006),tagAdd:d("tag-add",60006),tagRemove:d("tag-remove",60006),person:d("person",60007),personFollow:d("person-follow",60007),personOutline:d("person-outline",60007),personFilled:d("person-filled",60007),sourceControl:d("source-control",60008),mirror:d("mirror",60009),mirrorPublic:d("mirror-public",60009),star:d("star",60010),starAdd:d("star-add",60010),starDelete:d("star-delete",60010),starEmpty:d("star-empty",60010),comment:d("comment",60011),commentAdd:d("comment-add",60011),alert:d("alert",60012),warning:d("warning",60012),search:d("search",60013),searchSave:d("search-save",60013),logOut:d("log-out",60014),signOut:d("sign-out",60014),logIn:d("log-in",60015),signIn:d("sign-in",60015),eye:d("eye",60016),eyeUnwatch:d("eye-unwatch",60016),eyeWatch:d("eye-watch",60016),circleFilled:d("circle-filled",60017),primitiveDot:d("primitive-dot",60017),closeDirty:d("close-dirty",60017),debugBreakpoint:d("debug-breakpoint",60017),debugBreakpointDisabled:d("debug-breakpoint-disabled",60017),debugHint:d("debug-hint",60017),terminalDecorationSuccess:d("terminal-decoration-success",60017),primitiveSquare:d("primitive-square",60018),edit:d("edit",60019),pencil:d("pencil",60019),info:d("info",60020),issueOpened:d("issue-opened",60020),gistPrivate:d("gist-private",60021),gitForkPrivate:d("git-fork-private",60021),lock:d("lock",60021),mirrorPrivate:d("mirror-private",60021),close:d("close",60022),removeClose:d("remove-close",60022),x:d("x",60022),repoSync:d("repo-sync",60023),sync:d("sync",60023),clone:d("clone",60024),desktopDownload:d("desktop-download",60024),beaker:d("beaker",60025),microscope:d("microscope",60025),vm:d("vm",60026),deviceDesktop:d("device-desktop",60026),file:d("file",60027),more:d("more",60028),ellipsis:d("ellipsis",60028),kebabHorizontal:d("kebab-horizontal",60028),mailReply:d("mail-reply",60029),reply:d("reply",60029),organization:d("organization",60030),organizationFilled:d("organization-filled",60030),organizationOutline:d("organization-outline",60030),newFile:d("new-file",60031),fileAdd:d("file-add",60031),newFolder:d("new-folder",60032),fileDirectoryCreate:d("file-directory-create",60032),trash:d("trash",60033),trashcan:d("trashcan",60033),history:d("history",60034),clock:d("clock",60034),folder:d("folder",60035),fileDirectory:d("file-directory",60035),symbolFolder:d("symbol-folder",60035),logoGithub:d("logo-github",60036),markGithub:d("mark-github",60036),github:d("github",60036),terminal:d("terminal",60037),console:d("console",60037),repl:d("repl",60037),zap:d("zap",60038),symbolEvent:d("symbol-event",60038),error:d("error",60039),stop:d("stop",60039),variable:d("variable",60040),symbolVariable:d("symbol-variable",60040),array:d("array",60042),symbolArray:d("symbol-array",60042),symbolModule:d("symbol-module",60043),symbolPackage:d("symbol-package",60043),symbolNamespace:d("symbol-namespace",60043),symbolObject:d("symbol-object",60043),symbolMethod:d("symbol-method",60044),symbolFunction:d("symbol-function",60044),symbolConstructor:d("symbol-constructor",60044),symbolBoolean:d("symbol-boolean",60047),symbolNull:d("symbol-null",60047),symbolNumeric:d("symbol-numeric",60048),symbolNumber:d("symbol-number",60048),symbolStructure:d("symbol-structure",60049),symbolStruct:d("symbol-struct",60049),symbolParameter:d("symbol-parameter",60050),symbolTypeParameter:d("symbol-type-parameter",60050),symbolKey:d("symbol-key",60051),symbolText:d("symbol-text",60051),symbolReference:d("symbol-reference",60052),goToFile:d("go-to-file",60052),symbolEnum:d("symbol-enum",60053),symbolValue:d("symbol-value",60053),symbolRuler:d("symbol-ruler",60054),symbolUnit:d("symbol-unit",60054),activateBreakpoints:d("activate-breakpoints",60055),archive:d("archive",60056),arrowBoth:d("arrow-both",60057),arrowDown:d("arrow-down",60058),arrowLeft:d("arrow-left",60059),arrowRight:d("arrow-right",60060),arrowSmallDown:d("arrow-small-down",60061),arrowSmallLeft:d("arrow-small-left",60062),arrowSmallRight:d("arrow-small-right",60063),arrowSmallUp:d("arrow-small-up",60064),arrowUp:d("arrow-up",60065),bell:d("bell",60066),bold:d("bold",60067),book:d("book",60068),bookmark:d("bookmark",60069),debugBreakpointConditionalUnverified:d("debug-breakpoint-conditional-unverified",60070),debugBreakpointConditional:d("debug-breakpoint-conditional",60071),debugBreakpointConditionalDisabled:d("debug-breakpoint-conditional-disabled",60071),debugBreakpointDataUnverified:d("debug-breakpoint-data-unverified",60072),debugBreakpointData:d("debug-breakpoint-data",60073),debugBreakpointDataDisabled:d("debug-breakpoint-data-disabled",60073),debugBreakpointLogUnverified:d("debug-breakpoint-log-unverified",60074),debugBreakpointLog:d("debug-breakpoint-log",60075),debugBreakpointLogDisabled:d("debug-breakpoint-log-disabled",60075),briefcase:d("briefcase",60076),broadcast:d("broadcast",60077),browser:d("browser",60078),bug:d("bug",60079),calendar:d("calendar",60080),caseSensitive:d("case-sensitive",60081),check:d("check",60082),checklist:d("checklist",60083),chevronDown:d("chevron-down",60084),chevronLeft:d("chevron-left",60085),chevronRight:d("chevron-right",60086),chevronUp:d("chevron-up",60087),chromeClose:d("chrome-close",60088),chromeMaximize:d("chrome-maximize",60089),chromeMinimize:d("chrome-minimize",60090),chromeRestore:d("chrome-restore",60091),circleOutline:d("circle-outline",60092),circle:d("circle",60092),debugBreakpointUnverified:d("debug-breakpoint-unverified",60092),terminalDecorationIncomplete:d("terminal-decoration-incomplete",60092),circleSlash:d("circle-slash",60093),circuitBoard:d("circuit-board",60094),clearAll:d("clear-all",60095),clippy:d("clippy",60096),closeAll:d("close-all",60097),cloudDownload:d("cloud-download",60098),cloudUpload:d("cloud-upload",60099),code:d("code",60100),collapseAll:d("collapse-all",60101),colorMode:d("color-mode",60102),commentDiscussion:d("comment-discussion",60103),creditCard:d("credit-card",60105),dash:d("dash",60108),dashboard:d("dashboard",60109),database:d("database",60110),debugContinue:d("debug-continue",60111),debugDisconnect:d("debug-disconnect",60112),debugPause:d("debug-pause",60113),debugRestart:d("debug-restart",60114),debugStart:d("debug-start",60115),debugStepInto:d("debug-step-into",60116),debugStepOut:d("debug-step-out",60117),debugStepOver:d("debug-step-over",60118),debugStop:d("debug-stop",60119),debug:d("debug",60120),deviceCameraVideo:d("device-camera-video",60121),deviceCamera:d("device-camera",60122),deviceMobile:d("device-mobile",60123),diffAdded:d("diff-added",60124),diffIgnored:d("diff-ignored",60125),diffModified:d("diff-modified",60126),diffRemoved:d("diff-removed",60127),diffRenamed:d("diff-renamed",60128),diff:d("diff",60129),diffSidebyside:d("diff-sidebyside",60129),discard:d("discard",60130),editorLayout:d("editor-layout",60131),emptyWindow:d("empty-window",60132),exclude:d("exclude",60133),extensions:d("extensions",60134),eyeClosed:d("eye-closed",60135),fileBinary:d("file-binary",60136),fileCode:d("file-code",60137),fileMedia:d("file-media",60138),filePdf:d("file-pdf",60139),fileSubmodule:d("file-submodule",60140),fileSymlinkDirectory:d("file-symlink-directory",60141),fileSymlinkFile:d("file-symlink-file",60142),fileZip:d("file-zip",60143),files:d("files",60144),filter:d("filter",60145),flame:d("flame",60146),foldDown:d("fold-down",60147),foldUp:d("fold-up",60148),fold:d("fold",60149),folderActive:d("folder-active",60150),folderOpened:d("folder-opened",60151),gear:d("gear",60152),gift:d("gift",60153),gistSecret:d("gist-secret",60154),gist:d("gist",60155),gitCommit:d("git-commit",60156),gitCompare:d("git-compare",60157),compareChanges:d("compare-changes",60157),gitMerge:d("git-merge",60158),githubAction:d("github-action",60159),githubAlt:d("github-alt",60160),globe:d("globe",60161),grabber:d("grabber",60162),graph:d("graph",60163),gripper:d("gripper",60164),heart:d("heart",60165),home:d("home",60166),horizontalRule:d("horizontal-rule",60167),hubot:d("hubot",60168),inbox:d("inbox",60169),issueReopened:d("issue-reopened",60171),issues:d("issues",60172),italic:d("italic",60173),jersey:d("jersey",60174),json:d("json",60175),bracket:d("bracket",60175),kebabVertical:d("kebab-vertical",60176),key:d("key",60177),law:d("law",60178),lightbulbAutofix:d("lightbulb-autofix",60179),linkExternal:d("link-external",60180),link:d("link",60181),listOrdered:d("list-ordered",60182),listUnordered:d("list-unordered",60183),liveShare:d("live-share",60184),loading:d("loading",60185),location:d("location",60186),mailRead:d("mail-read",60187),mail:d("mail",60188),markdown:d("markdown",60189),megaphone:d("megaphone",60190),mention:d("mention",60191),milestone:d("milestone",60192),gitPullRequestMilestone:d("git-pull-request-milestone",60192),mortarBoard:d("mortar-board",60193),move:d("move",60194),multipleWindows:d("multiple-windows",60195),mute:d("mute",60196),noNewline:d("no-newline",60197),note:d("note",60198),octoface:d("octoface",60199),openPreview:d("open-preview",60200),package:d("package",60201),paintcan:d("paintcan",60202),pin:d("pin",60203),play:d("play",60204),run:d("run",60204),plug:d("plug",60205),preserveCase:d("preserve-case",60206),preview:d("preview",60207),project:d("project",60208),pulse:d("pulse",60209),question:d("question",60210),quote:d("quote",60211),radioTower:d("radio-tower",60212),reactions:d("reactions",60213),references:d("references",60214),refresh:d("refresh",60215),regex:d("regex",60216),remoteExplorer:d("remote-explorer",60217),remote:d("remote",60218),remove:d("remove",60219),replaceAll:d("replace-all",60220),replace:d("replace",60221),repoClone:d("repo-clone",60222),repoForcePush:d("repo-force-push",60223),repoPull:d("repo-pull",60224),repoPush:d("repo-push",60225),report:d("report",60226),requestChanges:d("request-changes",60227),rocket:d("rocket",60228),rootFolderOpened:d("root-folder-opened",60229),rootFolder:d("root-folder",60230),rss:d("rss",60231),ruby:d("ruby",60232),saveAll:d("save-all",60233),saveAs:d("save-as",60234),save:d("save",60235),screenFull:d("screen-full",60236),screenNormal:d("screen-normal",60237),searchStop:d("search-stop",60238),server:d("server",60240),settingsGear:d("settings-gear",60241),settings:d("settings",60242),shield:d("shield",60243),smiley:d("smiley",60244),sortPrecedence:d("sort-precedence",60245),splitHorizontal:d("split-horizontal",60246),splitVertical:d("split-vertical",60247),squirrel:d("squirrel",60248),starFull:d("star-full",60249),starHalf:d("star-half",60250),symbolClass:d("symbol-class",60251),symbolColor:d("symbol-color",60252),symbolConstant:d("symbol-constant",60253),symbolEnumMember:d("symbol-enum-member",60254),symbolField:d("symbol-field",60255),symbolFile:d("symbol-file",60256),symbolInterface:d("symbol-interface",60257),symbolKeyword:d("symbol-keyword",60258),symbolMisc:d("symbol-misc",60259),symbolOperator:d("symbol-operator",60260),symbolProperty:d("symbol-property",60261),wrench:d("wrench",60261),wrenchSubaction:d("wrench-subaction",60261),symbolSnippet:d("symbol-snippet",60262),tasklist:d("tasklist",60263),telescope:d("telescope",60264),textSize:d("text-size",60265),threeBars:d("three-bars",60266),thumbsdown:d("thumbsdown",60267),thumbsup:d("thumbsup",60268),tools:d("tools",60269),triangleDown:d("triangle-down",60270),triangleLeft:d("triangle-left",60271),triangleRight:d("triangle-right",60272),triangleUp:d("triangle-up",60273),twitter:d("twitter",60274),unfold:d("unfold",60275),unlock:d("unlock",60276),unmute:d("unmute",60277),unverified:d("unverified",60278),verified:d("verified",60279),versions:d("versions",60280),vmActive:d("vm-active",60281),vmOutline:d("vm-outline",60282),vmRunning:d("vm-running",60283),watch:d("watch",60284),whitespace:d("whitespace",60285),wholeWord:d("whole-word",60286),window:d("window",60287),wordWrap:d("word-wrap",60288),zoomIn:d("zoom-in",60289),zoomOut:d("zoom-out",60290),listFilter:d("list-filter",60291),listFlat:d("list-flat",60292),listSelection:d("list-selection",60293),selection:d("selection",60293),listTree:d("list-tree",60294),debugBreakpointFunctionUnverified:d("debug-breakpoint-function-unverified",60295),debugBreakpointFunction:d("debug-breakpoint-function",60296),debugBreakpointFunctionDisabled:d("debug-breakpoint-function-disabled",60296),debugStackframeActive:d("debug-stackframe-active",60297),circleSmallFilled:d("circle-small-filled",60298),debugStackframeDot:d("debug-stackframe-dot",60298),terminalDecorationMark:d("terminal-decoration-mark",60298),debugStackframe:d("debug-stackframe",60299),debugStackframeFocused:d("debug-stackframe-focused",60299),debugBreakpointUnsupported:d("debug-breakpoint-unsupported",60300),symbolString:d("symbol-string",60301),debugReverseContinue:d("debug-reverse-continue",60302),debugStepBack:d("debug-step-back",60303),debugRestartFrame:d("debug-restart-frame",60304),debugAlt:d("debug-alt",60305),callIncoming:d("call-incoming",60306),callOutgoing:d("call-outgoing",60307),menu:d("menu",60308),expandAll:d("expand-all",60309),feedback:d("feedback",60310),gitPullRequestReviewer:d("git-pull-request-reviewer",60310),groupByRefType:d("group-by-ref-type",60311),ungroupByRefType:d("ungroup-by-ref-type",60312),account:d("account",60313),gitPullRequestAssignee:d("git-pull-request-assignee",60313),bellDot:d("bell-dot",60314),debugConsole:d("debug-console",60315),library:d("library",60316),output:d("output",60317),runAll:d("run-all",60318),syncIgnored:d("sync-ignored",60319),pinned:d("pinned",60320),githubInverted:d("github-inverted",60321),serverProcess:d("server-process",60322),serverEnvironment:d("server-environment",60323),pass:d("pass",60324),issueClosed:d("issue-closed",60324),stopCircle:d("stop-circle",60325),playCircle:d("play-circle",60326),record:d("record",60327),debugAltSmall:d("debug-alt-small",60328),vmConnect:d("vm-connect",60329),cloud:d("cloud",60330),merge:d("merge",60331),export:d("export",60332),graphLeft:d("graph-left",60333),magnet:d("magnet",60334),notebook:d("notebook",60335),redo:d("redo",60336),checkAll:d("check-all",60337),pinnedDirty:d("pinned-dirty",60338),passFilled:d("pass-filled",60339),circleLargeFilled:d("circle-large-filled",60340),circleLarge:d("circle-large",60341),circleLargeOutline:d("circle-large-outline",60341),combine:d("combine",60342),gather:d("gather",60342),table:d("table",60343),variableGroup:d("variable-group",60344),typeHierarchy:d("type-hierarchy",60345),typeHierarchySub:d("type-hierarchy-sub",60346),typeHierarchySuper:d("type-hierarchy-super",60347),gitPullRequestCreate:d("git-pull-request-create",60348),runAbove:d("run-above",60349),runBelow:d("run-below",60350),notebookTemplate:d("notebook-template",60351),debugRerun:d("debug-rerun",60352),workspaceTrusted:d("workspace-trusted",60353),workspaceUntrusted:d("workspace-untrusted",60354),workspaceUnknown:d("workspace-unknown",60355),terminalCmd:d("terminal-cmd",60356),terminalDebian:d("terminal-debian",60357),terminalLinux:d("terminal-linux",60358),terminalPowershell:d("terminal-powershell",60359),terminalTmux:d("terminal-tmux",60360),terminalUbuntu:d("terminal-ubuntu",60361),terminalBash:d("terminal-bash",60362),arrowSwap:d("arrow-swap",60363),copy:d("copy",60364),personAdd:d("person-add",60365),filterFilled:d("filter-filled",60366),wand:d("wand",60367),debugLineByLine:d("debug-line-by-line",60368),inspect:d("inspect",60369),layers:d("layers",60370),layersDot:d("layers-dot",60371),layersActive:d("layers-active",60372),compass:d("compass",60373),compassDot:d("compass-dot",60374),compassActive:d("compass-active",60375),azure:d("azure",60376),issueDraft:d("issue-draft",60377),gitPullRequestClosed:d("git-pull-request-closed",60378),gitPullRequestDraft:d("git-pull-request-draft",60379),debugAll:d("debug-all",60380),debugCoverage:d("debug-coverage",60381),runErrors:d("run-errors",60382),folderLibrary:d("folder-library",60383),debugContinueSmall:d("debug-continue-small",60384),beakerStop:d("beaker-stop",60385),graphLine:d("graph-line",60386),graphScatter:d("graph-scatter",60387),pieChart:d("pie-chart",60388),bracketDot:d("bracket-dot",60389),bracketError:d("bracket-error",60390),lockSmall:d("lock-small",60391),azureDevops:d("azure-devops",60392),verifiedFilled:d("verified-filled",60393),newline:d("newline",60394),layout:d("layout",60395),layoutActivitybarLeft:d("layout-activitybar-left",60396),layoutActivitybarRight:d("layout-activitybar-right",60397),layoutPanelLeft:d("layout-panel-left",60398),layoutPanelCenter:d("layout-panel-center",60399),layoutPanelJustify:d("layout-panel-justify",60400),layoutPanelRight:d("layout-panel-right",60401),layoutPanel:d("layout-panel",60402),layoutSidebarLeft:d("layout-sidebar-left",60403),layoutSidebarRight:d("layout-sidebar-right",60404),layoutStatusbar:d("layout-statusbar",60405),layoutMenubar:d("layout-menubar",60406),layoutCentered:d("layout-centered",60407),target:d("target",60408),indent:d("indent",60409),recordSmall:d("record-small",60410),errorSmall:d("error-small",60411),terminalDecorationError:d("terminal-decoration-error",60411),arrowCircleDown:d("arrow-circle-down",60412),arrowCircleLeft:d("arrow-circle-left",60413),arrowCircleRight:d("arrow-circle-right",60414),arrowCircleUp:d("arrow-circle-up",60415),layoutSidebarRightOff:d("layout-sidebar-right-off",60416),layoutPanelOff:d("layout-panel-off",60417),layoutSidebarLeftOff:d("layout-sidebar-left-off",60418),blank:d("blank",60419),heartFilled:d("heart-filled",60420),map:d("map",60421),mapHorizontal:d("map-horizontal",60421),foldHorizontal:d("fold-horizontal",60421),mapFilled:d("map-filled",60422),mapHorizontalFilled:d("map-horizontal-filled",60422),foldHorizontalFilled:d("fold-horizontal-filled",60422),circleSmall:d("circle-small",60423),bellSlash:d("bell-slash",60424),bellSlashDot:d("bell-slash-dot",60425),commentUnresolved:d("comment-unresolved",60426),gitPullRequestGoToChanges:d("git-pull-request-go-to-changes",60427),gitPullRequestNewChanges:d("git-pull-request-new-changes",60428),searchFuzzy:d("search-fuzzy",60429),commentDraft:d("comment-draft",60430),send:d("send",60431),sparkle:d("sparkle",60432),insert:d("insert",60433),mic:d("mic",60434),thumbsdownFilled:d("thumbsdown-filled",60435),thumbsupFilled:d("thumbsup-filled",60436),coffee:d("coffee",60437),snake:d("snake",60438),game:d("game",60439),vr:d("vr",60440),chip:d("chip",60441),piano:d("piano",60442),music:d("music",60443),micFilled:d("mic-filled",60444),repoFetch:d("repo-fetch",60445),copilot:d("copilot",60446),lightbulbSparkle:d("lightbulb-sparkle",60447),robot:d("robot",60448),sparkleFilled:d("sparkle-filled",60449),diffSingle:d("diff-single",60450),diffMultiple:d("diff-multiple",60451),surroundWith:d("surround-with",60452),share:d("share",60453),gitStash:d("git-stash",60454),gitStashApply:d("git-stash-apply",60455),gitStashPop:d("git-stash-pop",60456),vscode:d("vscode",60457),vscodeInsiders:d("vscode-insiders",60458),codeOss:d("code-oss",60459),runCoverage:d("run-coverage",60460),runAllCoverage:d("run-all-coverage",60461),coverage:d("coverage",60462),githubProject:d("github-project",60463),mapVertical:d("map-vertical",60464),foldVertical:d("fold-vertical",60464),mapVerticalFilled:d("map-vertical-filled",60465),foldVerticalFilled:d("fold-vertical-filled",60465),goToSearch:d("go-to-search",60466),percentage:d("percentage",60467),sortPercentage:d("sort-percentage",60467),attach:d("attach",60468),goToEditingSession:d("go-to-editing-session",60469),editSession:d("edit-session",60470),codeReview:d("code-review",60471),copilotWarning:d("copilot-warning",60472),python:d("python",60473),copilotLarge:d("copilot-large",60474),copilotWarningLarge:d("copilot-warning-large",60475),keyboardTab:d("keyboard-tab",60476),copilotBlocked:d("copilot-blocked",60477),copilotNotConnected:d("copilot-not-connected",60478),flag:d("flag",60479),lightbulbEmpty:d("lightbulb-empty",60480),symbolMethodArrow:d("symbol-method-arrow",60481),copilotUnavailable:d("copilot-unavailable",60482),repoPinned:d("repo-pinned",60483),keyboardTabAbove:d("keyboard-tab-above",60484),keyboardTabBelow:d("keyboard-tab-below",60485),gitPullRequestDone:d("git-pull-request-done",60486),mcp:d("mcp",60487),extensionsLarge:d("extensions-large",60488),layoutPanelDock:d("layout-panel-dock",60489),layoutSidebarLeftDock:d("layout-sidebar-left-dock",60490),layoutSidebarRightDock:d("layout-sidebar-right-dock",60491),copilotInProgress:d("copilot-in-progress",60492),copilotError:d("copilot-error",60493),copilotSuccess:d("copilot-success",60494),chatSparkle:d("chat-sparkle",60495),searchSparkle:d("search-sparkle",60496),editSparkle:d("edit-sparkle",60497),copilotSnooze:d("copilot-snooze",60498),sendToRemoteAgent:d("send-to-remote-agent",60499),commentDiscussionSparkle:d("comment-discussion-sparkle",60500),chatSparkleWarning:d("chat-sparkle-warning",60501),chatSparkleError:d("chat-sparkle-error",60502),collection:d("collection",60503),newCollection:d("new-collection",60504),thinking:d("thinking",60505),build:d("build",60506),commentDiscussionQuote:d("comment-discussion-quote",60507),cursor:d("cursor",60508),eraser:d("eraser",60509),fileText:d("file-text",60510),quotes:d("quotes",60512),rename:d("rename",60513),runWithDeps:d("run-with-deps",60514),debugConnected:d("debug-connected",60515),strikethrough:d("strikethrough",60516),openInProduct:d("open-in-product",60517),indexZero:d("index-zero",60518),agent:d("agent",60519),editCode:d("edit-code",60520),repoSelected:d("repo-selected",60521),skip:d("skip",60522),mergeInto:d("merge-into",60523),gitBranchChanges:d("git-branch-changes",60524),gitBranchStagedChanges:d("git-branch-staged-changes",60525),gitBranchConflicts:d("git-branch-conflicts",60526),gitBranch:d("git-branch",60527),gitBranchCreate:d("git-branch-create",60527),gitBranchDelete:d("git-branch-delete",60527),searchLarge:d("search-large",60528),terminalGitBash:d("terminal-git-bash",60529),windowActive:d("window-active",60530),forward:d("forward",60531),download:d("download",60532),clockface:d("clockface",60533),unarchive:d("unarchive",60534),sessionInProgress:d("session-in-progress",60535),collectionSmall:d("collection-small",60536),vmSmall:d("vm-small",60537),cloudSmall:d("cloud-small",60538),addSmall:d("add-small",60539),removeSmall:d("remove-small",60540),worktreeSmall:d("worktree-small",60541),worktree:d("worktree",60542),screenCut:d("screen-cut",60543),ask:d("ask",60544),openai:d("openai",60545),claude:d("claude",60546),openInWindow:d("open-in-window",60547),newSession:d("new-session",60548),terminalSecure:d("terminal-secure",60549)};var r1={dialogError:d("dialog-error","error"),dialogWarning:d("dialog-warning","warning"),dialogInfo:d("dialog-info","info"),dialogClose:d("dialog-close","close"),treeItemExpanded:d("tree-item-expanded","chevron-down"),treeFilterOnTypeOn:d("tree-filter-on-type-on","list-filter"),treeFilterOnTypeOff:d("tree-filter-on-type-off","list-selection"),treeFilterClear:d("tree-filter-clear","close"),treeItemLoading:d("tree-item-loading","loading"),menuSelection:d("menu-selection","check"),menuSubmenu:d("menu-submenu","chevron-right"),menuBarMore:d("menubar-more","more"),scrollbarButtonLeft:d("scrollbar-button-left","triangle-left"),scrollbarButtonRight:d("scrollbar-button-right","triangle-right"),scrollbarButtonUp:d("scrollbar-button-up","triangle-up"),scrollbarButtonDown:d("scrollbar-button-down","triangle-down"),toolBarMore:d("toolbar-more","more"),quickInputBack:d("quick-input-back","arrow-left"),dropDownButton:d("drop-down-button",60084),symbolCustomColor:d("symbol-customcolor",60252),exportIcon:d("export",60332),workspaceUnspecified:d("workspace-unspecified",60355),newLine:d("newline",60394),thumbsDownFilled:d("thumbsdown-filled",60435),thumbsUpFilled:d("thumbsup-filled",60436),gitFetch:d("git-fetch",60445),lightbulbSparkleAutofix:d("lightbulb-sparkle-autofix",60447),debugBreakpointPending:d("debug-breakpoint-pending",60377),chatImport:d("chat-import",60550),chatExport:d("chat-export",60551)},Ds={...mf,...r1};var hf;(t=>{function i(e){return!!e&&typeof e=="object"&&typeof e.id=="string"}t.isThemeColor=i})(hf||={});var Bi;(y=>{y.iconNameSegment="[A-Za-z0-9]+",y.iconNameExpression="[A-Za-z0-9-]+",y.iconModifierExpression="~[A-Za-z]+",y.iconNameCharacter="[A-Za-z0-9~-]";let r=new RegExp(`^(${y.iconNameExpression})(${y.iconModifierExpression})?$`);function o(S){let C=r.exec(S.id);if(!C)return o(Ds.error);let[,X,Fe]=C,rt=["codicon","codicon-"+X];return Fe&&rt.push("codicon-modifier-"+Fe.substring(1)),rt}y.asClassNameArray=o;function s(S){return o(S).join(" ")}y.asClassName=s;function a(S){return"."+o(S).join(".")}y.asCSSSelector=a;function l(S){return!!S&&typeof S=="object"&&typeof S.id=="string"&&(typeof S.color>"u"||hf.isThemeColor(S.color))}y.isThemeIcon=l;let c=new RegExp(`^\\$\\((${y.iconNameExpression}(?:${y.iconModifierExpression})?)\\)$`);function p(S){let C=c.exec(S);if(!C)return;let[,X]=C;return{id:X}}y.fromString=p;function u(S){return{id:S}}y.fromId=u;function f(S,C){let X=S.id,Fe=X.lastIndexOf("~");return Fe!==-1&&(X=X.substring(0,Fe)),C&&(X=`${X}~${C}`),{id:X}}y.modify=f;function m(S){let C=S.id.lastIndexOf("~");if(C!==-1)return S.id.substring(C+1)}y.getModifier=m;function v(S,C){return S.id===C.id&&S.color?.id===C.color?.id}y.isEqual=v;function h(S){return S?.id===Ds.file.id}y.isFile=h;function I(S){return S?.id===Ds.folder.id}y.isFolder=I})(Bi||={});var fc=new RegExp(`\\$\\(${Bi.iconNameExpression}(?:${Bi.iconModifierExpression})?\\)`,"g"),OP=new RegExp(`(\\\\)?${fc.source}`,"g");var LP=new RegExp(`\\\\${fc.source}`,"g");var FP=new RegExp(`(\\s)?(\\\\)?${fc.source}(\\s)?`,"g");var UP=new RegExp(`\\$\\(${Bi.iconNameCharacter}+\\)`,"g");function jt(i){let t=Math.max(0,...(i.match(/`+/g)??[]).map(o=>o.length)),e="`".repeat(t+1),r=i.startsWith("`")||i.endsWith("`")?` ${i} `:i;return`${e}${r}${e}`}var mc;(t=>t.DEFAULT={allowTrailingComma:!0})(mc||={});function i1(i,t=!1){let e=0,n=i.length,r="",o=0,s=16,a=0;function l(h){let I=0,y=0;for(;I<h;){let S=i.charCodeAt(e);if(S>=48&&S<=57)y=y*16+S-48;else if(S>=65&&S<=70)y=y*16+S-65+10;else if(S>=97&&S<=102)y=y*16+S-97+10;else break;e++,I++}return I<h&&(y=-1),y}function c(h){e=h,r="",o=0,s=16,a=0}function p(){let h=e;if(i.charCodeAt(e)===48)e++;else for(e++;e<i.length&&Fr(i.charCodeAt(e));)e++;if(e<i.length&&i.charCodeAt(e)===46)if(e++,e<i.length&&Fr(i.charCodeAt(e)))for(e++;e<i.length&&Fr(i.charCodeAt(e));)e++;else return a=3,i.substring(h,e);let I=e;if(e<i.length&&(i.charCodeAt(e)===69||i.charCodeAt(e)===101))if(e++,(e<i.length&&i.charCodeAt(e)===43||i.charCodeAt(e)===45)&&e++,e<i.length&&Fr(i.charCodeAt(e))){for(e++;e<i.length&&Fr(i.charCodeAt(e));)e++;I=e}else a=3;return i.substring(h,I)}function u(){let h="",I=e;for(;;){if(e>=n){h+=i.substring(I,e),a=2;break}let y=i.charCodeAt(e);if(y===34){h+=i.substring(I,e),e++;break}if(y===92){if(h+=i.substring(I,e),e++,e>=n){a=2;break}switch(i.charCodeAt(e++)){case 34:h+='"';break;case 92:h+="\\";break;case 47:h+="/";break;case 98:h+="\b";break;case 102:h+="\f";break;case 110:h+=`
`;break;case 114:h+="\r";break;case 116:h+="	";break;case 117:{let C=l(4);C>=0?h+=String.fromCharCode(C):a=4;break}default:a=5}I=e;continue}if(y>=0&&y<=31)if(Os(y)){h+=i.substring(I,e),a=2;break}else a=6;e++}return h}function f(){if(r="",a=0,o=e,e>=n)return o=n,s=17;let h=i.charCodeAt(e);if(gc(h)){do e++,r+=String.fromCharCode(h),h=i.charCodeAt(e);while(gc(h));return s=15}if(Os(h))return e++,r+=String.fromCharCode(h),h===13&&i.charCodeAt(e)===10&&(e++,r+=`
`),s=14;switch(h){case 123:return e++,s=1;case 125:return e++,s=2;case 91:return e++,s=3;case 93:return e++,s=4;case 58:return e++,s=6;case 44:return e++,s=5;case 34:return e++,r=u(),s=10;case 47:{let I=e-1;if(i.charCodeAt(e+1)===47){for(e+=2;e<n&&!Os(i.charCodeAt(e));)e++;return r=i.substring(I,e),s=12}if(i.charCodeAt(e+1)===42){e+=2;let y=n-1,S=!1;for(;e<y;){if(i.charCodeAt(e)===42&&i.charCodeAt(e+1)===47){e+=2,S=!0;break}e++}return S||(e++,a=1),r=i.substring(I,e),s=13}return r+=String.fromCharCode(h),e++,s=16}case 45:if(r+=String.fromCharCode(h),e++,e===n||!Fr(i.charCodeAt(e)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=p(),s=11;default:for(;e<n&&m(h);)e++,h=i.charCodeAt(e);if(o!==e){switch(r=i.substring(o,e),r){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return r+=String.fromCharCode(h),e++,s=16}}function m(h){if(gc(h)||Os(h))return!1;switch(h){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function v(){let h;do h=f();while(h>=12&&h<=15);return h}return{setPosition:c,getPosition:()=>e,scan:t?v:f,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>o,getTokenLength:()=>e-o,getTokenError:()=>a}}function gc(i){return i===32||i===9||i===11||i===12||i===160||i===5760||i>=8192&&i<=8203||i===8239||i===8287||i===12288||i===65279}function Os(i){return i===10||i===13||i===8232||i===8233}function Fr(i){return i>=48&&i<=57}function vf(i,t=[],e=mc.DEFAULT){let n=null,r=[],o=[];function s(l){Array.isArray(r)?r.push(l):n!==null&&(r[n]=l)}return o1(i,{onObjectBegin:()=>{let l={};s(l),o.push(r),r=l,n=null},onObjectProperty:l=>{n=l},onObjectEnd:()=>{r=o.pop()},onArrayBegin:()=>{let l=[];s(l),o.push(r),r=l,n=null},onArrayEnd:()=>{r=o.pop()},onLiteralValue:s,onError:(l,c,p)=>{t.push({error:l,offset:c,length:p})}},e),r[0]}function o1(i,t,e=mc.DEFAULT){let n=i1(i,!1);function r(A){return A?()=>A(n.getTokenOffset(),n.getTokenLength()):()=>!0}function o(A){return A?Z=>A(Z,n.getTokenOffset(),n.getTokenLength()):()=>!0}let s=r(t.onObjectBegin),a=o(t.onObjectProperty),l=r(t.onObjectEnd),c=r(t.onArrayBegin),p=r(t.onArrayEnd),u=o(t.onLiteralValue),f=o(t.onSeparator),m=r(t.onComment),v=o(t.onError),h=e&&e.disallowComments,I=e&&e.allowTrailingComma;function y(){for(;;){let A=n.scan();switch(n.getTokenError()){case 4:S(14);break;case 5:S(15);break;case 3:S(13);break;case 1:h||S(11);break;case 2:S(12);break;case 6:S(16);break}switch(A){case 12:case 13:h?S(10):m();break;case 16:S(1);break;case 15:case 14:break;default:return A}}}function S(A,Z=[],ie=[]){if(v(A),Z.length+ie.length>0){let Ue=n.getToken();for(;Ue!==17;){if(Z.indexOf(Ue)!==-1){y();break}else if(ie.indexOf(Ue)!==-1)break;Ue=y()}}}function C(A){let Z=n.getTokenValue();return A?u(Z):a(Z),y(),!0}function X(){switch(n.getToken()){case 11:{let A=0;try{A=JSON.parse(n.getTokenValue()),typeof A!="number"&&(S(2),A=0)}catch{S(2)}u(A);break}case 7:u(null);break;case 8:u(!0);break;case 9:u(!1);break;default:return!1}return y(),!0}function Fe(){return n.getToken()!==10?(S(3,[],[2,5]),!1):(C(!1),n.getToken()===6?(f(":"),y(),F()||S(4,[],[2,5])):S(5,[],[2,5]),!0)}function rt(){s(),y();let A=!1;for(;n.getToken()!==2&&n.getToken()!==17;){if(n.getToken()===5){if(A||S(4,[],[]),f(","),y(),n.getToken()===2&&I)break}else A&&S(6,[],[]);Fe()||S(4,[],[2,5]),A=!0}return l(),n.getToken()!==2?S(7,[2],[]):y(),!0}function P(){c(),y();let A=!1;for(;n.getToken()!==4&&n.getToken()!==17;){if(n.getToken()===5){if(A||S(4,[],[]),f(","),y(),n.getToken()===4&&I)break}else A&&S(6,[],[]);F()||S(4,[],[4,5]),A=!0}return p(),n.getToken()!==4?S(8,[4],[]):y(),!0}function F(){switch(n.getToken()){case 3:return P();case 1:return rt();case 10:return C(!0);default:return X()}}return y(),n.getToken()===17?e.allowEmptyContent?!0:(S(4,[],[]),!1):F()?(n.getToken()!==17&&S(9,[],[]),!0):(S(4,[],[]),!1)}function bf(i,t){return i.replace(/^~($|\/|\\)/,`${t}$1`)}var l1={format:0,manifestPath:"plugin.json",hookConfigPath:"hooks.json",pluginRootToken:void 0,pluginRootEnvVar:void 0,parseHooks(i,t,e,n,r){return If(i,t,n,r)}},c1={format:1,manifestPath:".claude-plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${CLAUDE_PLUGIN_ROOT}",pluginRootEnvVar:"CLAUDE_PLUGIN_ROOT",parseHooks(i,t,e,n,r){return Sf(i,t,e,n,r,"${CLAUDE_PLUGIN_ROOT}","CLAUDE_PLUGIN_ROOT")}},d1={format:2,manifestPath:".plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${PLUGIN_ROOT}",pluginRootEnvVar:"PLUGIN_ROOT",parseHooks(i,t,e,n,r){return Sf(i,t,e,n,r,"${PLUGIN_ROOT}","PLUGIN_ROOT")}};async function u1(i,t){return await $i(te(i,".plugin","plugin.json"),t)?d1:i.path.split("/").includes(".claude")||await $i(te(i,".claude-plugin","plugin.json"),t)?c1:l1}var hc={paths:[],exclusive:!1};function Ls(i){if(i==null)return hc;if(typeof i=="string"){let t=i.trim();return t?{paths:[t],exclusive:!1}:hc}if(Array.isArray(i))return{paths:i.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0),exclusive:!1};if(typeof i=="object"){let t=i;if(Array.isArray(t.paths)){let e=t.paths.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0),n=t.exclusive===!0;return{paths:e,exclusive:n}}}return hc}function Fs(i,t,e){let n=[];e.exclusive||n.push(te(i,t));for(let r of e.paths){let o=Ft(te(i,r));Zd(o,i)&&n.push(o)}return n}function p1(i){if(!i||typeof i!="object"||Array.isArray(i))return;let t=i;return Object.hasOwn(t,"mcpServers")?t.mcpServers:t}function f1(i){if(!i||typeof i!="object")return;let t=i,e=typeof t.type=="string"?t.type:void 0,n=typeof t.command=="string"?t.command:void 0,r=typeof t.url=="string"?t.url:void 0,o=Array.isArray(t.args)?t.args.filter(u=>typeof u=="string"):void 0,s=t.env&&typeof t.env=="object"?Object.fromEntries(Object.entries(t.env).filter(([,u])=>typeof u=="string"||typeof u=="number"||u===null).map(([u,f])=>[u,f])):void 0,a=typeof t.envFile=="string"?t.envFile:void 0,l=typeof t.cwd=="string"?t.cwd:void 0,c=t.headers&&typeof t.headers=="object"?Object.fromEntries(Object.entries(t.headers).filter(([,u])=>typeof u=="string").map(([u,f])=>[u,f])):void 0,p=t.dev&&typeof t.dev=="object"?t.dev:void 0;if(e!=="ws"){if(e==="stdio"||!e&&n)return n?{type:"stdio",command:n,args:o,env:s,envFile:a,cwd:l,dev:p}:void 0;if(e==="http"||e==="sse"||!e&&r)return r?{type:"http",url:r,headers:c,dev:p}:void 0}}var g1=/[\s&|<>()^;!`"']/;function m1(i,t,e){if(!i.includes(e))return i;if(!g1.test(t))return i.replaceAll(e,t);let n=Dt(e),r=new RegExp(`(["']?)`+n+"([\\w./\\\\~:-]*)","g");return i.replace(r,(o,s,a)=>{let l=t+a;return s?s+l:'"'+l.replace(/"/g,'\\"')+'"'})}function h1(i,t,e,n){let r=a=>a.replaceAll(e,t),o=i.configuration,s;if(o.type==="stdio"){let a={...o};a.command=r(a.command),a.args&&(a.args=a.args.map(r)),a.cwd&&(a.cwd=r(a.cwd)),a.env={...a.env};for(let[l,c]of Object.entries(a.env))typeof c=="string"&&(a.env[l]=r(c));a.env[n]=t,a.envFile&&(a.envFile=r(a.envFile)),s=a}else{let a={...o};a.url=r(a.url),a.headers&&(a.headers=Object.fromEntries(Object.entries(a.headers).map(([l,c])=>[l,r(c)]))),s=a}return{name:i.name,configuration:s,uri:i.uri}}var v1=/\$\{(?![A-Za-z]+:)([A-Z_][A-Z0-9_]*)\}/g;function b1(i){return fl(i,t=>{if(b.isUri(t))return t;if(typeof t=="string"){let e=t.replace(v1,"${env:$1}");return e!==t?e:void 0}})}var y1={SessionStart:"SessionStart",SessionEnd:"SessionEnd",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",PreCompact:"PreCompact",SubagentStart:"SubagentStart",SubagentStop:"SubagentStop",Stop:"Stop",ErrorOccurred:"ErrorOccurred",sessionStart:"SessionStart",sessionEnd:"SessionEnd",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",agentStop:"Stop",subagentStop:"SubagentStop",errorOccurred:"ErrorOccurred"};function I1(i){if(i.type!==void 0&&i.type!=="command")return;let t=typeof i.command=="string"&&i.command.length>0,e=typeof i.bash=="string"&&i.bash.length>0,n=typeof i.powershell=="string"&&i.powershell.length>0,r=typeof i.windows=="string"&&i.windows.length>0,o=typeof i.linux=="string"&&i.linux.length>0,s=typeof i.osx=="string"&&i.osx.length>0;if(!t&&!e&&!n&&!r&&!o&&!s)return;let a=r?i.windows:n?i.powershell:void 0,l=o?i.linux:e?i.bash:void 0,c=s?i.osx:e?i.bash:void 0,p=typeof i.timeout=="number"?i.timeout:typeof i.timeoutSec=="number"?i.timeoutSec:void 0;return{...t&&{command:i.command},...a&&{windows:a},...l&&{linux:l},...c&&{osx:c},...typeof i.env=="object"&&i.env!==null&&{env:i.env},...p!==void 0&&{timeout:p}}}function yf(i,t,e){let n=I1(i);if(!n)return;let r,o=typeof i.cwd=="string"?i.cwd:void 0;if(o){let s=bf(o,e);Xn(s)?r=b.file(s):t&&(r=te(t,s))}else r=t;return{...n,cwd:r}}function S1(i,t,e){if(!i||typeof i!="object")return[];let n=i,r=[],o=n.hooks;if(o!==void 0&&Array.isArray(o))for(let s of o){if(!s||typeof s!="object")continue;let a=yf(s,t,e);a&&r.push(a)}else{let s=yf(n,t,e);s&&r.push(s)}return r}function If(i,t,e,n){if(!t||typeof t!="object")return[];let r=t;if(r.disableAllHooks===!0)return[];let o=r.hooks;if(!o||typeof o!="object")return[];let s=o,a=[];for(let l of Object.keys(s)){let c=y1[l];if(!c)continue;let p=s[l];if(!Array.isArray(p))continue;let u=[];for(let f of p)u.push(...S1(f,e,n));u.length>0&&a.push({type:c,commands:u,uri:i,originalId:l})}return a}function Sf(i,t,e,n,r,o,s){let a=e.fsPath,l=t,c=u=>{for(let f of["command","windows","linux","osx"])typeof u[f]=="string"&&(u[f]=m1(u[f],a,o));(!u.env||typeof u.env!="object")&&(u.env={}),u.env[s]=a};for(let u of Object.values(l.hooks??{}))if(Array.isArray(u))for(let f of u){if(!f||typeof f!="object")continue;let m=f;if(Array.isArray(m.hooks))for(let v of m.hooks)c(v);else c(m)}return If(i,fl(t,u=>typeof u=="string"?u.replaceAll(o,e.fsPath):void 0),n,r)}async function vc(i,t){try{let e=await t.readFile(i);return vf(e.value.toString())}catch{return}}async function $i(i,t){try{return await t.resolve(i),!0}catch{return!1}}var Us=".md";async function T1(i,t,e){let n=new Set,r=[],o=(s,a)=>{n.has(s)||(n.add(s),r.push({uri:a,name:s}))};for(let s of t){let a=b.joinPath(s,"SKILL.md");if(await $i(a,e)){o(Ee(s),a);continue}let l;try{l=await e.resolve(s)}catch{continue}if(!(!l.isDirectory||!l.children))for(let c of l.children){let p=b.joinPath(c.resource,"SKILL.md");await $i(p,e)&&o(Ee(c.resource),p)}}if(r.length===0){let s=b.joinPath(i,"SKILL.md");await $i(s,e)&&o(Ee(i),s)}return r.sort((s,a)=>s.name.localeCompare(a.name)),r}async function x1(i,t){let e=new Set,n=[],r=(o,s)=>{e.has(o)||(e.add(o),n.push({uri:s,name:o}))};for(let o of i){let s;try{s=await t.resolve(o)}catch{continue}if(s.isFile&&tl(o).toLowerCase()===Us){r(Ee(o).slice(0,-Us.length),o);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children)!a.isFile||tl(a.resource).toLowerCase()!==Us||r(Ee(a.resource).slice(0,-Us.length),a.resource)}return n.sort((o,s)=>o.name.localeCompare(s.name)),n}async function _1(i,t,e,n,r,o){for(let s of t){let a=await vc(s,n);if(a)return e.parseHooks(s,a,i,r,o)}return[]}async function E1(i,t,e,n){let r=new Map;for(let o of i){let s=await vc(o,n);for(let a of Tf(o,s,t,e))r.has(a.name)||r.set(a.name,a)}return[...r.values()].sort((o,s)=>o.name.localeCompare(s.name))}function Tf(i,t,e,n){let r=p1(t);if(!r)return[];let o=[];for(let[s,a]of Object.entries(r)){let l=f1(a);if(!l)continue;let c={name:s,configuration:l,uri:i};n.pluginRootToken&&n.pluginRootEnvVar&&(c=h1(c,e,n.pluginRootToken,n.pluginRootEnvVar)),c=b1(c),o.push(c)}return o}async function xf(i,t,e,n){let r=await u1(i,t),o=await vc(te(i,r.manifestPath),t),s=o&&typeof o=="object"?o:void 0,a=Fs(i,r.hookConfigPath,Ls(s?.hooks)),l=Fs(i,".mcp.json",Ls(s?.mcpServers)),c=Fs(i,"skills",Ls(s?.skills)),p=Fs(i,"agents",Ls(s?.agents)),u=[],f=s?.mcpServers;f&&typeof f=="object"&&!Array.isArray(f)&&!We(f,{paths:!0})&&(u=Tf(te(i,r.manifestPath),{mcpServers:f},i.fsPath,r));let m=[],v=s?.hooks;if(v&&typeof v=="object"&&!Array.isArray(v)&&!We(v,{paths:!0})){let C=te(i,r.manifestPath);m=r.parseHooks(C,{hooks:v},i,e,n)}let[h,I,y,S]=await Promise.all([m.length>0?Promise.resolve(m):_1(i,a,r,t,e,n),u.length>0?Promise.resolve(u):E1(l,i.fsPath,r,t),T1(i,c,t),x1(p,t)]);return{hooks:h,mcpServers:I,skills:y,agents:S}}var Ns=re("agentPluginManager");var Ur=re("sessionDataService"),Nr="session.db";import*as Ef from"child_process";var Ws=re("agentHostGitService");function _f(i){return i==="main"?0:i==="master"?1:2}function C1(i,t){let e=t?.query?.toLowerCase(),n=e?i.filter(r=>r.toLowerCase().includes(e)):[...i];return n.sort((r,o)=>_f(r)-_f(o)),t?.limit?n.slice(0,t.limit):n}var Ms=class{async isInsideWorkTree(t){return(await this._runGit(t,["rev-parse","--is-inside-work-tree"]))?.trim()==="true"}async getCurrentBranch(t){return(await this._runGit(t,["branch","--show-current"]))?.trim()||(await this._runGit(t,["rev-parse","--short","HEAD"]))?.trim()||void 0}async getDefaultBranch(t){let e=(await this._runGit(t,["symbolic-ref","refs/remotes/origin/HEAD"]))?.trim();if(e){if(!e.startsWith("refs/remotes/origin/"))return e;let n=e.substring(20);return await this._runGit(t,["show-ref","--verify","--quiet",`refs/heads/${n}`])!==void 0?n:`origin/${n}`}}async getBranches(t,e){let n=["for-each-ref","--format=%(refname:short)","--sort=-committerdate"];n.push("refs/heads");let r=await this._runGit(t,n);if(!r)return[];let o=r.split(/\r?\n/g).map(s=>s.trim()).filter(s=>s.length>0);return C1(o,e)}async getRepositoryRoot(t){let e=(await this._runGit(t,["rev-parse","--show-toplevel"]))?.trim();return e?b.file(e):void 0}async getWorktreeRoots(t){let e=await this._runGit(t,["worktree","list","--porcelain"]);return e?e.split(/\r?\n/g).filter(n=>n.startsWith("worktree ")).map(n=>b.file(n.substring(9))):[]}async addWorktree(t,e,n,r){await this._runGit(t,["worktree","add","-b",n,e.fsPath,r],{timeout:3e4,throwOnError:!0})}async removeWorktree(t,e){await this._runGit(t,["worktree","remove","--force",e.fsPath],{timeout:3e4,throwOnError:!0})}_runGit(t,e,n){return new Promise((r,o)=>{Ef.execFile("git",[...e],{cwd:t.fsPath,timeout:n?.timeout??5e3},(s,a,l)=>{if(s){if(n?.throwOnError){o(new Error(l||s.message));return}r(void 0);return}r(a)})})}};var R1=re("environmentService"),Bs=R1;var w1=new Set(["edit","create","apply_patch","git_apply_patch"]);function Br(i){return w1.has(i)}function $s(i){if(typeof i=="string")try{i=JSON.parse(i)}catch{return}return i?.path}var Vi=new Set(["bash","powershell"]),P1=new Set(["task"]),A1=new Set(["report_intent"]);function qi(i){return A1.has(i)}function bc(i){return Vi.has(i)}function Mr(i,t){return i.length>t?i.substring(0,t-3)+"...":i}function Wr(i){let t=b.file(i);return`[${Ee(t)}](${t})`}function ct(i){return{markdown:i}}function Ht(i){switch(i){case"bash":return g(1875,null);case"powershell":return g(1883,null);case"read_bash":case"read_powershell":return g(1884,null);case"write_bash":case"write_powershell":return g(1888,null);case"bash_shutdown":return g(1876,null);case"list_bash":case"list_powershell":return g(1881,null);case"view":return g(1885,null);case"edit":return g(1878,null);case"create":return g(1877,null);case"grep":return g(1880,null);case"glob":return g(1879,null);case"apply_patch":case"git_apply_patch":return g(1882,null);case"web_search":return g(1887,null);case"web_fetch":return g(1886,null);case"ask_user":return g(1874,null);default:return i}}function fn(i,t,e){if(Vi.has(i)){let n=e;if(n?.command){let r=n.command.split(`
`)[0];return ct(g(1871,null,jt(Mr(r,80))))}return g(1870,null,t)}switch(i){case"view":{let n=e;return n?.path?ct(g(1873,null,Wr(n.path))):g(1872,null)}case"edit":{let n=e;return n?.path?ct(g(1864,null,Wr(n.path))):g(1863,null)}case"create":{let n=e;return n?.path?ct(g(1862,null,Wr(n.path))):g(1861,null)}case"grep":{let n=e;return n?.pattern?ct(g(1869,null,jt(Mr(n.pattern,80)))):g(1868,null)}case"glob":{let n=e;return n?.pattern?ct(g(1867,null,jt(Mr(n.pattern,80)))):g(1866,null)}default:return g(1865,null,t)}}function Vs(i,t,e,n){if(!n)return g(1851,null,t);if(Vi.has(i)){let r=e;if(r?.command){let o=r.command.split(`
`)[0];return ct(g(1858,null,jt(Mr(o,80))))}return g(1857,null,t)}switch(i){case"view":{let r=e;return r?.path?ct(g(1860,null,Wr(r.path))):g(1859,null)}case"edit":{let r=e;return r?.path?ct(g(1850,null,Wr(r.path))):g(1849,null)}case"create":{let r=e;return r?.path?ct(g(1848,null,Wr(r.path))):g(1847,null)}case"grep":{let r=e;return r?.pattern?ct(g(1856,null,jt(Mr(r.pattern,80)))):g(1855,null)}case"glob":{let r=e;return r?.pattern?ct(g(1854,null,jt(Mr(r.pattern,80)))):g(1853,null)}default:return g(1852,null,t)}}function qs(i,t,e){if(!(!t&&!e)){if(Vi.has(i)){let n=t,r=n?.command??n?.args;return typeof r=="string"?r:typeof r=="object"&&r!==null&&We(r,{command:!0})?r.command:e}switch(i){case"grep":return t?.pattern??e;default:if(t)try{return JSON.stringify(t,null,2)}catch{return e}return e}}}function Ks(i){if(Vi.has(i))return"terminal";if(P1.has(i))return"subagent"}function zs(i){if(!i)return{};let t=typeof i.agent_type=="string"&&i.agent_type.length>0?i.agent_type:void 0,e=typeof i.description=="string"&&i.description.length>0?i.description:void 0;return{agentName:t,description:e}}function js(i){return i==="powershell"?"powershell":"shellscript"}function Et(i){try{return JSON.stringify(i)}catch{return}}function Bn(i){return typeof i=="string"?i:void 0}function Cf(i){let t=Bn(i.path)??Bn(i.fileName),e=Bn(i.fullCommandText),n=Bn(i.intention),r=Bn(i.serverName),o=Bn(i.toolName);switch(i.kind){case"shell":return{confirmationTitle:g(1845,null),invocationMessage:n??fn("bash",Ht("bash"),e?{command:e}:void 0),toolInput:e,permissionKind:"shell",permissionPath:t};case"custom-tool":{let s=typeof i.args=="object"&&i.args!==null?i.args:void 0,a=typeof s?.command=="string"?s.command:void 0,l=Bn(i.toolName);return a&&l&&bc(l)?{confirmationTitle:g(1845,null),invocationMessage:fn(l,Ht(l),{command:a}),toolInput:a,permissionKind:"shell",permissionPath:t}:{confirmationTitle:o??g(1842,null),invocationMessage:g(1841,null),toolInput:Et(s||i),permissionKind:i.kind,permissionPath:t}}case"write":return{confirmationTitle:g(1846,null),invocationMessage:fn("edit",Ht("edit"),t?{path:t}:void 0),toolInput:Et(t?{path:t}:i)??void 0,permissionKind:"write",permissionPath:t};case"mcp":{let s=o??g(1843,null);return{confirmationTitle:r?`${r}: ${s}`:s,invocationMessage:r?`${r}: ${s}`:s,toolInput:Et({serverName:r,toolName:o})??void 0,permissionKind:"mcp",permissionPath:t}}case"read":return{confirmationTitle:g(1844,null),invocationMessage:n??fn("view",Ht("view"),t?{path:t}:void 0),toolInput:Et(t?{path:t,intention:n}:i)??void 0,permissionKind:"read",permissionPath:t};default:return{confirmationTitle:g(1842,null),invocationMessage:g(1841,null),toolInput:Et(i)??void 0,permissionKind:i.kind,permissionPath:t}}}function Hs(i){try{return JSON.stringify(i)}catch{return}}async function Rf(i,t,e){let n=[],r=new Map,o=[];for(let l of e)if(l.type==="tool.execution_start"){let c=l.data;if(qi(c.toolName))continue;let p=c.arguments!==void 0?Hs(c.arguments):void 0,u;if(p)try{u=JSON.parse(p)}catch{}r.set(c.toolCallId,{toolName:c.toolName,parameters:u}),Br(c.toolName)&&o.push(c.toolCallId)}let s;if(t&&o.length>0)try{let l=await t.getFileEdits(o);if(l.length>0){s=new Map;for(let c of l){let p=s.get(c.toolCallId);p||(p=[],s.set(c.toolCallId,p)),p.push(c)}}}catch{}let a=i.toString();for(let l of e)if(l.type==="assistant.message"||l.type==="user.message"){let c=l.data;n.push({session:i,type:"message",role:l.type==="user.message"?"user":"assistant",messageId:c?.messageId??c?.interactionId??"",content:c?.content??"",toolRequests:c?.toolRequests?.map(p=>({toolCallId:p.toolCallId,name:p.name,arguments:p.arguments!==void 0?Hs(p.arguments):void 0,type:p.type})),reasoningOpaque:c?.reasoningOpaque,reasoningText:c?.reasoningText,encryptedContent:c?.encryptedContent,parentToolCallId:c?.parentToolCallId})}else if(l.type==="tool.execution_start"){let c=l.data;if(qi(c.toolName))continue;let p=r.get(c.toolCallId),u=Ht(c.toolName),f=Ks(c.toolName),m=c.arguments!==void 0?Hs(c.arguments):void 0,v=f==="subagent"?zs(p?.parameters):void 0;n.push({session:i,type:"tool_start",toolCallId:c.toolCallId,toolName:c.toolName,displayName:u,invocationMessage:fn(c.toolName,u,p?.parameters),toolInput:qs(c.toolName,p?.parameters,m),toolKind:f,language:f==="terminal"?js(c.toolName):void 0,toolArguments:m,subagentAgentName:v?.agentName,subagentDescription:v?.description,mcpServerName:c.mcpServerName,mcpToolName:c.mcpToolName,parentToolCallId:c.parentToolCallId})}else if(l.type==="tool.execution_complete"){let c=l.data,p=r.get(c.toolCallId);if(!p)continue;r.delete(c.toolCallId);let u=Ht(p.toolName),f=c.error?.message??c.result?.content,m=[];f!==void 0&&m.push({type:"text",text:f});let v=s?.get(c.toolCallId);if(v)for(let h of v){let I=h.kind==="rename"&&h.originalPath?b.file(h.originalPath).toString():b.file(h.filePath).toString(),y=b.file(h.filePath).toString(),S=h.kind!=="create",C=h.kind!=="delete";m.push({type:"fileEdit",before:S?{uri:I,content:{uri:pn(a,h.toolCallId,h.filePath,"before")}}:void 0,after:C?{uri:y,content:{uri:pn(a,h.toolCallId,h.filePath,"after")}}:void 0,diff:h.addedLines!==void 0||h.removedLines!==void 0?{added:h.addedLines,removed:h.removedLines}:void 0})}n.push({session:i,type:"tool_complete",toolCallId:c.toolCallId,result:{success:c.success,pastTenseMessage:Vs(p.toolName,u,p.parameters,c.success),content:m.length>0?m:void 0,error:c.error},isUserRequested:c.isUserRequested,toolTelemetry:c.toolTelemetry!==void 0?Hs(c.toolTelemetry):void 0,parentToolCallId:c.parentToolCallId})}else if(l.type==="subagent.started"){let c=l.data;n.push({session:i,type:"subagent_started",toolCallId:c.toolCallId,agentName:c.agentName,agentDisplayName:c.agentDisplayName,agentDescription:c.agentDescription})}return n}var Ki=class{constructor(t){this.type=1,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=t}},gn=class{constructor(t){this.type=2,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=t,this.entries=new Map}},Gs=class extends L{constructor(){super(...arguments);this.memoryFdCounter=0;this.fdMemory=new Map;this._onDidChangeCapabilities=this._register(new x);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._capabilities=525318;this.root=new gn("");this._onDidChangeFile=this._register(new x);this.onDidChangeFile=this._onDidChangeFile.event;this._bufferedChanges=[]}get capabilities(){return this._capabilities}setReadOnly(e){let n=!!(this._capabilities&2048);e!==n&&(this._capabilities=525314|(e?2048:0),this._onDidChangeCapabilities.fire())}async stat(e){return this._lookup(e,!1)}async readdir(e){let n=this._lookupAsDirectory(e,!1),r=[];return n.entries.forEach((o,s)=>r.push([s,o.type])),r}async readFile(e){let n=this._lookupAsFile(e,!1).data;if(n)return n;throw Y("file not found","EntryNotFound")}readFileStream(e){let n=this._lookupAsFile(e,!1).data,r=Nt(o=>_.concat(o.map(s=>_.wrap(s))).buffer);return r.end(n),r}async writeFile(e,n,r){let o=Ee(e),s=this._lookupParentDirectory(e),a=s.entries.get(o);if(a instanceof gn)throw Y("file is directory","EntryIsADirectory");if(!a&&!r.create)throw Y("file not found","EntryNotFound");if(a&&r.create&&!r.overwrite)throw Y("file exists already","EntryExists");if(a||(a=new Ki(o),s.entries.set(o,a),this._fireSoon({type:1,resource:e})),a.mtime=Date.now(),r.append){a.size+=n.byteLength;let l=a.data??new Uint8Array(0),c=new Uint8Array(l.byteLength+n.byteLength);c.set(l,0),c.set(n,l.byteLength),a.data=c}else a.size=n.byteLength,a.data=n;this._fireSoon({type:0,resource:e})}open(e,n){let r=this._lookup(e,!0),o=Vt(n),s=o&&!!n.append;if(r){if(r instanceof gn)throw Y("file is directory","EntryIsADirectory")}else{if(!o)throw Y("file not found","EntryNotFound");let l=Ee(e),c=this._lookupParentDirectory(e);r=new Ki(l),r.data=new Uint8Array(0),c.entries.set(l,r),this._fireSoon({type:1,resource:e})}r.data||(r.data=new Uint8Array(0));let a=this.memoryFdCounter++;return this.fdMemory.set(a,{file:r,resource:e,write:o,append:s}),Promise.resolve(a)}close(e){let n=this.fdMemory.get(e);return n?.write&&(n.file.mtime=Date.now(),n.file.size=n.file.data?.byteLength??0,this._fireSoon({type:0,resource:n.resource})),this.fdMemory.delete(e),Promise.resolve()}read(e,n,r,o,s){let a=this.fdMemory.get(e);if(!a)throw Y("No file with that descriptor open","Unavailable");if(!a.file.data)return Promise.resolve(0);let l=_.wrap(a.file.data).slice(n,n+s);return r.set(l.buffer,o),Promise.resolve(l.byteLength)}write(e,n,r,o,s){let a=this.fdMemory.get(e);if(!a)throw Y("No file with that descriptor open","Unavailable");let l=_.wrap(r).slice(o,o+s);a.file.data??=new Uint8Array(0);let c=a.append?a.file.data.byteLength:n,p=c+l.byteLength;if(p>a.file.data.byteLength){let u=new Uint8Array(p);u.set(a.file.data,0),a.file.data=u}return a.file.data.set(l.buffer,c),Promise.resolve(l.byteLength)}async rename(e,n,r){if(!r.overwrite&&this._lookup(n,!0))throw Y("file exists already","EntryExists");let o=this._lookup(e,!1),s=this._lookupParentDirectory(e),a=this._lookupParentDirectory(n),l=Ee(n);s.entries.delete(o.name),o.name=l,a.entries.set(l,o),this._fireSoon({type:2,resource:e},{type:1,resource:n})}async delete(e,n){let r=on(e),o=Ee(e),s=this._lookupAsDirectory(r,!1);s.entries.delete(o)&&(s.mtime=Date.now(),s.size-=1,this._fireSoon({type:0,resource:r},{resource:e,type:2}))}async mkdir(e){if(this._lookup(e,!0))throw Y("file exists already","EntryExists");let n=Ee(e),r=on(e),o=this._lookupAsDirectory(r,!1),s=new gn(n);o.entries.set(s.name,s),o.mtime=Date.now(),o.size+=1,this._fireSoon({type:0,resource:r},{type:1,resource:e})}_lookup(e,n){let r=e.path.split("/"),o=this.root;for(let s of r){if(!s)continue;let a;if(o instanceof gn&&(a=o.entries.get(s)),!a){if(n)return;throw Y("file not found","EntryNotFound")}o=a}return o}_lookupAsDirectory(e,n){let r=this._lookup(e,n);if(r instanceof gn)return r;throw Y("file not a directory","EntryNotADirectory")}_lookupAsFile(e,n){let r=this._lookup(e,n);if(r instanceof Ki)return r;throw Y("file is a directory","EntryIsADirectory")}_lookupParentDirectory(e){let n=on(e);return this._lookupAsDirectory(n,!1)}watch(e,n){return L.None}_fireSoon(...e){this._bufferedChanges.push(...e),this._fireSoonHandle&&clearTimeout(this._fireSoonHandle),this._fireSoonHandle=setTimeout(()=>{this._onDidChangeFile.fire(this._bufferedChanges),this._bufferedChanges.length=0},5)}dispose(){super.dispose(),this.fdMemory.clear()}};var wf="pending-edit-content";function Pf(i,t,e){return b.from({scheme:wf,authority:sn(_.fromString(i)).toString(),path:`/${encodeURIComponent(t)}/${sn(_.fromString(e))}`})}function Af(i){let t=new Gs,e=i.registerProvider(wf,t);return{dispose(){e.dispose(),t.dispose()}}}var k1=".copilot",kf=q(k1,"session-state");function D1(i){let t=process.env.XDG_STATE_HOME;return t?q(t,kf):q(i,kf)}var $r=class extends L{constructor(e,n,r,o,s,a){super();this._instantiationService=n;this._logService=r;this._fileService=s;this._environmentService=a;this._activeToolCalls=new Map;this._pendingPermissions=new Map;this._pendingUserInputs=new Map;this._turnId="";this._pendingClientToolCalls=new Map;this._pendingEditContentUris=new Map;this.sessionId=e.rawSessionId,this.sessionUri=e.sessionUri,this._onDidSessionProgress=e.onDidSessionProgress,this._wrapperFactory=e.wrapperFactory,this._shellManager=e.shellManager,this._appliedSnapshot=e.clientSnapshot??{clientId:"",tools:[],plugins:[]},this._clientToolNames=new Set(this._appliedSnapshot.tools.map(l=>l.name)),this._databaseRef=o.openDatabase(e.sessionUri),this._register(w(()=>this._databaseRef.dispose())),this._editTracker=this._instantiationService.createInstance(wr,e.sessionUri.toString(),this._databaseRef.object),this._register(w(()=>this._denyPendingPermissions())),this._register(w(()=>this._shellManager?.dispose())),this._register(w(()=>this._cancelPendingUserInputs())),this._shellManager&&this._register(this._shellManager.onDidAssociateTerminal(({toolCallId:l,terminalUri:c,displayName:p})=>{let u=this._activeToolCalls.get(l);u&&(u.content.push({type:"terminal",resource:c,title:p}),this._onDidSessionProgress.fire({session:this.sessionUri,type:"tool_content_changed",toolCallId:l,content:u.content}))})),this._register(w(()=>this._cancelPendingClientToolCalls()))}get appliedSnapshot(){return this._appliedSnapshot}createClientSdkTools(){let e=this._appliedSnapshot.tools;return e.length===0?[]:e.map(n=>({name:n.name,description:n.description??"",parameters:n.inputSchema??{type:"object",properties:{}},handler:async(r,{toolCallId:o})=>{try{let s=this._pendingClientToolCalls.get(o);s||(s=new Be,this._pendingClientToolCalls.set(o,s));let a=await s.p;return this._pendingClientToolCalls.delete(o),a}catch(s){throw this._logService.error(s,`[Copilot:${this.sessionId}] Failed in client tool handler: tool=${n.name}, toolCallId=${o}`),s}}}))}handleClientToolCallComplete(e,n){let r=this._pendingClientToolCalls.get(e);r||(r=new Be,this._pendingClientToolCalls.set(e,r));let o=n.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
`)??"",s=n.content?.filter(a=>a.type==="embeddedResource").map(a=>{let l=a;return{data:l.data,mimeType:l.contentType,type:l.contentType}});n.success?r.complete({textResultForLlm:o,resultType:"success",binaryResultsForLlm:s?.length?s:void 0}):r.complete({textResultForLlm:o||n.error?.message||"Tool call failed",resultType:"failure",error:n.error?.message,binaryResultsForLlm:s?.length?s:void 0})}async initializeSession(){this._wrapper=this._register(await this._wrapperFactory({onPermissionRequest:e=>this.handlePermissionRequest(e),onUserInputRequest:(e,n)=>this.handleUserInputRequest(e,n),clientTools:this.createClientSdkTools(),hooks:{onPreToolUse:e=>this._handlePreToolUse(e),onPostToolUse:e=>this._handlePostToolUse(e)}})),this._subscribeToEvents(),this._subscribeForLogging()}async send(e,n,r){r&&(this._turnId=r),this._logService.info(`[Copilot:${this.sessionId}] sendMessage called: "${e.substring(0,100)}${e.length>100?"...":""}" (${n?.length??0} attachments)`);let o=n?.map(s=>s.type==="selection"?{type:"selection",filePath:s.path,displayName:s.displayName??s.path,text:s.text,selection:s.selection}:{type:s.type,path:s.path,displayName:s.displayName});o?.length&&this._logService.trace(`[Copilot:${this.sessionId}] Attachments: ${JSON.stringify(o.map(s=>({type:s.type,path:s.type==="selection"?s.filePath:s.path})))}`),await this._wrapper.session.send({prompt:e,attachments:o}),this._logService.info(`[Copilot:${this.sessionId}] session.send() returned`)}async sendSteering(e){this._logService.info(`[Copilot:${this.sessionId}] Sending steering message: "${e.userMessage.text.substring(0,100)}"`);try{await this._wrapper.session.send({prompt:e.userMessage.text,mode:"immediate"}),this._onDidSessionProgress.fire({session:this.sessionUri,type:"steering_consumed",id:e.id})}catch(n){this._logService.error(`[Copilot:${this.sessionId}] Steering message failed`,n)}}async getMessages(){let e=await this._wrapper.session.getMessages(),n;try{n=this._databaseRef.object}catch{}return Rf(this.sessionUri,n,e)}async abort(){this._logService.info(`[Copilot:${this.sessionId}] Aborting session...`),this._denyPendingPermissions(),await this._wrapper.session.abort()}async destroySession(){await this._wrapper.session.destroy()}async setModel(e,n){this._logService.info(`[Copilot:${this.sessionId}] Changing model to: ${e}`),await this._wrapper.session.setModel(e,{reasoningEffort:n})}async handlePermissionRequest(e){this._logService.info(`[Copilot:${this.sessionId}] Permission request: kind=${e.kind}`);try{let n=e.toolCallId;if(!n)return this._logService.warn(`[Copilot:${this.sessionId}] Permission request without toolCallId, auto-denying: kind=${e.kind}`),{kind:"denied-interactively-by-user"};let r=this._getInternalSessionResourcePath(e);if(r)return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving internal session resource ${r}`),{kind:"approved"};this._logService.info(`[Copilot:${this.sessionId}] Requesting confirmation for tool call: ${n}`);let o=new Be;this._pendingPermissions.set(n,o);let{confirmationTitle:s,invocationMessage:a,toolInput:l,permissionKind:c,permissionPath:p}=Cf(e),u=await this._buildEditsForPermission(e,n);if(!this._pendingPermissions.has(n))return{kind:"denied-interactively-by-user"};this._onDidSessionProgress.fire({session:this.sessionUri,type:"tool_ready",toolCallId:n,invocationMessage:a,toolInput:l,confirmationTitle:s,permissionKind:c,permissionPath:p,edits:u});let f=await o.p;return this._logService.info(`[Copilot:${this.sessionId}] Permission response: toolCallId=${n}, approved=${f}`),{kind:f?"approved":"denied-interactively-by-user"}}catch(n){throw this._logService.error(n,`[Copilot:${this.sessionId}] Failed to handle permission request: kind=${e.kind}, toolCallId=${e.toolCallId??"missing"}`),n}}_getInternalSessionResourcePath(e){let n;if(e.kind==="read"?n=typeof e.path=="string"?e.path:void 0:e.kind==="write"&&(n=typeof e.fileName=="string"?e.fileName:void 0),!n)return;let r=Ft(b.file(D1(this._environmentService.userHome.fsPath))),o=Ft(b.joinPath(r,this.sessionId));if(!It.isEqualOrParent(o,r))return;let s=Ft(b.file(n));return It.isEqualOrParent(s,o)?n:void 0}async _buildEditsForPermission(e,n){if(e.kind!=="write")return;let r=typeof e.fileName=="string"?e.fileName:void 0,o=typeof e.newFileContents=="string"?e.newFileContents:void 0;if(!r||o===void 0)return;let s=b.file(r),a=s.toString(),l=!1;try{l=await this._fileService.exists(s)}catch(f){this._logService.warn(`[Copilot:${this.sessionId}] Failed to check file for edit preview: ${r}`,f)}let c=Pf(this.sessionUri.toString(),n,r);try{await this._fileService.writeFile(c,_.fromString(o))}catch(f){this._logService.warn(`[Copilot:${this.sessionId}] Failed to write pending edit content for ${r}`,f);return}if(!this._pendingPermissions.has(n)){this._fileService.del(c).catch(f=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to delete orphaned pending edit content: ${c.toString()}`,f)});return}this._pendingEditContentUris.set(n,c);let p=typeof e.diff=="string"?O1(e.diff):void 0;return{items:[{...l?{before:{uri:a,content:{uri:a}}}:{},after:{uri:a,content:{uri:c.toString()}},...p?{diff:p}:{}}]}}respondToPermissionRequest(e,n){let r=this._pendingPermissions.get(e);return r?(this._pendingPermissions.delete(e),this._deletePendingEditContent(e),r.complete(n),!0):!1}async handleUserInputRequest(e,n){let r=e.question.substring(0,100);try{let o=ne(),s=ne();this._logService.info(`[Copilot:${this.sessionId}] User input request: requestId=${o}, question="${r}"`);let a=new Be;this._pendingUserInputs.set(o,{deferred:a,questionId:s});let l={id:o,message:e.question,questions:[e.choices&&e.choices.length>0?{kind:"single-select",id:s,message:e.question,required:!0,options:e.choices.map(f=>({id:f,label:f})),allowFreeformInput:e.allowFreeform??!0}:{kind:"text",id:s,message:e.question,required:!0}]};this._onDidSessionProgress.fire({session:this.sessionUri,type:"user_input_request",request:l});let c=await a.p;if(this._logService.info(`[Copilot:${this.sessionId}] User input response: requestId=${o}, response=${c.response}`),c.response!=="accept"||!c.answers)return{answer:"",wasFreeform:!0};let p=c.answers[s];if(!p||p.state==="skipped")return{answer:"",wasFreeform:!0};let{value:u}=p;if(u.kind==="text")return{answer:u.value,wasFreeform:!0};if(u.kind==="selected"){let f=!e.choices?.includes(u.value);return{answer:u.value,wasFreeform:f}}return{answer:"",wasFreeform:!0}}catch(o){throw this._logService.error(o,`[Copilot:${this.sessionId}] Failed to handle user input request: question="${r}"`),o}}respondToUserInputRequest(e,n,r){let o=this._pendingUserInputs.get(e);return o?(this._pendingUserInputs.delete(e),o.deferred.complete({response:n,answers:r}),!0):!1}async _handlePreToolUse(e){try{if(Br(e.toolName)){let n=$s(e.toolArgs);n&&await this._editTracker.trackEditStart(n)}}catch(n){throw this._logService.error(n,`[Copilot:${this.sessionId}] Failed in onPreToolUse: tool=${e.toolName}`),n}}async _handlePostToolUse(e){try{if(Br(e.toolName)){let n=$s(e.toolArgs);n&&await this._editTracker.completeEdit(n)}}catch(n){throw this._logService.error(n,`[Copilot:${this.sessionId}] Failed in onPostToolUse: tool=${e.toolName}`),n}}_subscribeToEvents(){let e=this._wrapper,n=this.sessionId,r=this.sessionUri;this._register(e.onUserMessage(o=>{this._turnId&&this._databaseRef.object.setTurnEventId(this._turnId,o.id)})),this._register(e.onMessageDelta(o=>{this._logService.trace(`[Copilot:${n}] delta: ${o.data.deltaContent}`),this._onDidSessionProgress.fire({session:r,type:"delta",messageId:o.data.messageId,content:o.data.deltaContent,parentToolCallId:o.data.parentToolCallId})})),this._register(e.onMessage(o=>{this._logService.info(`[Copilot:${n}] Full message received: ${o.data.content.length} chars`),this._onDidSessionProgress.fire({session:r,type:"message",role:"assistant",messageId:o.data.messageId,content:o.data.content,toolRequests:o.data.toolRequests?.map(s=>({toolCallId:s.toolCallId,name:s.name,arguments:s.arguments!==void 0?Et(s.arguments):void 0,type:s.type})),reasoningOpaque:o.data.reasoningOpaque,reasoningText:o.data.reasoningText,encryptedContent:o.data.encryptedContent,parentToolCallId:o.data.parentToolCallId})})),this._register(e.onToolStart(o=>{if(qi(o.data.toolName)){this._logService.trace(`[Copilot:${n}] Tool started (hidden): ${o.data.toolName}`);return}this._logService.info(`[Copilot:${n}] Tool started: ${o.data.toolName}`);let s=o.data.arguments!==void 0?Et(o.data.arguments):void 0,a;if(s)try{a=JSON.parse(s)}catch{}let l=Ht(o.data.toolName);this._activeToolCalls.set(o.data.toolCallId,{toolName:o.data.toolName,displayName:l,parameters:a,content:[]});let c=Ks(o.data.toolName),p=c==="subagent"?zs(a):void 0;this._onDidSessionProgress.fire({session:r,type:"tool_start",toolCallId:o.data.toolCallId,toolName:o.data.toolName,displayName:l,invocationMessage:fn(o.data.toolName,l,a),toolInput:qs(o.data.toolName,a,s),toolKind:c,language:c==="terminal"?js(o.data.toolName):void 0,toolArguments:s,subagentAgentName:p?.agentName,subagentDescription:p?.description,mcpServerName:o.data.mcpServerName,mcpToolName:o.data.mcpToolName,parentToolCallId:o.data.parentToolCallId,toolClientId:this._clientToolNames.has(o.data.toolName)?this._appliedSnapshot.clientId:void 0})})),this._register(e.onToolComplete(async o=>{let s=this._activeToolCalls.get(o.data.toolCallId);if(!s)return;this._logService.info(`[Copilot:${n}] Tool completed: ${o.data.toolCallId}`),this._activeToolCalls.delete(o.data.toolCallId);let a=s.displayName,l=o.data.error?.message??o.data.result?.content,c=[...s.content];l!==void 0&&c.push({type:"text",text:l});let p=Br(s.toolName)?$s(s.parameters):void 0;if(p)try{let u=await this._editTracker.takeCompletedEdit(this._turnId,o.data.toolCallId,p);u&&c.push(u)}catch(u){this._logService.warn(`[Copilot:${n}] Failed to take completed edit`,u)}if(bc(s.toolName)&&this._shellManager){let u=this._shellManager.getTerminalUriForToolCall(o.data.toolCallId);u&&!c.some(f=>f.type==="terminal"&&f.resource===u)&&c.push({type:"terminal",resource:u,title:s.displayName})}this._onDidSessionProgress.fire({session:r,type:"tool_complete",toolCallId:o.data.toolCallId,result:{success:o.data.success,pastTenseMessage:Vs(s.toolName,a,s.parameters,o.data.success),content:c.length>0?c:void 0,error:o.data.error},isUserRequested:o.data.isUserRequested,toolTelemetry:o.data.toolTelemetry!==void 0?Et(o.data.toolTelemetry):void 0,parentToolCallId:o.data.parentToolCallId})})),this._register(e.onIdle(()=>{this._logService.info(`[Copilot:${n}] Session idle`),this._onDidSessionProgress.fire({session:r,type:"idle"})})),this._register(e.onSubagentStarted(o=>{this._logService.info(`[Copilot:${n}] Subagent started: toolCallId=${o.data.toolCallId}, agent=${o.data.agentName}`),this._onDidSessionProgress.fire({session:r,type:"subagent_started",toolCallId:o.data.toolCallId,agentName:o.data.agentName,agentDisplayName:o.data.agentDisplayName,agentDescription:o.data.agentDescription})})),this._register(e.onSessionError(o=>{this._logService.error(`[Copilot:${n}] Session error: ${o.data.errorType} - ${o.data.message}`),this._onDidSessionProgress.fire({session:r,type:"error",errorType:o.data.errorType,message:o.data.message,stack:o.data.stack})})),this._register(e.onUsage(o=>{this._logService.trace(`[Copilot:${n}] Usage: model=${o.data.model}, in=${o.data.inputTokens??"?"}, out=${o.data.outputTokens??"?"}, cacheRead=${o.data.cacheReadTokens??"?"}`),this._onDidSessionProgress.fire({session:r,type:"usage",inputTokens:o.data.inputTokens,outputTokens:o.data.outputTokens,model:o.data.model,cacheReadTokens:o.data.cacheReadTokens})})),this._register(e.onReasoningDelta(o=>{this._logService.trace(`[Copilot:${n}] Reasoning delta: ${o.data.deltaContent.length} chars`),this._onDidSessionProgress.fire({session:r,type:"reasoning",content:o.data.deltaContent})}))}_subscribeForLogging(){let e=this._wrapper,n=this.sessionId;this._register(e.onSessionStart(r=>{this._logService.trace(`[Copilot:${n}] Session started: model=${r.data.selectedModel??"default"}, producer=${r.data.producer}`)})),this._register(e.onSessionResume(r=>{this._logService.trace(`[Copilot:${n}] Session resumed: eventCount=${r.data.eventCount}`)})),this._register(e.onSessionInfo(r=>{this._logService.trace(`[Copilot:${n}] Session info [${r.data.infoType}]: ${r.data.message}`)})),this._register(e.onSessionModelChange(r=>{this._logService.trace(`[Copilot:${n}] Model changed: ${r.data.previousModel??"(none)"} -> ${r.data.newModel}`)})),this._register(e.onSessionHandoff(r=>{this._logService.trace(`[Copilot:${n}] Session handoff: sourceType=${r.data.sourceType}, remoteSessionId=${r.data.remoteSessionId??"(none)"}`)})),this._register(e.onSessionTruncation(r=>{this._logService.trace(`[Copilot:${n}] Session truncation: removed ${r.data.tokensRemovedDuringTruncation} tokens, ${r.data.messagesRemovedDuringTruncation} messages`)})),this._register(e.onSessionSnapshotRewind(r=>{this._logService.trace(`[Copilot:${n}] Snapshot rewind: upTo=${r.data.upToEventId}, eventsRemoved=${r.data.eventsRemoved}`)})),this._register(e.onSessionShutdown(r=>{this._logService.trace(`[Copilot:${n}] Session shutdown: type=${r.data.shutdownType}, premiumRequests=${r.data.totalPremiumRequests}, apiDuration=${r.data.totalApiDurationMs}ms`)})),this._register(e.onSessionUsageInfo(r=>{this._logService.trace(`[Copilot:${n}] Usage info: ${r.data.currentTokens}/${r.data.tokenLimit} tokens, ${r.data.messagesLength} messages`)})),this._register(e.onSessionCompactionStart(()=>{this._logService.trace(`[Copilot:${n}] Compaction started`)})),this._register(e.onSessionCompactionComplete(r=>{this._logService.trace(`[Copilot:${n}] Compaction complete: success=${r.data.success}, tokensRemoved=${r.data.tokensRemoved??"?"}`)})),this._register(e.onUserMessage(r=>{this._logService.trace(`[Copilot:${n}] User message: ${r.data.content.length} chars, ${r.data.attachments?.length??0} attachments`)})),this._register(e.onPendingMessagesModified(()=>{this._logService.trace(`[Copilot:${n}] Pending messages modified`)})),this._register(e.onTurnStart(r=>{this._logService.trace(`[Copilot:${n}] Turn started: ${r.data.turnId}`)})),this._register(e.onIntent(r=>{this._logService.trace(`[Copilot:${n}] Intent: ${r.data.intent}`)})),this._register(e.onReasoning(r=>{this._logService.trace(`[Copilot:${n}] Reasoning: ${r.data.content.length} chars`)})),this._register(e.onTurnEnd(r=>{this._logService.trace(`[Copilot:${n}] Turn ended: ${r.data.turnId}`)})),this._register(e.onAbort(r=>{this._logService.trace(`[Copilot:${n}] Aborted: ${r.data.reason}`)})),this._register(e.onToolUserRequested(r=>{this._logService.trace(`[Copilot:${n}] Tool user-requested: ${r.data.toolName} (${r.data.toolCallId})`)})),this._register(e.onToolPartialResult(r=>{this._logService.trace(`[Copilot:${n}] Tool partial result: ${r.data.toolCallId} (${r.data.partialOutput.length} chars)`)})),this._register(e.onToolProgress(r=>{this._logService.trace(`[Copilot:${n}] Tool progress: ${r.data.toolCallId} - ${r.data.progressMessage}`)})),this._register(e.onSkillInvoked(r=>{this._logService.trace(`[Copilot:${n}] Skill invoked: ${r.data.name} (${r.data.path})`)})),this._register(e.onSubagentStarted(r=>{this._logService.trace(`[Copilot:${n}] Subagent started: ${r.data.agentName} (${r.data.agentDisplayName})`)})),this._register(e.onSubagentCompleted(r=>{this._logService.trace(`[Copilot:${n}] Subagent completed: ${r.data.agentName}`)})),this._register(e.onSubagentFailed(r=>{this._logService.error(`[Copilot:${n}] Subagent failed: ${r.data.agentName} - ${r.data.error}`)})),this._register(e.onSubagentSelected(r=>{this._logService.trace(`[Copilot:${n}] Subagent selected: ${r.data.agentName}`)})),this._register(e.onHookStart(r=>{this._logService.trace(`[Copilot:${n}] Hook started: ${r.data.hookType} (${r.data.hookInvocationId})`)})),this._register(e.onHookEnd(r=>{this._logService.trace(`[Copilot:${n}] Hook ended: ${r.data.hookType} (${r.data.hookInvocationId}), success=${r.data.success}`)})),this._register(e.onSystemMessage(r=>{this._logService.trace(`[Copilot:${n}] System message [${r.data.role}]: ${r.data.content.length} chars`)}))}getNextTurnEventId(e){return this._databaseRef.object.getNextTurnEventId(e)}getFirstTurnEventId(){return this._databaseRef.object.getFirstTurnEventId()}async truncateAtEventId(e,n){this._logService.info(`[Copilot:${this.sessionId}] Truncating via SDK RPC at eventId=${e}`);let r=await this._wrapper.session.rpc.history.truncate({eventId:e});this._logService.info(`[Copilot:${this.sessionId}] SDK truncation removed ${r.eventsRemoved} events`),n?await this._databaseRef.object.deleteTurnsAfter(n):await this._databaseRef.object.deleteAllTurns()}async remapTurnIds(e){await this._databaseRef.object.remapTurnIds(e)}_denyPendingPermissions(){for(let[e,n]of this._pendingPermissions)this._deletePendingEditContent(e),n.complete(!1);this._pendingPermissions.clear()}_deletePendingEditContent(e){let n=this._pendingEditContentUris.get(e);n&&(this._pendingEditContentUris.delete(e),this._fileService.del(n).catch(r=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to delete pending edit content: ${n.toString()}`,r)}))}_cancelPendingUserInputs(){for(let[,e]of this._pendingUserInputs)e.deferred.complete({response:"cancel"});this._pendingUserInputs.clear()}_cancelPendingClientToolCalls(){for(let[,e]of this._pendingClientToolCalls)e.complete({textResultForLlm:"Tool call cancelled: session ended",resultType:"failure",error:"Session ended"});this._pendingClientToolCalls.clear()}};$r=O([K(1,pr),K(2,ue),K(3,Ur),K(4,tt),K(5,Bs)],$r);function O1(i){let t=0,e=0;for(let n of i.split(`
`))n.startsWith("+++")||n.startsWith("---")||(n.startsWith("+")?t++:n.startsWith("-")&&e++);if(!(t===0&&e===0))return{added:t,removed:e}}async function L1(i,t){if(!i||i.scheme!==ee.file||!await t.isInsideWorkTree(i))return;let e=(await t.getWorktreeRoots(i))[0]??await t.getRepositoryRoot(i);if(e)return{uri:e,displayName:Te(e.fsPath)||e.toString()}}function F1(i){let t=i.includes("://")?b.parse(i):b.parse(`https://github.com/${i}`),e=Te(t.path)||i.split("/").filter(Boolean).pop()||i,n=e.endsWith(".git")?e.slice(0,-4):e;return{uri:t,displayName:n}}async function Js(i,t){let e=typeof i?.cwd=="string"?b.file(i.cwd):typeof i?.gitRoot=="string"?b.file(i.gitRoot):void 0,n=await L1(e,t);if(n)return n;if(i?.repository)return F1(i.repository)}import{spawn as U1}from"child_process";function Df(i){let t={};for(let e of i){let n=e.configuration;n.type==="stdio"?t[e.name]={type:"local",command:n.command,args:n.args?[...n.args]:[],tools:["*"],...n.env&&{env:N1(n.env)},...n.cwd&&{cwd:n.cwd}}:t[e.name]={type:"http",url:n.url,tools:["*"],...n.headers&&{headers:{...n.headers}}}}return t}function N1(i){let t={};for(let[e,n]of Object.entries(i))n!==null&&(t[e]=String(n));return t}async function Of(i,t){let e=[];for(let n of i)try{let r=await t.readFile(n.uri);e.push({name:n.name,prompt:r.value.toString()})}catch{}return e}function Lf(i){let t=new Set,e=[];for(let n of i){let r=me(n.uri.fsPath);t.has(r)||(t.add(r),e.push(r))}return e}function M1(i,t){return t===1&&i.windows?i.windows:t===2&&i.osx?i.osx:t===3&&i.linux?i.linux:i.command}function Vr(i,t){let e=M1(i,po);if(!e)return Promise.resolve("");let n=(i.timeout??30)*1e3,r=i.cwd?.fsPath;return new Promise((o,s)=>{let a=po===1,p=U1(a?"cmd.exe":"/bin/sh",a?["/c",e]:["-c",e],{cwd:r,env:{...process.env,...i.env},stdio:["pipe","pipe","pipe"],timeout:n}),u="",f="";p.stdout.on("data",m=>{u+=m.toString()}),p.stderr.on("data",m=>{f+=m.toString()}),t&&p.stdin.write(t),p.stdin.end(),p.on("error",s),p.on("close",m=>{m===0?o(u):s(new Error(`Hook command exited with code ${m}: ${f||u}`))})})}var W1={PreToolUse:"onPreToolUse",PostToolUse:"onPostToolUse",UserPromptSubmit:"onUserPromptSubmitted",SessionStart:"onSessionStart",SessionEnd:"onSessionEnd",ErrorOccurred:"onErrorOccurred"};function Ff(i,t){let e=new Map;for(let p of i){let u=W1[p.type];if(!u)continue;let f=e.get(u)??[];f.push(...p.commands),e.set(u,f)}let n={},r=e.get("onPreToolUse");(r?.length||t)&&(n.onPreToolUse=async p=>{if(await t?.onPreToolUse(p),r){let u=JSON.stringify(p);for(let f of r)try{let m=await Vr(f,u);if(m.trim())try{let v=JSON.parse(m);if(v&&typeof v=="object")return v}catch{}}catch{}}});let o=e.get("onPostToolUse");(o?.length||t)&&(n.onPostToolUse=async p=>{if(await t?.onPostToolUse(p),o){let u=JSON.stringify(p);for(let f of o)try{await Vr(f,u)}catch{}}});let s=e.get("onUserPromptSubmitted");s?.length&&(n.onUserPromptSubmitted=async p=>{let u=JSON.stringify(p);for(let f of s)try{await Vr(f,u)}catch{}});let a=e.get("onSessionStart");a?.length&&(n.onSessionStart=async p=>{let u=JSON.stringify(p);for(let f of a)try{await Vr(f,u)}catch{}});let l=e.get("onSessionEnd");l?.length&&(n.onSessionEnd=async p=>{let u=JSON.stringify(p);for(let f of l)try{await Vr(f,u)}catch{}});let c=e.get("onErrorOccurred");return c?.length&&(n.onErrorOccurred=async p=>{let u=JSON.stringify(p);for(let f of c)try{await Vr(f,u)}catch{}}),n}function Uf(i,t){let e=n=>JSON.stringify(n.map(r=>({hooks:r.hooks.map(o=>({type:o.type,commands:o.commands.map(s=>({command:s.command,windows:s.windows,linux:s.linux,osx:s.osx,cwd:s.cwd?.toString(),env:s.env,timeout:s.timeout}))})),mcpServers:r.mcpServers.map(o=>({name:o.name,configuration:o.configuration})),skills:r.skills.map(o=>({uri:o.uri.toString(),name:o.name})),agents:r.agents.map(o=>({uri:o.uri.toString(),name:o.name}))})));return e(i)===e(t)}var qr=class extends L{constructor(e){super();this.session=e;this._register(w(()=>{e.destroy().catch(()=>{})}))}get sessionId(){return this.session.sessionId}get onMessageDelta(){return this._onMessageDelta??=this._sdkEvent("assistant.message_delta")}get onMessage(){return this._onMessage??=this._sdkEvent("assistant.message")}get onToolStart(){return this._onToolStart??=this._sdkEvent("tool.execution_start")}get onToolComplete(){return this._onToolComplete??=this._sdkEvent("tool.execution_complete")}get onIdle(){return this._onIdle??=this._sdkEvent("session.idle")}get onSessionStart(){return this._onSessionStart??=this._sdkEvent("session.start")}get onSessionResume(){return this._onSessionResume??=this._sdkEvent("session.resume")}get onSessionError(){return this._onSessionError??=this._sdkEvent("session.error")}get onSessionInfo(){return this._onSessionInfo??=this._sdkEvent("session.info")}get onSessionModelChange(){return this._onSessionModelChange??=this._sdkEvent("session.model_change")}get onSessionHandoff(){return this._onSessionHandoff??=this._sdkEvent("session.handoff")}get onSessionTruncation(){return this._onSessionTruncation??=this._sdkEvent("session.truncation")}get onSessionSnapshotRewind(){return this._onSessionSnapshotRewind??=this._sdkEvent("session.snapshot_rewind")}get onSessionShutdown(){return this._onSessionShutdown??=this._sdkEvent("session.shutdown")}get onSessionUsageInfo(){return this._onSessionUsageInfo??=this._sdkEvent("session.usage_info")}get onSessionCompactionStart(){return this._onSessionCompactionStart??=this._sdkEvent("session.compaction_start")}get onSessionCompactionComplete(){return this._onSessionCompactionComplete??=this._sdkEvent("session.compaction_complete")}get onUserMessage(){return this._onUserMessage??=this._sdkEvent("user.message")}get onPendingMessagesModified(){return this._onPendingMessagesModified??=this._sdkEvent("pending_messages.modified")}get onTurnStart(){return this._onTurnStart??=this._sdkEvent("assistant.turn_start")}get onIntent(){return this._onIntent??=this._sdkEvent("assistant.intent")}get onReasoning(){return this._onReasoning??=this._sdkEvent("assistant.reasoning")}get onReasoningDelta(){return this._onReasoningDelta??=this._sdkEvent("assistant.reasoning_delta")}get onTurnEnd(){return this._onTurnEnd??=this._sdkEvent("assistant.turn_end")}get onUsage(){return this._onUsage??=this._sdkEvent("assistant.usage")}get onAbort(){return this._onAbort??=this._sdkEvent("abort")}get onToolUserRequested(){return this._onToolUserRequested??=this._sdkEvent("tool.user_requested")}get onToolPartialResult(){return this._onToolPartialResult??=this._sdkEvent("tool.execution_partial_result")}get onToolProgress(){return this._onToolProgress??=this._sdkEvent("tool.execution_progress")}get onSkillInvoked(){return this._onSkillInvoked??=this._sdkEvent("skill.invoked")}get onSubagentStarted(){return this._onSubagentStarted??=this._sdkEvent("subagent.started")}get onSubagentCompleted(){return this._onSubagentCompleted??=this._sdkEvent("subagent.completed")}get onSubagentFailed(){return this._onSubagentFailed??=this._sdkEvent("subagent.failed")}get onSubagentSelected(){return this._onSubagentSelected??=this._sdkEvent("subagent.selected")}get onHookStart(){return this._onHookStart??=this._sdkEvent("hook.start")}get onHookEnd(){return this._onHookEnd??=this._sdkEvent("hook.end")}get onSystemMessage(){return this._onSystemMessage??=this._sdkEvent("system.message")}_sdkEvent(e){let n=this._register(new x),r=this.session.on(e,o=>n.fire(o));return this._register(w(r)),n.event}};var Nf=8e4,B1=12e4,Tc="<<<COPILOT_SENTINEL_";function $1(i){return i==="powershell"?"powershell.exe":process.env.SHELL||"/bin/bash"}var $n=class{constructor(t,e,n,r){this._sessionUri=t;this._workingDirectory=e;this._terminalManager=n;this._logService=r;this._shells=new Map;this._toolCallShells=new Map;this._onDidAssociateTerminal=new x;this.onDidAssociateTerminal=this._onDidAssociateTerminal.event}async getOrCreateShell(t,e,n,r){for(let p of this._shells.values())if(p.shellType===t&&this._terminalManager.hasTerminal(p.terminalUri)){if(this._terminalManager.getExitCode(p.terminalUri)===void 0)return this._trackToolCall(n,p.id),p;this._shells.delete(p.id)}let o=ne(),s=`agenthost-terminal://shell/${o}`,a={kind:"session",session:this._sessionUri.toString(),turnId:e,toolCallId:n},l=t==="bash"?"Bash":"PowerShell";await this._terminalManager.createTerminal({terminal:s,claim:a,name:l,cwd:r??this._workingDirectory?.fsPath},{shell:$1(t),preventShellHistory:!0});let c={id:o,terminalUri:s,shellType:t};return this._shells.set(o,c),this._trackToolCall(n,o),this._logService.info(`[ShellManager] Created ${t} shell ${o} (terminal=${s})`),c}_trackToolCall(t,e){this._toolCallShells.set(t,e);let n=this._shells.get(e);if(n){let r=n.shellType==="bash"?"Bash":"PowerShell";this._onDidAssociateTerminal.fire({toolCallId:t,terminalUri:n.terminalUri,displayName:r})}}getTerminalUriForToolCall(t){let e=this._toolCallShells.get(t);if(e)return this._shells.get(e)?.terminalUri}getShell(t){return this._shells.get(t)}listShells(){let t=[];for(let e of this._shells.values())this._terminalManager.hasTerminal(e.terminalUri)&&t.push(e);return t}shutdownShell(t){let e=this._shells.get(t);return e?(this._terminalManager.disposeTerminal(e.terminalUri),this._shells.delete(t),this._logService.info(`[ShellManager] Shut down shell ${t}`),!0):!1}dispose(){for(let t of this._shells.values())this._terminalManager.hasTerminal(t.terminalUri)&&this._terminalManager.disposeTerminal(t.terminalUri);this._shells.clear(),this._toolCallShells.clear()}};$n=O([K(2,kr),K(3,ue)],$n);function V1(){return ne().replace(/-/g,"")}function q1(i,t){return t==="powershell"?`Write-Output "${Tc}${i}_EXIT_$LASTEXITCODE>>>"`:`echo "${Tc}${i}_EXIT_$?>>>"`}function Mf(i){return i==="powershell"?"":" "}function K1(i,t){let e=`${Tc}${t}_EXIT_`,n=i.indexOf(e);if(n===-1)return{found:!1,exitCode:-1,outputBeforeSentinel:i};let r=i.substring(0,n),o=i.substring(n+e.length),s=o.indexOf(">>>"),a=s>=0?o.substring(0,s):o.trim(),l=parseInt(a,10);return{found:!0,exitCode:isNaN(l)?-1:l,outputBeforeSentinel:r}}function Vn(i){let t=Wd(i).trim();return t.length>Nf&&(t=t.substring(t.length-Nf)),t}function mt(i){return{textResultForLlm:i,resultType:"success"}}function Ct(i,t){return{textResultForLlm:i,resultType:"failure",error:t}}async function z1(i,t,e,n,r){return n.supportsCommandDetection(i.terminalUri)?j1(i,t,e,n,r):H1(i,t,e,n,r)}async function j1(i,t,e,n,r){let o=new N;return n.writeInput(i.terminalUri,`${Mf(i.shellType)}${t}\r`),new Promise(s=>{let a=!1,l=p=>{a||(a=!0,o.dispose(),s(p))};o.add(n.onCommandFinished(i.terminalUri,p=>{let u=Vn(p.output),f=p.exitCode??0;r.info(`[ShellTool] Command completed (shell integration) with exit code ${f}`),l(f===0?mt(`Exit code: ${f}
${u}`):Ct(`Exit code: ${f}
${u}`))})),o.add(n.onExit(i.terminalUri,p=>{r.info(`[ShellTool] Shell exited unexpectedly with code ${p}`);let u=n.getContent(i.terminalUri)??"",f=Vn(u);l(Ct(`Shell exited with code ${p}
${f}`))})),o.add(n.onClaimChanged(i.terminalUri,p=>{p.kind==="session"&&!p.toolCallId&&(r.info("[ShellTool] Continuing in background (claim narrowed)"),l(mt("The user chose to continue this command in the background. The terminal is still running.")))}));let c=setTimeout(()=>{r.warn(`[ShellTool] Command timed out after ${e}ms`);let p=n.getContent(i.terminalUri)??"",u=Vn(p);l(Ct(`Command timed out after ${Math.round(e/1e3)}s. Partial output:
${u}`,"timeout"))},e);o.add(w(()=>clearTimeout(c)))})}async function H1(i,t,e,n,r){let o=V1(),s=q1(o,i.shellType),a=new N,c=(n.getContent(i.terminalUri)??"").length,p=`${Mf(i.shellType)}${t}\r${s}\r`;return n.writeInput(i.terminalUri,p),new Promise(u=>{let f=!1,m=I=>{f||(f=!0,a.dispose(),u(I))},v=()=>{let I=n.getContent(i.terminalUri)??"",y=Math.min(c,I.length),S=I.substring(y),C=K1(S,o);if(C.found){let X=Vn(C.outputBeforeSentinel);r.info(`[ShellTool] Command completed with exit code ${C.exitCode}`),C.exitCode===0?m(mt(`Exit code: ${C.exitCode}
${X}`)):m(Ct(`Exit code: ${C.exitCode}
${X}`))}};a.add(n.onData(i.terminalUri,()=>{v()})),a.add(n.onExit(i.terminalUri,I=>{r.info(`[ShellTool] Shell exited unexpectedly with code ${I}`);let S=(n.getContent(i.terminalUri)??"").substring(c),C=Vn(S);m(Ct(`Shell exited with code ${I}
${C}`))})),a.add(n.onClaimChanged(i.terminalUri,I=>{I.kind==="session"&&!I.toolCallId&&(r.info("[ShellTool] Continuing in background (claim narrowed)"),m(mt("The user chose to continue this command in the background. The terminal is still running.")))}));let h=setTimeout(()=>{r.warn(`[ShellTool] Command timed out after ${e}ms`);let y=(n.getContent(i.terminalUri)??"").substring(c),S=Vn(y);m(Ct(`Command timed out after ${Math.round(e/1e3)}s. Partial output:
${S}`,"timeout"))},e);a.add(w(()=>clearTimeout(h))),v()})}function Wf(i,t,e){let n=B?"powershell":"bash",r={name:n,description:`Execute a command in a persistent ${n} shell. The shell is reused across calls.`,parameters:{type:"object",properties:{command:{type:"string",description:"The command to execute"},timeout:{type:"number",description:"Timeout in milliseconds (default 120000)"}},required:["command"]},overridesBuiltInTool:!0,handler:async(c,p)=>{let u=await i.getOrCreateShell(n,p.toolCallId,p.toolCallId),f=c.timeout??B1;return z1(u,c.command,f,t,e)}},o={name:`read_${n}`,description:`Read the latest output from a running ${n} shell.`,parameters:{type:"object",properties:{shell_id:{type:"string",description:"Shell ID to read from (optional; uses latest shell if omitted)"}}},overridesBuiltInTool:!0,handler:c=>{let p=i.listShells(),u=c.shell_id?i.getShell(c.shell_id):p[p.length-1];if(!u)return Ct("No active shell found.","no_shell");let f=t.getContent(u.terminalUri);return mt(f?Vn(f):"(no output)")}},s={name:`write_${n}`,description:`Send input to a running ${n} shell (e.g. answering a prompt, sending Ctrl+C).`,parameters:{type:"object",properties:{command:{type:"string",description:"Text to write to the shell stdin"}},required:["command"]},overridesBuiltInTool:!0,handler:c=>{let p=i.listShells(),u=p[p.length-1];return u?(t.writeInput(u.terminalUri,c.command),mt("Input sent to shell.")):Ct("No active shell found.","no_shell")}},a={name:n==="bash"?"bash_shutdown":`${n}_shutdown`,description:`Stop a ${n} shell.`,parameters:{type:"object",properties:{shell_id:{type:"string",description:"Shell ID to stop (optional; stops latest shell if omitted)"}}},overridesBuiltInTool:!0,handler:c=>{if(c.shell_id)return i.shutdownShell(c.shell_id)?mt("Shell stopped."):Ct("Shell not found.","not_found");let p=i.listShells(),u=p[p.length-1];return u?(i.shutdownShell(u.id),mt("Shell stopped.")):Ct("No active shell to stop.","no_shell")}},l={name:`list_${n}`,description:`List active ${n} shell instances.`,parameters:{type:"object",properties:{}},overridesBuiltInTool:!0,handler:()=>{let c=i.listShells();if(c.length===0)return mt("No active shells.");let p=c.map(u=>{let f=t.getExitCode(u.terminalUri),m=f!==void 0?`exited (${f})`:"running";return`- ${u.id}: ${u.shellType} [${m}]`});return mt(p.join(`
`))}};return[r,o,s,a,l]}var Bf="thinkingLevel",Q1=["low","medium","high","xhigh"];function Y1(i){return Q1.some(t=>t===i)}function X1(i){return b.joinPath(i,"..",`${Te(i.fsPath)}.worktrees`)}function Z1(i){return i.replace(/\//g,"-")}function eb(i,t){return`agents/${t?`${t}-${i.substring(0,8)}`:i}`}function $f(i){return g(1840,null,jt(i))+`

`}function tb(i,t){let e=i.findIndex(o=>o.type==="message"&&o.role==="assistant"&&!o.parentToolCallId);if(e===-1)return i;let n=i[e],r={...n,content:t+n.content};return[...i.slice(0,e),r,...i.slice(e+1)]}var Ie=class extends L{constructor(e,n,r,o,s,a){super();this._logService=e;this._instantiationService=n;this._fileService=r;this._sessionDataService=o;this._gitService=s;this._terminalManager=a;this.id="copilot";this._onDidSessionProgress=this._register(new x);this.onDidSessionProgress=this._onDidSessionProgress.event;this._models=Ln(this,[]);this.models=this._models;this._sessions=this._register(new it);this._createdWorktrees=new Map;this._pendingFirstTurnAnnouncements=new Map;this._sessionSequencer=new St;this._activeClients=new ut;this._plugins=this._instantiationService.createInstance(zi)}static{this._BRANCH_COMPLETION_LIMIT=25}_createCopilotClient(e){return new G1(e)}getDescriptor(){return{provider:"copilot",displayName:"Copilot CLI",description:"Copilot SDK agent running in a dedicated process"}}getProtectedResources(){return[{resource:"https://api.github.com",resource_name:"GitHub Copilot",authorization_servers:["https://github.com/login/oauth"],scopes_supported:["read:user","user:email"],required:!0}]}async authenticate(e,n){if(e!=="https://api.github.com")return!1;let r=this._githubToken!==n;return this._githubToken=n,this._logService.info(`[Copilot] Auth token ${r?"updated":"unchanged"}`),r&&this._client&&this._sessions.size===0&&(this._logService.info("[Copilot] Restarting CopilotClient with new token"),await this._stopClient()),r&&this._refreshModels(),!0}async _refreshModels(){let e=this._githubToken;if(!e){this._models.set([],void 0);return}try{let n=await this._listModels();this._githubToken===e&&this._models.set(n,void 0)}catch(n){this._logService.error(n,"[Copilot] Failed to refresh models"),this._githubToken===e&&this._models.set([],void 0)}}async _stopClient(){let e=this._client;this._client=void 0,this._clientStarting=void 0,await e?.stop()}async _ensureClient(){let e=this._githubToken;if(!e)throw new H(ns,"Authentication is required to use Copilot");if(this._client)return this._client;if(this._clientStarting)return this._clientStarting;let n=(async()=>{this._logService.info("[Copilot] Starting CopilotClient... (with token)");let r=Object.assign({},process.env,{ELECTRON_RUN_AS_NODE:"1"});delete r.NODE_OPTIONS,delete r.VSCODE_INSPECTOR_OPTIONS,delete r.VSCODE_ESM_ENTRYPOINT,delete r.VSCODE_HANDLES_UNCAUGHT_ERRORS;for(let u of Object.keys(r))u!=="ELECTRON_RUN_AS_NODE"&&(u.startsWith("VSCODE_")||u.startsWith("ELECTRON_"))&&delete r[u];r.COPILOT_CLI_RUN_AS_NODE="1",r.USE_BUILTIN_RIPGREP="false";let o=b.joinPath(Xe.asFileUri(""),"..","node_modules","@github","copilot","index.js").fsPath,s=J1.replace(/\bnode_modules\.asar\b/,"node_modules.asar.unpacked"),a=me(s),l=Object.keys(r).find(u=>u.toUpperCase()==="PATH")??"PATH",c=r[l];r[l]=c?`${c}${Va}${a}`:a,this._logService.info(`[Copilot] Resolved CLI path: ${o}`);let p=this._createCopilotClient({githubToken:e,useLoggedInUser:!1,useStdio:!0,autoStart:!0,env:r,cliPath:o});if(await p.start(),this._githubToken!==e)throw await p.stop(),new Error("Copilot authentication changed while the client was starting");return this._logService.info("[Copilot] CopilotClient started successfully"),this._client=p,this._clientStarting=void 0,p})();return this._clientStarting=n,n.catch(()=>{this._clientStarting=void 0}),n}_createThinkingLevelConfigSchema(e,n){if(!e?.length)return;let r=e.map(o=>{switch(o){case"low":return g(1836,null);case"medium":return g(1837,null);case"high":return g(1835,null);case"xhigh":return g(1839,null);default:return o}});return{type:"object",properties:{[Bf]:{type:"string",title:g(1838,null),description:g(1834,null),default:n,enum:[...e],enumLabels:r}}}}_getReasoningEffort(e){let n=e?.config?.[Bf];return Y1(n)?n:void 0}_serializeModelSelection(e){return JSON.stringify(e)}_parseModelSelection(e){if(e){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.id=="string"){let r={id:n.id};if(n.config&&typeof n.config=="object"){let o={};for(let[s,a]of Object.entries(n.config))typeof a=="string"&&(o[s]=a);Object.keys(o).length>0&&(r.config=o)}return r}}catch{}return{id:e}}}async listSessions(){this._logService.info("[Copilot] Listing sessions...");let n=await(await this._ensureClient()).listSessions(),r=new ui(4),o=new Map,a=(await Promise.all(n.map(async l=>{let c=ce.uri(this.id,l.sessionId),p=await this._readStoredSessionMetadata(c);if(!p)return;let{project:u,resolved:f}=p;f||(u=await this._resolveSessionProject(l.context,r,o),this._storeSessionProjectResolution(c,u));let m=p.workingDirectory??(typeof l.context?.cwd=="string"?b.file(l.context.cwd):void 0);return{session:c,startTime:l.startTime.getTime(),modifiedTime:l.modifiedTime.getTime(),project:u,summary:l.summary,model:p.model,workingDirectory:m}}))).filter(l=>l!==void 0);return this._logService.info(`[Copilot] Found ${a.length} sessions`),a}async _listModels(){this._logService.info("[Copilot] Listing models...");let r=(await(await this._ensureClient()).listModels()).map(o=>({provider:this.id,id:o.id,name:o.name,maxContextWindow:o.capabilities.limits.max_context_window_tokens,supportsVision:o.capabilities.supports.vision,configSchema:this._createThinkingLevelConfigSchema(o.supportedReasoningEfforts,o.defaultReasoningEffort),policyState:o.policy?.state}));return this._logService.info(`[Copilot] Found ${r.length} models`),r}async createSession(e){if(!e?.workingDirectory)throw new Error("workingDirectory is required to create a Copilot session");this._logService.info(`[Copilot] Creating session... ${e?.model?`model=${e.model.id}`:""}`);let n=await this._ensureClient();if(e?.fork){let h=ce.id(e.fork.session);return this._sessionSequencer.queue(h,async()=>{this._logService.info(`[Copilot] Forking session ${h} at turnId=${e.fork.turnId}`);let y=await(this._sessions.get(h)??await this._resumeSession(h)).getNextTurnEventId(e.fork.turnId),C=(await n.rpc.sessions.fork({sessionId:h,...y?{toEventId:y}:{}})).sessionId,X=this._sessionDataService.getSessionDataDir(e.fork.session),Fe=this._sessionDataService.getSessionDataDirById(C),rt=b.joinPath(X,Nr),P=b.joinPath(Fe,Nr);try{await ji.mkdir(Fe.fsPath,{recursive:!0}),await ji.copyFile(rt.fsPath,P.fsPath)}catch(ie){this._logService.warn(`[Copilot] Failed to copy session database for fork: ${ie instanceof Error?ie.message:String(ie)}`)}let F=await this._resumeSession(C);e.fork.turnIdMapping&&await F.remapTurnIds(e.fork.turnIdMapping);let A=F.sessionUri;this._logService.info(`[Copilot] Forked session created: ${A.toString()}`);let Z=await Js({cwd:e.workingDirectory?.fsPath},this._gitService);return await this._storeSessionMetadata(A,e.model,e.workingDirectory,Z,!0),{session:A,workingDirectory:e.workingDirectory,...Z?{project:Z}:{}}})}let r=e?.session?ce.id(e.session):ne(),o=ce.uri(this.id,r),s=this._activeClients.get(o),a=s?await s.snapshot():void 0,l=await this._resolveSessionWorkingDirectory(e,r),c=this._instantiationService.createInstance($n,o,l),p=this._buildSessionConfig(a,c),u=async h=>{let I=await n.createSession({model:e?.model?.id,reasoningEffort:this._getReasoningEffort(e?.model),sessionId:r,streaming:!0,workingDirectory:l?.fsPath,...await p(h)});return new qr(I)},f;try{f=this._createAgentSession(u,r,c,a),await f.initializeSession()}catch(h){throw await this._removeCreatedWorktree(r),h}let m=f.sessionUri;this._logService.info(`[Copilot] Session created: ${m.toString()}`);let v=await Js({cwd:l?.fsPath},this._gitService);return await this._storeSessionMetadata(f.sessionUri,e?.model,l,v,!0),{session:m,workingDirectory:l,...v?{project:v}:{}}}async resolveSessionConfig(e){let n=e.workingDirectory?await this._getGitInfo(e.workingDirectory):void 0,r=e.config?.isolation==="folder"||e.config?.isolation==="worktree"?e.config.isolation:n?"worktree":"folder",o=e.config?.autoApprove==="default"||e.config?.autoApprove==="autoApprove"||e.config?.autoApprove==="autopilot"?e.config.autoApprove:"default",s={isolation:r,autoApprove:o};if(n){let l=r==="worktree"?n.defaultBranch:n.currentBranch;s.branch=typeof e.config?.branch=="string"&&r==="worktree"?e.config.branch:l}let a={isolation:{type:"string",title:g(1828,null),description:g(1833,null),enum:n?["folder","worktree"]:["folder"],enumLabels:n?[g(1829,null),g(1831,null)]:[g(1829,null)],enumDescriptions:n?[g(1830,null),g(1832,null)]:[g(1830,null)],default:n?"worktree":"folder",readOnly:!n},autoApprove:{type:"string",title:g(1818,null),description:g(1825,null),enum:["default","autoApprove","autopilot"],enumLabels:[g(1823,null),g(1821,null),g(1819,null)],enumDescriptions:[g(1824,null),g(1822,null),g(1820,null)],default:"default",sessionMutable:!0}};if(n){let l=r==="folder",c=r==="worktree"?n.defaultBranch:n.currentBranch;a.branch={type:"string",title:g(1826,null),description:g(1827,null),enum:[c],enumLabels:[c],default:c,enumDynamic:!l,readOnly:l}}return{schema:{type:"object",properties:a},values:s}}async sessionConfigCompletions(e){return e.property!=="branch"||!e.workingDirectory?{items:[]}:{items:(await this._getBranches(e.workingDirectory,e.query)).map(r=>({value:r,label:r}))}}async setClientCustomizations(e,n,r){return this._plugins.sync(e,n,r)}setClientTools(e,n,r){this._getOrCreateActiveClient(e).updateTools(n,r),this._logService.info(`[Copilot:${ce.id(e)}] Client tools updated: ${r.map(s=>s.name).join(", ")||"(none)"}`)}onClientToolCallComplete(e,n,r){this._sessions.get(ce.id(e))?.handleClientToolCallComplete(n,r)}setCustomizationEnabled(e,n){this._plugins.setEnabled(e,n)}async sendMessage(e,n,r,o){let s=ce.id(e);await this._sessionSequencer.queue(s,async()=>{let a=this._sessions.get(s),l=this._activeClients.get(e);a&&l&&await l.isOutdated(a.appliedSnapshot)&&(this._logService.info(`[Copilot:${s}] Session config changed, refreshing session`),this._sessions.deleteAndDispose(s),a=void 0),a??=await this._resumeSession(s);let c=this._pendingFirstTurnAnnouncements.get(s);if(c){this._pendingFirstTurnAnnouncements.delete(s);let p=`copilot-announcement-${ne()}`,u={type:"delta",session:e,messageId:p,content:c};this._onDidSessionProgress.fire(u)}await a.send(n,r,o)})}setPendingMessages(e,n,r){let o=ce.id(e),s=this._sessions.get(o);if(!s){this._logService.warn(`[Copilot:${o}] setPendingMessages: session not found`);return}n&&s.sendSteering(n)}async getSessionMessages(e){let n=ce.id(e),r=this._sessions.get(n)??await this._resumeSession(n).catch(a=>{this._logService.warn(`[Copilot:${n}] Failed to resume session for message lookup`,a)});if(!r)return[];let o=await r.getMessages(),s=await this._readWorktreeBranchMetadata(e).catch(a=>{this._logService.warn(`[Copilot:${n}] Failed to read worktree branch metadata`,a)});return s?[...tb(o,$f(s))]:o}async disposeSession(e){let n=ce.id(e);await this._sessionSequencer.queue(n,async()=>{await this._destroyAndDisposeSession(n)})}async abortSession(e){let n=ce.id(e);await this._sessionSequencer.queue(n,async()=>{let r=this._sessions.get(n);r&&await r.abort()})}async truncateSession(e,n){let r=ce.id(e);await this._sessionSequencer.queue(r,async()=>{this._logService.info(`[Copilot:${r}] Truncating session${n!==void 0?` at turnId=${n}`:" (all turns)"}`);let o=this._sessions.get(r)??await this._resumeSession(r),s;n?s=await o.getNextTurnEventId(n):s=await o.getFirstTurnEventId(),s?await o.truncateAtEventId(s,n):this._logService.info(`[Copilot:${r}] No event ID found for truncation, nothing to truncate`),this._logService.info(`[Copilot:${r}] Session truncated`)})}async changeModel(e,n){let r=ce.id(e),o=this._sessions.get(r);o&&await o.setModel(n.id,this._getReasoningEffort(n)),await this._storeSessionMetadata(e,n,void 0,void 0)}async shutdown(){return this._shutdownPromise??=(async()=>{this._logService.info("[Copilot] Shutting down...");let e=new Set([...this._sessions.keys(),...this._createdWorktrees.keys()]);for(let n of e)await this._sessionSequencer.queue(n,()=>this._destroyAndDisposeSession(n));await this._client?.stop(),this._client=void 0})(),this._shutdownPromise}respondToPermissionRequest(e,n){for(let[,r]of this._sessions)if(r.respondToPermissionRequest(e,n))return}respondToUserInputRequest(e,n,r){for(let[,o]of this._sessions)if(o.respondToUserInputRequest(e,n,r))return}hasSession(e){return this._sessions.has(ce.id(e))}_getOrCreateActiveClient(e){let n=this._activeClients.get(e);return n||(n=new xc(()=>this._plugins.getAppliedPlugins()),this._activeClients.set(e,n)),n}_createAgentSession(e,n,r,o){let s=ce.uri(this.id,n),a=this._instantiationService.createInstance($r,{sessionUri:s,rawSessionId:n,onDidSessionProgress:this._onDidSessionProgress,wrapperFactory:e,shellManager:r,clientSnapshot:o});return this._sessions.set(n,a),a}async _destroyAndDisposeSession(e){let n=this._sessions.get(e);if(n)try{await n.destroySession()}catch(r){this._logService.warn(`[Copilot:${e}] Failed to destroy session before cleanup: ${r instanceof Error?r.message:String(r)}`)}this._sessions.deleteAndDispose(e),await this._removeCreatedWorktree(e)}_buildSessionConfig(e,n){let r=Wf(n,this._terminalManager,this._logService),o=e?.plugins??[];return async s=>{let a=await Of(o.flatMap(l=>l.agents),this._fileService);return{onPermissionRequest:s.onPermissionRequest,onUserInputRequest:s.onUserInputRequest,hooks:Ff(o.flatMap(l=>l.hooks),s.hooks),mcpServers:Df(o.flatMap(l=>l.mcpServers)),customAgents:a,skillDirectories:Lf(o.flatMap(l=>l.skills)),tools:[...r,...s.clientTools]}}}async _resumeSession(e){this._logService.info(`[Copilot:${e}] Session not in memory, resuming...`);let n=await this._ensureClient(),r=ce.uri(this.id,e),o=this._activeClients.get(r),s=o?await o.snapshot():void 0,a=await this._readSessionMetadata(r),l=await n.getSessionMetadata(e).catch(v=>{this._logService.warn(`[Copilot:${e}] getSessionMetadata failed`,v)}),c=a.workingDirectory??(typeof l?.context?.cwd=="string"?b.file(l.context.cwd):void 0);if(!c)throw new Error(`workingDirectory is required to resume Copilot session '${e}'`);let p=this._instantiationService.createInstance($n,r,c),u=this._buildSessionConfig(s,p),f=async v=>{let h=await u(v);try{let I=await n.resumeSession(e,{...h,workingDirectory:c?.fsPath});return new qr(I)}catch(I){if(!I||I.code!==-32603)throw I;this._logService.warn(`[Copilot:${e}] Resume failed (session not found in SDK), recreating`);let y=await n.createSession({...h,sessionId:e,streaming:!0,model:a.model?.id,reasoningEffort:this._getReasoningEffort(a.model),workingDirectory:c?.fsPath});return new qr(y)}},m=this._createAgentSession(f,e,p,s);return await m.initializeSession(),m}async _getGitInfo(e){if(!await this._gitService.isInsideWorkTree(e))return;let n=await this._gitService.getCurrentBranch(e)??"HEAD",r=await this._gitService.getDefaultBranch(e)??n;return{currentBranch:n,defaultBranch:r}}async _getBranches(e,n){return this._gitService.getBranches(e,{query:n,limit:Ie._BRANCH_COMPLETION_LIMIT})}async _resolveSessionWorkingDirectory(e,n){if(e?.config?.isolation!=="worktree"||!e.workingDirectory||typeof e.config.branch!="string")return e?.workingDirectory;let r=await this._gitService.getRepositoryRoot(e.workingDirectory);if(!r)return e.workingDirectory;let o=X1(r),s=e.config[ku],a=eb(n,s),l=b.joinPath(o,Z1(a));await ji.mkdir(o.fsPath,{recursive:!0}),await this._gitService.addWorktree(r,l,a,e.config.branch),this._createdWorktrees.set(n,{repositoryRoot:r,worktree:l}),this._pendingFirstTurnAnnouncements.set(n,$f(a));let c=ce.uri(this.id,n);try{await this._writeWorktreeBranchMetadata(c,a)}catch(p){this._logService.warn(`[Copilot:${n}] Failed to persist worktree branch metadata: ${p instanceof Error?p.message:String(p)}`)}return l}async _removeCreatedWorktree(e){let n=this._createdWorktrees.get(e);if(n)try{await this._gitService.removeWorktree(n.repositoryRoot,n.worktree)}catch(r){this._logService.warn(`[Copilot:${e}] Failed to remove worktree '${n.worktree.fsPath}': ${r instanceof Error?r.message:String(r)}`)}finally{this._createdWorktrees.delete(e)}}static{this._META_MODEL="copilot.model"}static{this._META_CWD="copilot.workingDirectory"}static{this._META_PROJECT_RESOLVED="copilot.project.resolved"}static{this._META_PROJECT_URI="copilot.project.uri"}static{this._META_PROJECT_DISPLAY_NAME="copilot.project.displayName"}static{this._META_WORKTREE_BRANCH="copilot.worktree.branchName"}async _writeWorktreeBranchMetadata(e,n){let r=this._sessionDataService.openDatabase(e);try{await r.object.setMetadata(Ie._META_WORKTREE_BRANCH,n)}finally{r.dispose()}}async _readWorktreeBranchMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(n)try{return await n.object.getMetadata(Ie._META_WORKTREE_BRANCH)??void 0}finally{n.dispose()}}async _storeSessionMetadata(e,n,r,o,s=o!==void 0){let a=this._sessionDataService.openDatabase(e),l=a.object;try{let c=[];n&&c.push(l.setMetadata(Ie._META_MODEL,this._serializeModelSelection(n))),r&&c.push(l.setMetadata(Ie._META_CWD,r.toString())),s&&c.push(l.setMetadata(Ie._META_PROJECT_RESOLVED,"true")),o&&(c.push(l.setMetadata(Ie._META_PROJECT_URI,o.uri.toString())),c.push(l.setMetadata(Ie._META_PROJECT_DISPLAY_NAME,o.displayName))),await Promise.all(c)}finally{a.dispose()}}async _readSessionMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(!n)return{};try{let[r,o]=await Promise.all([n.object.getMetadata(Ie._META_MODEL),n.object.getMetadata(Ie._META_CWD)]);return{model:this._parseModelSelection(r),workingDirectory:o?b.parse(o):void 0}}finally{n.dispose()}}async _readStoredSessionMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(n)try{let[r,o,s,a,l]=await Promise.all([n.object.getMetadata(Ie._META_MODEL),n.object.getMetadata(Ie._META_CWD),n.object.getMetadata(Ie._META_PROJECT_RESOLVED),n.object.getMetadata(Ie._META_PROJECT_URI),n.object.getMetadata(Ie._META_PROJECT_DISPLAY_NAME)]),c=o?b.parse(o):void 0,p=a&&l?{uri:b.parse(a),displayName:l}:void 0;return{model:this._parseModelSelection(r),workingDirectory:c,project:p,resolved:s==="true"||p!==void 0}}finally{n.dispose()}}async _storeSessionProjectResolution(e,n){await this._storeSessionMetadata(e,void 0,void 0,n,!0)}_resolveSessionProject(e,n,r){let o=this._projectContextKey(e);if(!o)return Promise.resolve(void 0);let s=r.get(o);return s||(s=n.queue(()=>Js(e,this._gitService)),r.set(o,s)),s}_projectContextKey(e){if(e?.cwd)return`cwd:${e.cwd}`;if(e?.gitRoot)return`gitRoot:${e.gitRoot}`;if(e?.repository)return`repository:${e.repository}`}dispose(){this.shutdown().catch(e=>{this._logService.warn("[Copilot] Shutdown failed during dispose",e)}).finally(()=>super.dispose())}};Ie=O([K(0,ue),K(1,pr),K(2,tt),K(3,Ur),K(4,Ws),K(5,kr)],Ie);var zi=class{constructor(t,e,n){this._pluginManager=t;this._logService=e;this._fileService=n;this._enablement=new Map;this._lastSynced=Promise.resolve({synced:[],parsed:[]})}async getAppliedPlugins(){let{parsed:t}=await this._lastSynced;return t}setEnabled(t,e){this._enablement.set(t,e)}sync(t,e,n){let r=this._lastSynced;return(this._lastSynced=r.catch(s=>{this._logService.warn("[Copilot:PluginController] Previous customization sync failed",s)}).then(async()=>{let s=await this._pluginManager.syncCustomizations(t,e,c=>{n?.(c.map(p=>({customization:p})))}),a=[],l=[];for(let c of s)if(c.pluginDir)try{a.push(await xf(c.pluginDir,this._fileService,void 0,this._getUserHome())),l.push(c)}catch(p){this._logService.warn(`[Copilot:PluginController] Error parsing plugin: ${p}`),l.push({customization:{...c.customization,status:"error",statusMessage:`Error parsing plugin: ${p}`}})}else l.push(c);return{synced:l,parsed:a}})).then(s=>s.synced)}_getUserHome(){return process.env.HOME??process.env.USERPROFILE??""}};zi=O([K(0,Ns),K(1,ue),K(2,tt)],zi);var xc=class{constructor(t){this._resolvePlugins=t;this._tools=[];this._clientId=""}updateTools(t,e){this._clientId=t,this._tools=e}async snapshot(){return{clientId:this._clientId,tools:this._tools,plugins:await this._resolvePlugins()}}async isOutdated(t){let e=await this._resolvePlugins();if(!Uf(t.plugins,e)||t.tools.length!==this._tools.length)return!0;let n=new Map(t.tools.map(r=>[r.name,r]));for(let r of this._tools){let o=n.get(r.name);if(!o||o.description!==r.description||!An(o.inputSchema,r.inputSchema))return!0}return!1}};var Qs=class extends Error{constructor(e,n,r){super(n);this.code=e;this.data=r}},Vf=class i extends L{constructor(e,n){super();this._send=e;this._handlers=n;this._nextRequestId=1;this._pendingRequests=new Map}static{this.ParseError=-32700}static{this.MethodNotFound=-32601}static{this.InternalError=-32603}sendNotification(e){this._send({jsonrpc:"2.0",...e})}sendRequest(e,n=Ze.None,r){if(this._store.isDisposed)return Promise.reject(new Ae);let o=this._nextRequestId++,s=new Be,a=new _e;this._pendingRequests.set(o,{promise:s,cts:a});let l=n.onCancellationRequested(()=>{s.isSettled||(this._pendingRequests.delete(o),a.cancel(),r?.(o),s.cancel()),l.dispose()});return this._send({jsonrpc:"2.0",id:o,...e}),s.p.finally(()=>{l.dispose(),this._pendingRequests.delete(o),a.dispose(!0)})}async handleMessage(e){if(Array.isArray(e)){let r=[];for(let o of e){let s=await this._handleMessage(o);s&&r.push(s)}return r}let n=await this._handleMessage(e);return n?[n]:[]}cancelPendingRequest(e){let n=this._pendingRequests.get(e);n&&(this._pendingRequests.delete(e),n.cts.cancel(),n.promise.cancel(),n.cts.dispose(!0))}cancelAllRequests(){for(let[e,n]of this._pendingRequests)this._pendingRequests.delete(e),n.cts.cancel(),n.promise.cancel(),n.cts.dispose(!0)}async _handleMessage(e){if(_c(e)){We(e,{result:!0})?this._handleResult(e):this._handleError(e);return}if(nb(e))return this._handleRequest(e);rb(e)&&this._handlers.handleNotification?.(e)}_handleResult(e){let n=this._pendingRequests.get(e.id);n&&(this._pendingRequests.delete(e.id),n.promise.complete(e.result),n.cts.dispose(!0))}_handleError(e){if(e.id===void 0)return;let n=this._pendingRequests.get(e.id);n&&(this._pendingRequests.delete(e.id),n.promise.error(new Qs(e.error.code,e.error.message,e.error.data)),n.cts.dispose(!0))}async _handleRequest(e){if(!this._handlers.handleRequest){let r={jsonrpc:"2.0",id:e.id,error:{code:i.MethodNotFound,message:`Method not found: ${e.method}`}};return this._send(r),r}let n=new _e;this._register(w(()=>n.dispose(!0)));try{let r=this._handlers.handleRequest(e,n.token),o=ib(r)?await r:r,s={jsonrpc:"2.0",id:e.id,result:o};return this._send(s),s}catch(r){let o;return r instanceof Qs?o={jsonrpc:"2.0",id:e.id,error:{code:r.code,message:r.message,data:r.data}}:o={jsonrpc:"2.0",id:e.id,error:{code:i.InternalError,message:r instanceof Error?r.message:"Internal error"}},this._send(o),o}finally{n.dispose(!0)}}dispose(){this.cancelAllRequests(),super.dispose()}static createParseError(e,n){return{jsonrpc:"2.0",error:{code:i.ParseError,message:e,data:n}}}};function nb(i){return"method"in i&&"id"in i&&(typeof i.id=="string"||typeof i.id=="number")}function _c(i){return We(i,{id:!0,result:!0})||We(i,{id:!0,error:!0})}function rb(i){return We(i,{method:!0})&&!We(i,{id:!0})}function ib(i){return typeof i=="object"&&i!==null&&"then"in i&&typeof i.then=="function"}var ob=1e3;function Ys(i,t){return{jsonrpc:"2.0",id:i,result:t}}function Ec(i,t,e,n){return{jsonrpc:"2.0",id:i,error:{code:t,message:e,...n!==void 0?{data:n}:{}}}}function Xs(i,t){if(t instanceof H)return Ec(i,t.code,t.message,t.data);let e=t instanceof Error?t.stack??t.message:String(t);return Ec(i,Tr,e)}var qn=class extends L{constructor(e,n,r,o,s,a){super();this._agentService=e;this._stateManager=n;this._server=r;this._config=o;this._clientFileSystemProvider=s;this._logService=a;this._clients=new Map;this._replayBuffer=[];this._onDidChangeConnectionCount=this._register(new x);this.onDidChangeConnectionCount=this._onDidChangeConnectionCount.event;this._requestHandlers={subscribe:async(e,n)=>{try{let r=await this._agentService.subscribe(b.parse(n.resource));return e.subscriptions.add(n.resource),{snapshot:r}}catch(r){throw r instanceof H?r:new H(cn,`Resource not found: ${n.resource}`)}},createSession:async(e,n)=>{let r,o;if(n.fork){let s=this._stateManager.getSessionState(n.fork.session);if(!s)throw new H(cn,`Fork source session not found: ${n.fork.session}`);let a=s.turns.findIndex(l=>l.id===n.fork.turnId);if(a<0)throw new H(cn,`Fork turn ID ${n.fork.turnId} not found in session ${n.fork.session}`);o={session:b.parse(n.fork.session),turnIndex:a,turnId:n.fork.turnId}}try{r=await this._agentService.createSession({provider:n.provider,model:n.model,workingDirectory:n.workingDirectory?b.parse(n.workingDirectory):void 0,session:b.parse(n.session),fork:o,config:n.config})}catch(s){throw s instanceof H?s:new H(cp,s instanceof Error?s.message:String(s))}return r.toString()!==b.parse(n.session).toString()&&this._logService.warn(`[ProtocolServer] createSession: provider returned URI ${r.toString()} but client requested ${n.session}`),null},disposeSession:async(e,n)=>(await this._agentService.disposeSession(b.parse(n.session)),null),resourceWrite:async(e,n)=>this._agentService.resourceWrite(n),listSessions:async()=>({items:(await this._agentService.listSessions()).map(r=>({resource:r.session.toString(),provider:ce.provider(r.session)??"copilot",title:r.summary??"Session",status:r.status??1,createdAt:r.startTime,modifiedAt:r.modifiedTime,...r.project?{project:{uri:r.project.uri.toString(),displayName:r.project.displayName}}:{},model:r.model,workingDirectory:r.workingDirectory?.toString(),isRead:r.isRead,isDone:r.isDone}))}),resolveSessionConfig:async(e,n)=>this._agentService.resolveSessionConfig({provider:n.provider,workingDirectory:n.workingDirectory?b.parse(n.workingDirectory):void 0,config:n.config}),sessionConfigCompletions:async(e,n)=>this._agentService.sessionConfigCompletions({provider:n.provider,workingDirectory:n.workingDirectory?b.parse(n.workingDirectory):void 0,config:n.config,property:n.property,query:n.query}),fetchTurns:async(e,n)=>{let r=this._stateManager.getSessionState(n.session);if(!r)throw new H(cn,`Session not found: ${n.session}`);let o=r.turns,s=Math.min(n.limit??50,100),a=o.length;if(n.before){let c=o.findIndex(p=>p.id===n.before);c!==-1&&(a=c)}let l=Math.max(0,a-s);return{turns:o.slice(l,a),hasMore:l>0}},resourceList:async(e,n)=>this._agentService.resourceList(b.parse(n.uri)),resourceRead:async(e,n)=>this._agentService.resourceRead(b.parse(n.uri)),resourceCopy:async(e,n)=>this._agentService.resourceCopy(n),resourceDelete:async(e,n)=>this._agentService.resourceDelete(n),resourceMove:async(e,n)=>this._agentService.resourceMove(n),authenticate:async(e,n)=>{if(!(await this._agentService.authenticate(n)).authenticated)throw new H(ns,"Authentication failed for resource: "+n.resource);return{}},createTerminal:async(e,n)=>(await this._agentService.createTerminal(n),null),disposeTerminal:async(e,n)=>(await this._agentService.disposeTerminal(b.parse(n.terminal)),null)};this._reverseRequestId=0;this._pendingReverseRequests=new Map;this._register(this._server.onConnection(l=>{this._handleNewConnection(l)})),this._register(this._stateManager.onDidEmitEnvelope(l=>{this._replayBuffer.push(l),this._replayBuffer.length>ob&&this._replayBuffer.shift(),this._broadcastAction(l)})),this._register(this._stateManager.onDidEmitNotification(l=>{this._broadcastNotification(l)}))}_handleNewConnection(e){let n=new N,r;n.add(e.onMessage(o=>{if(up(o)){if(this._logService.trace(`[ProtocolServer] request: method=${o.method} id=${o.id}`),!r&&o.method==="initialize"){try{let s=this._handleInitialize(o.params,e,n);r=s.client,e.send(Ys(o.id,s.response))}catch(s){e.send(Xs(o.id,s))}return}if(!r&&o.method==="reconnect"){try{let s=this._handleReconnect(o.params,e,n);r=s.client,e.send(Ys(o.id,s.response))}catch(s){e.send(Xs(o.id,s))}return}if(!r)return;this._handleRequest(r,o.method,o.params,o.id)}else if(pp(o))switch(this._logService.trace(`[ProtocolServer] notification: method=${o.method}`),o.method){case"unsubscribe":r&&r.subscriptions.delete(o.params.resource);break;case"dispatchAction":if(r){this._logService.trace(`[ProtocolServer] dispatchAction: ${JSON.stringify(o.params.action.type)}`);let s=o.params.action;this._agentService.dispatchAction(s,r.clientId,o.params.clientSeq)}break}else if(_c(o)){let s=this._pendingReverseRequests.get(o.id);s&&(this._pendingReverseRequests.delete(o.id),We(o,{error:!0})?s.reject(new Error(o.error?.message??"Reverse RPC error")):s.resolve(o.result))}})),n.add(e.onClose(()=>{r&&this._clients.get(r.clientId)===r&&(this._logService.info(`[ProtocolServer] Client disconnected: ${r.clientId}`),this._clients.delete(r.clientId),this._rejectPendingReverseRequests(r.clientId),this._onDidChangeConnectionCount.fire(this._clients.size)),n.dispose()})),n.add(e)}_handleInitialize(e,n,r){if(this._logService.info(`[ProtocolServer] Initialize: clientId=${e.clientId}, version=${e.protocolVersion}`),e.protocolVersion<1)throw new H(dp,`Client protocol version ${e.protocolVersion} is below minimum ${1}`);let o={clientId:e.clientId,protocolVersion:e.protocolVersion,transport:n,subscriptions:new Set,disposables:r};this._clients.set(e.clientId,o),this._onDidChangeConnectionCount.fire(this._clients.size),r.add(this._clientFileSystemProvider.registerAuthority(e.clientId,{resourceList:a=>this._sendReverseRequest(e.clientId,"resourceList",{uri:a.toString()}),resourceRead:a=>this._sendReverseRequest(e.clientId,"resourceRead",{uri:a.toString()}),resourceWrite:a=>this._sendReverseRequest(e.clientId,"resourceWrite",a),resourceDelete:a=>this._sendReverseRequest(e.clientId,"resourceDelete",a),resourceMove:a=>this._sendReverseRequest(e.clientId,"resourceMove",a)}));let s=[];if(e.initialSubscriptions)for(let a of e.initialSubscriptions){let l=this._stateManager.getSnapshot(a);l&&(s.push(l),o.subscriptions.add(a.toString()))}return{client:o,response:{protocolVersion:1,serverSeq:this._stateManager.serverSeq,snapshots:s,defaultDirectory:this._config.defaultDirectory}}}_handleReconnect(e,n,r){this._logService.info(`[ProtocolServer] Reconnect: clientId=${e.clientId}, lastSeenSeq=${e.lastSeenServerSeq}`);let o={clientId:e.clientId,protocolVersion:1,transport:n,subscriptions:new Set,disposables:r};this._clients.set(e.clientId,o),this._onDidChangeConnectionCount.fire(this._clients.size);let s=this._replayBuffer.length>0?this._replayBuffer[0].serverSeq:this._stateManager.serverSeq;if(e.lastSeenServerSeq>=s){let l=[];for(let c of e.subscriptions)o.subscriptions.add(c.toString());for(let c of this._replayBuffer)c.serverSeq>e.lastSeenServerSeq&&this._isRelevantToClient(o,c)&&l.push(c);return{client:o,response:{type:"replay",actions:l}}}else{let l=[];for(let c of e.subscriptions){let p=this._stateManager.getSnapshot(c);p&&(l.push(p),o.subscriptions.add(c))}return{client:o,response:{type:"snapshot",snapshots:l}}}}_sendReverseRequest(e,n,r){let o=this._clients.get(e);if(!o)return Promise.reject(new Error(`Client ${e} is not connected`));let s=++this._reverseRequestId;return new Promise((a,l)=>{this._pendingReverseRequests.set(s,{clientId:e,resolve:a,reject:l});let c={jsonrpc:"2.0",id:s,method:n,params:r};o.transport.send(c)})}_rejectPendingReverseRequests(e){for(let[n,r]of this._pendingReverseRequests)r.clientId===e&&(this._pendingReverseRequests.delete(n),r.reject(new Error(`Client ${e} disconnected`)))}_handleRequest(e,n,r,o){let s=this._requestHandlers.hasOwnProperty(n)?this._requestHandlers[n]:void 0;if(s){s(e,r).then(l=>{this._logService.trace(`[ProtocolServer] Request '${n}' id=${o} succeeded`),e.transport.send(Ys(o,l??null))}).catch(l=>{this._logService.error(`[ProtocolServer] Request '${n}' failed`,l),e.transport.send(Xs(o,l))});return}let a=this._handleExtensionRequest(n,r);if(a){a.then(l=>{e.transport.send(Ys(o,l??null))}).catch(l=>{this._logService.error(`[ProtocolServer] Extension request '${n}' failed`,l),e.transport.send(Xs(o,l))});return}e.transport.send(Ec(o,Tr,`Unknown method: ${n}`))}_handleExtensionRequest(e,n){if(e==="shutdown")return this._agentService.shutdown()}_broadcastAction(e){this._logService.trace(`[ProtocolServer] Broadcasting action: ${e.action.type}`);let n={jsonrpc:"2.0",method:"action",params:e};for(let r of this._clients.values())this._isRelevantToClient(r,e)&&r.transport.send(n)}_broadcastNotification(e){let n={jsonrpc:"2.0",method:"notification",params:{notification:e}};for(let r of this._clients.values())r.transport.send(n)}_isRelevantToClient(e,n){let r=n.action;return r.type.startsWith("root/")?e.subscriptions.has(os):Sr(r)?e.subscriptions.has(r.session):ts(r)?e.subscriptions.has(r.terminal):!1}dispose(){for(let e of this._clients.values())e.disposables.dispose();this._clients.clear();for(let[,e]of this._pendingReverseRequests)e.reject(new Error("ProtocolServerHandler disposed"));this._pendingReverseRequests.clear(),this._replayBuffer.length=0,super.dispose()}};qn=O([K(5,ue)],qn);var Cc=class extends L{constructor(e,n){super();this._ws=e;this._WebSocket=n;this._onMessage=this._register(new x);this.onMessage=this._onMessage.event;this._onClose=this._register(new x);this.onClose=this._onClose.event;this._ws.on("message",r=>{try{let o=typeof r=="string"?r:r.toString("utf-8"),s=JSON.parse(o);this._onMessage.fire(s)}catch{this.send({jsonrpc:"2.0",id:null,error:{code:lp,message:"Parse error"}})}}),this._ws.on("close",()=>{this._onClose.fire()}),this._ws.on("error",()=>{this._onClose.fire()})}send(e){this._ws.readyState===this._WebSocket.OPEN&&this._ws.send(JSON.stringify(e))}dispose(){this._ws.close(),super.dispose()}},Hi=class i extends L{constructor(e,n,r,o,s){super();this._logService=n;this._onConnection=this._register(new x);this.onConnection=this._onConnection.event;this._WebSocket=r.WebSocket;let a=typeof e=="number"?{port:e}:e,l=a.host??"127.0.0.1",c=a.connectionTokenValidate?(p,u)=>{let m=s.parse(p.req.url??"",!0).query[Za];if(!a.connectionTokenValidate(m)){this._logService.warn("[WebSocketProtocol] Connection rejected: invalid connection token"),u(!1,403,"Forbidden");return}u(!0)}:void 0;a.socketPath?(this._httpServer=o.createServer(),this._wss=new r.WebSocketServer({server:this._httpServer,verifyClient:c}),this._httpServer.listen(a.socketPath,()=>{this._logService.info(`[WebSocketProtocol] Server listening on socket ${a.socketPath}`)})):(this._wss=new r.WebSocketServer({port:a.port,host:l,verifyClient:c}),this._logService.info(`[WebSocketProtocol] Server listening on ${l}:${a.port}`)),this._wss.on("connection",p=>{this._logService.trace("[WebSocketProtocol] New client connection");let u=new Cc(p,this._WebSocket);this._onConnection.fire(u)}),this._wss.on("error",p=>{this._logService.error("[WebSocketProtocol] Server error",p)})}get address(){let e=this._wss.address();return!e||typeof e=="string"?e??void 0:`${e.address}:${e.port}`}static async create(e,n){let[r,o,s]=await Promise.all([import("ws"),import("http"),import("url")]);return new i(e,n,r,o,s)}dispose(){this._wss.close(),this._httpServer?.close(),super.dispose()}};import{homedir as fb,tmpdir as gb}from"os";var sb=60,ab=sb*60,Rc=ab*24,AA=Rc*7,kA=Rc*30,DA=Rc*365;function zf(i){return i.getFullYear()+"-"+String(i.getMonth()+1).padStart(2,"0")+"-"+String(i.getDate()).padStart(2,"0")+"T"+String(i.getHours()).padStart(2,"0")+":"+String(i.getMinutes()).padStart(2,"0")+":"+String(i.getSeconds()).padStart(2,"0")+"."+(i.getMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"}var jf=/^([^.]+\..+)[:=](.+)$/,G=class{constructor(t,e,n){this._args=t;this.paths=e;this.productService=n}get appRoot(){return me(Xe.asFileUri("").fsPath)}get userHome(){return b.file(this.paths.homeDir)}get userDataPath(){return this.paths.userDataDir}get appSettingsHome(){return b.file(q(this.userDataPath,"User"))}get tmpDir(){return b.file(this.paths.tmpDir)}get cacheHome(){return b.file(this.userDataPath)}get stateResource(){return te(this.appSettingsHome,"globalStorage","storage.json")}get userRoamingDataHome(){return this.appSettingsHome.with({scheme:ee.vscodeUserData})}get userDataSyncHome(){return te(this.appSettingsHome,"sync")}get logsHome(){if(!this.args.logsPath){let t=zf(new Date).replace(/-|:|\.\d+Z$/g,"");this.args.logsPath=q(this.userDataPath,"logs",t)}return b.file(this.args.logsPath)}get sync(){return this.args.sync}get workspaceStorageHome(){return te(this.appSettingsHome,"workspaceStorage")}get localHistoryHome(){return te(this.appSettingsHome,"History")}get keyboardLayoutResource(){return te(this.userRoamingDataHome,"keyboardLayout.json")}get argvResource(){let t=be.VSCODE_PORTABLE;return t?b.file(q(t,"argv.json")):te(this.appSettingsHome,"argv.json")}get isExtensionDevelopment(){return!!this.args.extensionDevelopmentPath}get untitledWorkspacesHome(){return b.file(q(this.userDataPath,"Workspaces"))}get builtinExtensionsPath(){let t=this.args["builtin-extensions-dir"];return t?xn(t):ot(q(Xe.asFileUri("").fsPath,"..","extensions"))}get extensionsDownloadLocation(){let t=this.args["extensions-download-dir"];return t?b.file(xn(t)):b.file(q(this.userDataPath,"CachedExtensionVSIXs"))}get extensionsPath(){let t=this.args["extensions-dir"];if(t)return xn(t);let e=be.VSCODE_EXTENSIONS;if(e)return e;let n=be.VSCODE_PORTABLE;return n?q(n,"extensions"):te(this.userHome,this.productService.dataFolderName,"extensions").fsPath}get agentPluginsPath(){let t=this.args["agent-plugins-dir"];if(t)return xn(t);let e=be.VSCODE_AGENT_PLUGINS;if(e)return e;let n=be.VSCODE_PORTABLE;return n?q(n,"agent-plugins"):te(this.userHome,this.productService.dataFolderName,"agent-plugins").fsPath}get extensionDevelopmentLocationURI(){let t=this.args.extensionDevelopmentPath;if(Array.isArray(t))return t.map(e=>/^[^:/?#]+?:\/\//.test(e)?b.parse(e):b.file(ot(e)))}get extensionDevelopmentKind(){return this.args.extensionDevelopmentKind?.map(t=>t==="ui"||t==="workspace"||t==="web"?t:"workspace")}get extensionTestsLocationURI(){let t=this.args.extensionTestsPath;if(t)return/^[^:/?#]+?:\/\//.test(t)?b.parse(t):b.file(ot(t))}get disableExtensions(){if(this.args["disable-extensions"])return!0;let t=this.args["disable-extension"];if(t){if(typeof t=="string")return[t];if(Array.isArray(t)&&t.length>0)return t}return!1}get skipBuiltinExtensions(){let t=be.VSCODE_SKIP_BUILTIN_EXTENSIONS;return t?t.split(",").map(e=>e.trim()).filter(e=>e):[]}get debugExtensionHost(){return lb(this.args,this.isBuilt)}get debugRenderer(){return!!this.args.debugRenderer}get isBuilt(){return!be.VSCODE_DEV}get verbose(){return!!this.args.verbose}get logLevel(){return this.args.log?.find(t=>!jf.test(t))}get extensionLogLevel(){let t=[];for(let e of this.args.log||[]){let n=jf.exec(e);n?.[1]&&n[2]&&t.push([n[1],n[2]])}return t.length?t:void 0}get serviceMachineIdResource(){return te(b.file(this.userDataPath),"machineid")}get crashReporterId(){return this.args["crash-reporter-id"]}get crashReporterDirectory(){return this.args["crash-reporter-directory"]}get disableTelemetry(){return!!this.args["disable-telemetry"]}get disableExperiments(){return!!this.args["disable-experiments"]}get disableWorkspaceTrust(){return!!this.args["disable-workspace-trust"]}get useInMemorySecretStorage(){return!!this.args["use-inmemory-secretstorage"]}get policyFile(){if(this.args["__enable-file-policy"]){let t=be.VSCODE_PORTABLE;return t?b.file(q(t,"policy.json")):te(this.userHome,this.productService.dataFolderName,"policy.json")}}get agentSessionsWorkspace(){return te(this.appSettingsHome,"agent-sessions.code-workspace")}get editSessionId(){return this.args.editSessionId}get exportPolicyData(){return this.args["export-policy-data"]}get exportDefaultKeybindings(){return this.args["export-default-keybindings"]}get continueOn(){return this.args.continueOn}set continueOn(t){this.args.continueOn=t}get args(){return this._args}};O([J],G.prototype,"appRoot",1),O([J],G.prototype,"userHome",1),O([J],G.prototype,"userDataPath",1),O([J],G.prototype,"appSettingsHome",1),O([J],G.prototype,"tmpDir",1),O([J],G.prototype,"cacheHome",1),O([J],G.prototype,"stateResource",1),O([J],G.prototype,"userRoamingDataHome",1),O([J],G.prototype,"userDataSyncHome",1),O([J],G.prototype,"sync",1),O([J],G.prototype,"workspaceStorageHome",1),O([J],G.prototype,"localHistoryHome",1),O([J],G.prototype,"keyboardLayoutResource",1),O([J],G.prototype,"argvResource",1),O([J],G.prototype,"isExtensionDevelopment",1),O([J],G.prototype,"untitledWorkspacesHome",1),O([J],G.prototype,"builtinExtensionsPath",1),O([J],G.prototype,"extensionsDownloadLocation",1),O([J],G.prototype,"extensionsPath",1),O([J],G.prototype,"agentPluginsPath",1),O([J],G.prototype,"extensionDevelopmentLocationURI",1),O([J],G.prototype,"extensionDevelopmentKind",1),O([J],G.prototype,"extensionTestsLocationURI",1),O([J],G.prototype,"debugExtensionHost",1),O([J],G.prototype,"logLevel",1),O([J],G.prototype,"extensionLogLevel",1),O([J],G.prototype,"serviceMachineIdResource",1),O([J],G.prototype,"disableTelemetry",1),O([J],G.prototype,"disableExperiments",1),O([J],G.prototype,"disableWorkspaceTrust",1),O([J],G.prototype,"useInMemorySecretStorage",1),O([J],G.prototype,"policyFile",1),O([J],G.prototype,"agentSessionsWorkspace",1);function lb(i,t){return Hf(i["inspect-extensions"],i["inspect-brk-extensions"],5870,t,i.debugId,i.extensionEnvironment)}function Hf(i,t,e,n,r,o){let a=Number(t||i)||(n?null:e),l=a?!!t:!1,c;if(o)try{c=JSON.parse(o)}catch{}return{port:a,break:l,debugId:r,env:c}}import{homedir as Gf}from"os";import{resolve as cb,isAbsolute as db,join as Kr}from"path";var ub=process.env.VSCODE_CWD||process.cwd();function Jf(i,t){let e=pb(i,t),n=[e];return db(e)||n.unshift(ub),cb(...n)}function pb(i,t){process.env.VSCODE_DEV&&(process.isEmbeddedApp?t="agents-oss-dev":t="code-oss-dev");let e=process.env.VSCODE_PORTABLE;if(e)return Kr(e,"user-data");let n=process.env.VSCODE_APPDATA;if(n)return Kr(n,t);let r=i["user-data-dir"];if(r)return r;switch(process.platform){case"win32":if(n=process.env.APPDATA,!n){let o=process.env.USERPROFILE;if(typeof o!="string")throw new Error("Windows: Unexpected undefined %USERPROFILE% environment variable");n=Kr(o,"AppData","Roaming")}break;case"darwin":n=Kr(Gf(),"Library","Application Support");break;case"linux":n=process.env.XDG_CONFIG_HOME||Kr(Gf(),".config");break;default:throw new Error("Platform not supported")}return Kr(n,t)}var Zs=class extends G{constructor(t,e){super(t,{homeDir:fb(),tmpDir:gb(),userDataDir:Jf(t,e.nameShort)},e)}};import mb from"minimist";var ZA={o:g(1966,null),e:g(1950,null),t:g(1980,null),m:g(1961,null)};var Qf={chat:{type:"subcommand",description:"Pass in a prompt to run in a chat session in the current working directory.",options:{_:{type:"string[]",description:g(1970,null)},mode:{type:"string",cat:"o",alias:"m",args:"mode",description:g(1937,null)},"add-file":{type:"string[]",cat:"o",alias:"a",args:"path",description:g(1932,null)},maximize:{type:"boolean",cat:"o",description:g(1936,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:g(1973,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:g(1964,null)},profile:{type:"string",cat:"o",args:"profileName",description:g(1969,null)},help:{type:"boolean",alias:"h",description:g(1952,null)}}},"serve-web":{type:"subcommand",description:"Run a server that displays the editor UI in browsers.",options:{"cli-data-dir":{type:"string",args:"dir",description:g(1938,null)},"disable-telemetry":{type:"boolean"},"telemetry-level":{type:"string"}}},"agent-host":{type:"subcommand",description:"Run a server that hosts agents.",options:{"cli-data-dir":{type:"string",args:"dir",description:g(1938,null)},"disable-telemetry":{type:"boolean"},"telemetry-level":{type:"string"}}},tunnel:{type:"subcommand",description:"Make the current machine accessible from vscode.dev or other machines through a secure tunnel.",options:{"cli-data-dir":{type:"string",args:"dir",description:g(1938,null)},"disable-telemetry":{type:"boolean"},"telemetry-level":{type:"string"},user:{type:"subcommand",options:{login:{type:"subcommand",options:{provider:{type:"string"},"access-token":{type:"string"}}}}}}},diff:{type:"boolean",cat:"o",alias:"d",args:["file","file"],description:g(1942,null)},merge:{type:"boolean",cat:"o",alias:"m",args:["path1","path2","base","result"],description:g(1962,null)},add:{type:"boolean",cat:"o",alias:"a",args:"folder",description:g(1931,null)},remove:{type:"boolean",cat:"o",args:"folder",description:g(1971,null)},goto:{type:"boolean",cat:"o",alias:"g",args:"file:line[:character]",description:g(1951,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:g(1963,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:g(1972,null)},agents:{type:"boolean",cat:"o",deprecates:["sessions"],description:g(1934,null)},wait:{type:"boolean",cat:"o",alias:"w",description:g(1990,null)},waitMarkerFilePath:{type:"string"},locale:{type:"string",cat:"o",args:"locale",description:g(1958,null)},"user-data-dir":{type:"string",cat:"o",args:"dir",description:g(1987,null)},profile:{type:"string",cat:"o",args:"profileName",description:g(1969,null)},help:{type:"boolean",cat:"o",alias:"h",description:g(1952,null)},"stdin-to-clipboard":{type:"boolean",cat:"o",alias:"c",description:g(1939,null)},"extensions-dir":{type:"string",deprecates:["extensionHomePath"],cat:"e",args:"dir",description:g(1949,null)},"extensions-download-dir":{type:"string"},"builtin-extensions-dir":{type:"string"},"list-extensions":{type:"boolean",cat:"e",description:g(1957,null)},"agent-plugins-dir":{type:"string"},"show-versions":{type:"boolean",cat:"e",description:g(1974,null)},category:{type:"string",allowEmptyValue:!0,cat:"e",description:g(1935,null),args:"category"},"install-extension":{type:"string[]",cat:"e",args:"ext-id | path",description:g(1956,null)},"pre-release":{type:"boolean",cat:"e",description:g(1955,null)},"uninstall-extension":{type:"string[]",cat:"e",args:"ext-id",description:g(1982,null)},"update-extensions":{type:"boolean",cat:"e",description:g(1985,null)},"enable-proposed-api":{type:"string[]",allowEmptyValue:!0,cat:"e",args:"ext-id",description:g(1948,null)},"add-mcp":{type:"string[]",cat:"m",args:"json",description:g(1933,null)},version:{type:"boolean",cat:"t",alias:"v",description:g(1989,null)},verbose:{type:"boolean",cat:"t",global:!0,description:g(1988,null)},log:{type:"string[]",cat:"t",args:"level",global:!0,description:g(1960,null)},status:{type:"boolean",alias:"s",cat:"t",description:g(1975,null)},"prof-startup":{type:"boolean",cat:"t",description:g(1968,null)},"prof-append-timers":{type:"string"},"prof-duration-markers":{type:"string[]"},"prof-duration-markers-file":{type:"string"},"no-cached-data":{type:"boolean"},"prof-startup-prefix":{type:"string"},"prof-v8-extensions":{type:"boolean"},"disable-extensions":{type:"boolean",deprecates:["disableExtensions"],cat:"t",description:g(1945,null)},"disable-extension":{type:"string[]",cat:"t",args:"ext-id",description:g(1944,null)},sync:{type:"string",cat:"t",description:g(1981,null),args:["on | off"]},"inspect-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugPluginHost"],args:"port",cat:"t",description:g(1954,null)},"inspect-brk-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugBrkPluginHost"],args:"port",cat:"t",description:g(1953,null)},"disable-lcd-text":{type:"boolean",cat:"t",description:g(1947,null)},"disable-gpu":{type:"boolean",cat:"t",description:g(1946,null)},"disable-chromium-sandbox":{type:"boolean",cat:"t",description:g(1943,null)},sandbox:{type:"boolean"},"locate-shell-integration-path":{type:"string",cat:"t",args:["shell"],description:g(1959,null)},telemetry:{type:"boolean",cat:"t",description:g(1978,null)},remote:{type:"string",allowEmptyValue:!0},"folder-uri":{type:"string[]",cat:"o",args:"uri"},"file-uri":{type:"string[]",cat:"o",args:"uri"},"locate-extension":{type:"string[]"},extensionDevelopmentPath:{type:"string[]"},extensionDevelopmentKind:{type:"string[]"},extensionTestsPath:{type:"string"},extensionEnvironment:{type:"string"},debugId:{type:"string"},debugRenderer:{type:"boolean"},"inspect-ptyhost":{type:"string",allowEmptyValue:!0},"inspect-brk-ptyhost":{type:"string",allowEmptyValue:!0},"inspect-agenthost":{type:"string",allowEmptyValue:!0},"inspect-brk-agenthost":{type:"string",allowEmptyValue:!0},"inspect-search":{type:"string",deprecates:["debugSearch"],allowEmptyValue:!0},"inspect-brk-search":{type:"string",deprecates:["debugBrkSearch"],allowEmptyValue:!0},"inspect-sharedprocess":{type:"string",allowEmptyValue:!0},"inspect-brk-sharedprocess":{type:"string",allowEmptyValue:!0},"export-default-configuration":{type:"string"},"export-policy-data":{type:"string",allowEmptyValue:!0},"export-default-keybindings":{type:"string",allowEmptyValue:!0},"install-source":{type:"string"},"enable-smoke-test-driver":{type:"boolean"},"skip-sessions-welcome":{type:"boolean"},logExtensionHostCommunication:{type:"boolean"},"skip-release-notes":{type:"boolean"},"skip-welcome":{type:"boolean"},"disable-telemetry":{type:"boolean"},"disable-updates":{type:"boolean"},"share-secrets-with-agents-app":{type:"boolean"},transient:{type:"boolean",cat:"t",description:g(1979,null)},"use-inmemory-secretstorage":{type:"boolean",deprecates:["disable-keytar"]},"password-store":{type:"string"},"disable-workspace-trust":{type:"boolean"},"disable-crash-reporter":{type:"boolean"},"crash-reporter-directory":{type:"string"},"crash-reporter-id":{type:"string"},"skip-add-to-recently-opened":{type:"boolean"},"open-url":{type:"boolean"},"file-write":{type:"boolean"},"file-chmod":{type:"boolean"},"install-builtin-extension":{type:"string[]"},force:{type:"boolean"},"do-not-sync":{type:"boolean"},"do-not-include-pack-dependencies":{type:"boolean"},trace:{type:"boolean"},"trace-memory-infra":{type:"boolean"},"trace-category-filter":{type:"string"},"trace-options":{type:"string"},"preserve-env":{type:"boolean"},"force-user-env":{type:"boolean"},"force-disable-user-env":{type:"boolean"},"open-devtools":{type:"boolean"},"disable-gpu-sandbox":{type:"boolean"},logsPath:{type:"string"},"__enable-file-policy":{type:"boolean"},editSessionId:{type:"string"},continueOn:{type:"string"},"enable-coi":{type:"boolean"},"unresponsive-sample-interval":{type:"string"},"unresponsive-sample-period":{type:"string"},"enable-rdp-display-tracking":{type:"boolean"},"disable-layout-restore":{type:"boolean"},"disable-experiments":{type:"boolean"},"no-proxy-server":{type:"boolean"},"no-sandbox":{type:"boolean",alias:"sandbox"},"proxy-server":{type:"string"},"proxy-bypass-list":{type:"string"},"proxy-pac-url":{type:"string"},"js-flags":{type:"string"},inspect:{type:"string",allowEmptyValue:!0},"inspect-brk":{type:"string",allowEmptyValue:!0},nolazy:{type:"boolean"},"force-device-scale-factor":{type:"string"},"force-renderer-accessibility":{type:"boolean"},"ignore-certificate-errors":{type:"boolean"},"allow-insecure-localhost":{type:"boolean"},"log-net-log":{type:"string"},vmodule:{type:"string"},_urls:{type:"string[]"},"disable-dev-shm-usage":{type:"boolean"},"profile-temp":{type:"boolean"},"ozone-platform":{type:"string"},"enable-tracing":{type:"string"},"trace-startup-format":{type:"string"},"trace-startup-file":{type:"string"},"trace-startup-duration":{type:"string"},"xdg-portal-required-version":{type:"string"},_:{type:"string[]"}},hb={onUnknownOption:()=>{},onMultipleValues:()=>{},onEmptyValue:()=>{},onDeprecatedOption:()=>{}};function wc(i,t,e=hb){let n=i.find((f,m)=>f.length>0&&f[0]!=="-"&&t.hasOwnProperty(f)&&t[f].type==="subcommand"),r={},o=["_"],s=[],a={},l;for(let f in t){let m=t[f];m.type==="subcommand"?f===n&&(l=m):(m.alias&&(r[f]=m.alias),m.type==="string"||m.type==="string[]"?(o.push(f),m.deprecates&&o.push(...m.deprecates)):m.type==="boolean"&&(s.push(f),m.deprecates&&s.push(...m.deprecates)),m.global&&(a[f]=m))}if(l&&n){let f=a;for(let I in l.options)f[I]=l.options[I];let m=i.filter(I=>I!==n),v=e.getSubcommandReporter?e.getSubcommandReporter(n):void 0,h=wc(m,f,v);return{[n]:h,_:[]}}let c=mb(i,{string:o,boolean:s,alias:r}),p={},u=c;p._=c._.map(f=>String(f)).filter(f=>f.length>0),delete u._;for(let f in t){let m=t[f];if(m.type==="subcommand")continue;m.alias&&delete u[m.alias];let v=u[f];if(m.deprecates)for(let h of m.deprecates)u.hasOwnProperty(h)&&(v||(v=u[h],v&&e.onDeprecatedOption(h,m.deprecationMessage||g(1941,null,f))),delete u[h]);if(typeof v<"u"){if(m.type==="string[]"){if(Array.isArray(v)||(v=[v]),!m.allowEmptyValue){let h=v.filter(I=>I.length>0);h.length!==v.length&&(e.onEmptyValue(f),v=h.length>0?h:void 0)}}else m.type==="string"&&(Array.isArray(v)?(v=v.pop(),e.onMultipleValues(f,v)):!v&&!m.allowEmptyValue&&(e.onEmptyValue(f),v=void 0));p[f]=v,m.deprecationMessage&&e.onDeprecatedOption(f,m.deprecationMessage)}delete u[f]}for(let f in u)e.onUnknownOption(f);return p}var ea=class extends L{constructor(t,e=[]){super(),this.logger=new vs([t,...e]),this._register(t.onDidChangeLogLevel(n=>this.setLevel(n)))}get onDidChangeLogLevel(){return this.logger.onDidChangeLogLevel}setLevel(t){this.logger.setLevel(t)}getLevel(){return this.logger.getLevel()}trace(t,...e){this.logger.trace(t,...e)}debug(t,...e){this.logger.debug(t,...e)}info(t,...e){this.logger.info(t,...e)}warn(t,...e){this.logger.warn(t,...e)}error(t,...e){this.logger.error(t,...e)}flush(){this.logger.flush()}};async function bb(i,t,e,n,r){try{let o=await import("@vscode/spdlog");o.setFlushOn(0);let s=await o.createAsyncRotatingLogger(i,t,e,n);return r?s.clearFormatters():s.setPattern("%Y-%m-%d %H:%M:%S.%e [%l] %v"),s}catch(o){console.error(o)}return null}function Yf(i,t,e){switch(t){case 1:i.trace(e);break;case 2:i.debug(e);break;case 3:i.info(e);break;case 4:i.warn(e);break;case 5:i.error(e);break;case 0:break;default:throw new Error(`Invalid log level ${t}`)}}function Xf(i,t){switch(t){case 1:i.setLevel(0);break;case 2:i.setLevel(1);break;case 3:i.setLevel(2);break;case 4:i.setLevel(3);break;case 5:i.setLevel(4);break;case 0:i.setLevel(6);break;default:throw new Error(`Invalid log level ${t}`)}}var ta=class extends Fi{constructor(e,n,r,o,s){super();this.buffer=[];this.setLevel(s),this._loggerCreationPromise=this._createSpdLogLogger(e,n,r,o),this._register(this.onDidChangeLogLevel(a=>{this._logger&&Xf(this._logger,a)}))}async _createSpdLogLogger(e,n,r,o){let s=r?6:1,a=30/s*Yo.MB,l=await bb(e,n,a,s,o);if(l){this._logger=l,Xf(this._logger,this.getLevel());for(let{level:c,message:p}of this.buffer)Yf(this._logger,c,p);this.buffer=[]}}log(e,n){this._logger?Yf(this._logger,e,n):this.getLevel()<=e&&this.buffer.push({level:e,message:n})}flush(){this._logger?this.flushLogger():this._loggerCreationPromise.then(()=>this.flushLogger())}dispose(){this._logger?this.disposeLogger():this._loggerCreationPromise.then(()=>this.disposeLogger()),super.dispose()}flushLogger(){this._logger&&this._logger.flush()}disposeLogger(){this._logger&&(this._logger.drop(),this._logger=void 0)}};var na=class extends Ui{doCreateLogger(t,e,n){return new ta(ne(),t.fsPath,!n?.donotRotate,!!n?.donotUseFormatters,e)}};var ra=class{constructor(t,e){this.loggerService=t;this.getUriTransformer=e}listen(t,e){let n=this.getUriTransformer(t);switch(e){case"onDidChangeLoggers":return Q.map(this.loggerService.onDidChangeLoggers,r=>({added:[...r.added].map(o=>this.transformLogger(o,n)),removed:[...r.removed].map(o=>this.transformLogger(o,n))}));case"onDidChangeVisibility":return Q.map(this.loggerService.onDidChangeVisibility,r=>[n.transformOutgoingURI(r[0]),r[1]]);case"onDidChangeLogLevel":return Q.map(this.loggerService.onDidChangeLogLevel,r=>Yl(r)?r:[n.transformOutgoingURI(r[0]),r[1]])}throw new Error(`Event not found: ${e}`)}async call(t,e,n){let r=this.getUriTransformer(t);switch(e){case"setLogLevel":return Yl(n[0])?this.loggerService.setLogLevel(n[0]):this.loggerService.setLogLevel(b.revive(r.transformIncoming(n[0][0])),n[0][1]);case"getRegisteredLoggers":return Promise.resolve([...this.loggerService.getRegisteredLoggers()].map(o=>this.transformLogger(o,r)))}throw new Error(`Call not found: ${e}`)}transformLogger(t,e){return{...t,resource:e.transformOutgoingURI(t.resource)}}};var Zf=new class{transformIncoming(i){return i}transformOutgoing(i){return i}transformOutgoingURI(i){return i}transformOutgoingScheme(i){return i}};var Ve,Pc=globalThis.vscode;if(typeof Pc<"u"&&typeof Pc.context<"u"){let i=Pc.context.configuration();if(i)Ve=i.product;else throw new Error("Sandbox: unable to resolve product configuration from preload script.")}else if(globalThis._VSCODE_PRODUCT_JSON&&globalThis._VSCODE_PACKAGE_JSON){if(Ve=globalThis._VSCODE_PRODUCT_JSON,be.VSCODE_DEV&&Object.assign(Ve,{nameShort:`${Ve.nameShort} Dev`,nameLong:`${Ve.nameLong} Dev`,dataFolderName:`${Ve.dataFolderName}-dev`,serverDataFolderName:Ve.serverDataFolderName?`${Ve.serverDataFolderName}-dev`:void 0}),!Ve.version){let i=globalThis._VSCODE_PACKAGE_JSON;Object.assign(Ve,{version:i.version})}Object.assign(Ve,{extensionsGallery:be.EXTENSIONS_GALLERY?JSON.parse(be.EXTENSIONS_GALLERY):Ve.extensionsGallery||{serviceUrl:"https://open-vsx.org/vscode/gallery",itemUrl:"https://open-vsx.org/vscode/item",extensionUrlTemplate:"https://open-vsx.org/vscode/gallery/{publisher}/{name}/latest",resourceUrlTemplate:"https://open-vsx.org/vscode/asset/{publisher}/{name}/{version}/Microsoft.VisualStudio.Code.WebResources/{path}",controlUrl:"",recommendationsUrl:""},telemetryEndpoint:be.CS_TELEMETRY_URL||Ve.telemetryEndpoint||"https://v1.telemetry.coder.com/track"})}else Ve={nameShort:"code-server",nameLong:"code-server",applicationName:"code-server",dataFolderName:".code-server",win32MutexName:"codeserver",licenseName:"MIT",licenseUrl:"https://github.com/coder/code-server/blob/main/LICENSE",serverLicenseUrl:"https://github.com/microsoft/vscode/blob/main/LICENSE.txt",serverGreeting:[],serverLicense:[],serverLicensePrompt:"",serverApplicationName:"code-server-oss",serverDataFolderName:".vscode-server-oss",tunnelApplicationName:"code-tunnel-oss",win32DirName:"code-server",win32NameVersion:"code-server",win32RegValueName:"CodeOSS",win32x64AppId:"{{D77B7E06-80BA-4137-BCF4-654B95CCEBC5}",win32arm64AppId:"{{D1ACE434-89C5-48D1-88D3-E2991DF85475}",win32x64UserAppId:"{{CC6B787D-37A0-49E8-AE24-8559A032BE0C}",win32arm64UserAppId:"{{3AEBF0C8-F733-4AD4-BADE-FDB816D53D7B}",win32AppUserModelId:"coder.code-server",win32ShellNameShort:"c&ode-server",win32TunnelServiceMutex:"vscodeoss-tunnelservice",win32TunnelMutex:"vscodeoss-tunnel",darwinBundleIdentifier:"com.coder.code.server",darwinProfileUUID:"47827DD9-4734-49A0-AF80-7E19B11495CC",darwinProfilePayloadUUID:"CF808BE7-53F3-46C6-A7E2-7EDB98A5E959",linuxIconName:"com.coder.code.server",licenseFileName:"LICENSE.txt",reportIssueUrl:"https://github.com/coder/code-server/issues/new",nodejsRepository:"https://nodejs.org",urlProtocol:"code-oss",webviewContentExternalBaseUrlTemplate:"https://{{uuid}}.vscode-cdn.net/insider/ef65ac1ba57f57f2a3961bfe94aa20481caca4c6/out/vs/workbench/contrib/webview/browser/pre/",builtInExtensions:[{name:"ms-vscode.js-debug-companion",version:"1.1.3",sha256:"7380a890787452f14b2db7835dfa94de538caf358ebc263f9d46dd68ac52de93",repo:"https://github.com/microsoft/vscode-js-debug-companion",metadata:{id:"99cb0b7f-7354-4278-b8da-6cc79972169d",publisherId:{publisherId:"5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",publisherName:"ms-vscode",displayName:"Microsoft",flags:"verified"},publisherDisplayName:"Microsoft"}},{name:"ms-vscode.js-debug",version:"1.117.0",sha256:"854eeb8a785b1f41ba2bd02d7ccd4fdbe10021b61473293973c7e96d036c7fb8",repo:"https://github.com/microsoft/vscode-js-debug",metadata:{id:"25629058-ddac-4e17-abba-74678e126c5d",publisherId:{publisherId:"5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",publisherName:"ms-vscode",displayName:"Microsoft",flags:"verified"},publisherDisplayName:"Microsoft"}},{name:"ms-vscode.vscode-js-profile-table",version:"1.0.10",sha256:"7361748ddf9fd09d8a2ed1f2a2d7376a2cf9aae708692820b799708385c38e08",repo:"https://github.com/microsoft/vscode-js-profile-visualizer",metadata:{id:"7e52b41b-71ad-457b-ab7e-0620f1fc4feb",publisherId:{publisherId:"5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",publisherName:"ms-vscode",displayName:"Microsoft",flags:"verified"},publisherDisplayName:"Microsoft"}}],defaultChatAgent:{extensionId:"GitHub.copilot",chatExtensionId:"GitHub.copilot-chat",chatExtensionOutputId:"GitHub.copilot-chat.GitHub Copilot Chat.log",chatExtensionOutputExtensionStateCommand:"github.copilot.debug.extensionState",documentationUrl:"https://aka.ms/github-copilot-overview",termsStatementUrl:"https://aka.ms/github-copilot-terms-statement",privacyStatementUrl:"https://aka.ms/github-copilot-privacy-statement",skusDocumentationUrl:"https://aka.ms/github-copilot-plans",publicCodeMatchesUrl:"https://aka.ms/github-copilot-match-public-code",manageSettingsUrl:"https://aka.ms/github-copilot-settings",managePlanUrl:"https://aka.ms/github-copilot-manage-plan",manageOverageUrl:"https://aka.ms/github-copilot-manage-overage",upgradePlanUrl:"https://aka.ms/github-copilot-upgrade-plan",signUpUrl:"https://aka.ms/github-sign-up",provider:{default:{id:"github",name:"GitHub"},enterprise:{id:"github-enterprise",name:"GHE"},google:{id:"google",name:"Google"},apple:{id:"apple",name:"Apple"}},providerExtensionId:"vscode.github-authentication",providerUriSetting:"github-enterprise.uri",providerScopes:[["read:user","user:email","repo","workflow"],["user:email"],["read:user"]],entitlementUrl:"https://api.github.com/copilot_internal/user",entitlementSignupLimitedUrl:"https://api.github.com/copilot_internal/subscribe_limited_user",chatQuotaExceededContext:"github.copilot.chat.quotaExceeded",completionsQuotaExceededContext:"github.copilot.completions.quotaExceeded",walkthroughCommand:"github.copilot.open.walkthrough",completionsMenuCommand:"github.copilot.toggleStatusMenu",completionsRefreshTokenCommand:"github.copilot.signIn",chatRefreshTokenCommand:"github.copilot.refreshToken",generateCommitMessageCommand:"github.copilot.git.generateCommitMessage",resolveMergeConflictsCommand:"github.copilot.git.resolveMergeConflicts",completionsAdvancedSetting:"github.copilot.advanced",completionsEnablementSetting:"github.copilot.enable",nextEditSuggestionsSetting:"github.copilot.nextEditSuggestions.enabled",tokenEntitlementUrl:"https://api.github.com/copilot_internal/v2/token",mcpRegistryDataUrl:"https://api.github.com/copilot/mcp_registry"},trustedExtensionAuthAccess:["vscode.git","vscode.github","github.vscode-pull-request-github","github.copilot","github.copilot-chat"],onboardingKeymaps:[{id:"vscode",label:"VS Code",description:"Default keyboard mapping"},{id:"sublime",label:"Sublime Text",extensionId:"ms-vscode.sublime-keybindings",description:"Keyboard mapping from Sublime Text"},{id:"intellij",label:"IntelliJ / JetBrains",extensionId:"k--kato.intellij-idea-keybindings",description:"Keyboard mapping from IntelliJ IDEA"},{id:"vim",label:"Vim",extensionId:"vscodevim.vim",description:"Vim modal editing"},{id:"eclipse",label:"Eclipse",extensionId:"alphabotsec.vscode-eclipse-keybindings",description:"Keyboard mapping from Eclipse"},{id:"notepadpp",label:"Notepad++",extensionId:"ms-vscode.notepadplusplus-keybindings",description:"Keyboard mapping from Notepad++"}],onboardingThemes:[{id:"dark-2026",label:"Dark 2026",themeId:"Dark 2026",type:"dark"},{id:"hc-dark",label:"Dark High Contrast",themeId:"Default High Contrast",type:"hcDark"},{id:"solarized-dark",label:"Solarized Dark",themeId:"Solarized Dark",type:"dark"},{id:"light-2026",label:"Light 2026",themeId:"Light 2026",type:"light"},{id:"hc-light",label:"Light High Contrast",themeId:"Default High Contrast Light",type:"hcLight"},{id:"solarized-light",label:"Solarized Light",themeId:"Solarized Light",type:"light"}],builtInExtensionsEnabledWithAutoUpdates:["GitHub.copilot-chat"],enableTelemetry:!0,quality:"stable",codeServerVersion:"4.117.0",documentationUrl:"https://go.microsoft.com/fwlink/?LinkID=533484#vscode",keyboardShortcutsUrlMac:"https://go.microsoft.com/fwlink/?linkid=832143",keyboardShortcutsUrlLinux:"https://go.microsoft.com/fwlink/?linkid=832144",keyboardShortcutsUrlWin:"https://go.microsoft.com/fwlink/?linkid=832145",introductoryVideosUrl:"https://go.microsoft.com/fwlink/?linkid=832146",tipsAndTricksUrl:"https://go.microsoft.com/fwlink/?linkid=852118",newsletterSignupUrl:"https://www.research.net/r/vsc-newsletter",linkProtectionTrustedDomains:["https://open-vsx.org"],aiConfig:{ariaKey:"code-server"},version:"1.117.0",commit:"ddeb0a3de0321412c0633dffa85d35770005ae0f",date:"2026-04-21T16:12:14-07:00"},Object.keys(Ve).length===0&&Object.assign(Ve,{version:"1.104.0-dev",nameShort:"Code - OSS Dev",nameLong:"Code - OSS Dev",applicationName:"code-oss",dataFolderName:".vscode-oss",urlProtocol:"code-oss",reportIssueUrl:"https://github.com/microsoft/vscode/issues/new",licenseName:"MIT",licenseUrl:"https://github.com/microsoft/vscode/blob/main/LICENSE.txt",serverLicenseUrl:"https://github.com/microsoft/vscode/blob/main/LICENSE.txt",defaultChatAgent:{extensionId:"GitHub.copilot",chatExtensionId:"GitHub.copilot-chat",provider:{default:{id:"github",name:"GitHub"},enterprise:{id:"github-enterprise",name:"GitHub Enterprise"}},providerScopes:[]}});var eg=Ve;function Ac(i){let t=[];typeof i=="number"&&t.push("code/timeOrigin",i);function e(o,s){t.push(o,s?.startTime??Date.now())}function n(){let o=[];for(let s=0;s<t.length;s+=2)o.push({name:t[s],startTime:t[s+1]});return o}function r(o){if(typeof o>"u"){let s=t.length>=2&&t[0]==="code/timeOrigin",a=s?t[1]:void 0;t.length=0,s&&t.push("code/timeOrigin",a)}else for(let s=t.length-2;s>=0;s-=2)t[s]===o&&t.splice(s,2)}return{mark:e,getMarks:n,clearMarks:r}}function yb(){if(typeof performance=="object"&&typeof performance.mark=="function"&&!performance.nodeTiming)return typeof performance.timeOrigin!="number"&&!performance.timing?Ac():{mark(i,t){performance.mark(i,t)},clearMarks(i){performance.clearMarks(i)},getMarks(){let i=performance.timeOrigin;typeof i!="number"&&(i=(performance.timing.navigationStart||performance.timing.redirectStart||performance.timing.fetchStart)??0);let t=[{name:"code/timeOrigin",startTime:Math.round(i)}];for(let e of performance.getEntriesByType("mark"))t.push({name:e.name,startTime:Math.round(i+e.startTime)});return t}};if(typeof process=="object"){let i=performance?.timeOrigin;return Ac(i)}else return console.trace("perf-util loaded in UNKNOWN environment"),Ac()}function Ib(i){return i.MonacoPerformanceMarks||(i.MonacoPerformanceMarks=yb()),i.MonacoPerformanceMarks}var kc=Ib(globalThis),tg=kc.mark,W8=kc.clearMarks,B8=kc.getMarks;async function ia(i,t,e,n,r,o){let s;try{await Sb(i,t,e,n,r,o)}catch(a){s=a}finally{s&&r.errorTransformer&&(s=r.errorTransformer(s)),typeof s<"u"&&e.error(s),e.end()}}async function Sb(i,t,e,n,r,o){Dc(o);let s=await i.open(t,{create:!1});try{Dc(o);let a=0,l=0,c=r&&typeof r.length=="number"?r.length:void 0,p=_.alloc(Math.min(r.bufferSize,typeof c=="number"?c:r.bufferSize)),u=r&&typeof r.position=="number"?r.position:0,f=0;do l=await i.read(s,u,p.buffer,f,p.byteLength-f),u+=l,f+=l,a+=l,typeof c=="number"&&(c-=l),f===p.byteLength&&(await e.write(n(p)),p=_.alloc(Math.min(r.bufferSize,typeof c=="number"?c:r.bufferSize)),f=0);while(l>0&&(typeof c!="number"||c>0)&&Dc(o)&&Tb(a,r));if(f>0){let m=f;typeof c=="number"&&(m=Math.min(f,c)),e.write(n(p.slice(0,m)))}}catch(a){throw Kt(a)}finally{await i.close(s)}}function Dc(i){if(i.isCancellationRequested)throw eo();return!0}function Tb(i,t){if(typeof t?.limits?.size=="number"&&i>t.limits.size)throw Y(g(2152,null),"EntryTooLarge");return!0}var mn=class extends L{constructor(e){super();this.logService=e;this.BUFFER_SIZE=256*1024;this._onDidChangeFileSystemProviderRegistrations=this._register(new x);this.onDidChangeFileSystemProviderRegistrations=this._onDidChangeFileSystemProviderRegistrations.event;this._onWillActivateFileSystemProvider=this._register(new x);this.onWillActivateFileSystemProvider=this._onWillActivateFileSystemProvider.event;this._onDidChangeFileSystemProviderCapabilities=this._register(new x);this.onDidChangeFileSystemProviderCapabilities=this._onDidChangeFileSystemProviderCapabilities.event;this.provider=new Map;this._onDidRunOperation=this._register(new x);this.onDidRunOperation=this._onDidRunOperation.event;this.internalOnDidFilesChange=this._register(new x);this._onDidUncorrelatedFilesChange=this._register(new x);this.onDidFilesChange=this._onDidUncorrelatedFilesChange.event;this._onDidWatchError=this._register(new x);this.onDidWatchError=this._onDidWatchError.event;this.activeWatchers=new Map;this.writeQueue=this._register(new tr)}registerProvider(e,n){if(this.provider.has(e))throw new Error(`A filesystem provider for the scheme '${e}' is already registered.`);tg(`code/registerFilesystem/${e}`);let r=new N;return this.provider.set(e,n),this._onDidChangeFileSystemProviderRegistrations.fire({added:!0,scheme:e,provider:n}),r.add(n.onDidChangeFile(o=>{let s=new Qo(o,!this.isPathCaseSensitive(n));this.internalOnDidFilesChange.fire(s),s.hasCorrelation()||this._onDidUncorrelatedFilesChange.fire(s)})),typeof n.onDidWatchError=="function"&&r.add(n.onDidWatchError(o=>this._onDidWatchError.fire(new Error(o)))),r.add(n.onDidChangeCapabilities(()=>this._onDidChangeFileSystemProviderCapabilities.fire({provider:n,scheme:e}))),w(()=>{this._onDidChangeFileSystemProviderRegistrations.fire({added:!1,scheme:e,provider:n}),this.provider.delete(e),Ke(r)})}getProvider(e){return this.provider.get(e)}async activateProvider(e){let n=[];this._onWillActivateFileSystemProvider.fire({scheme:e,join(r){n.push(r)}}),!this.provider.has(e)&&await wn.settled(n)}async canHandleResource(e){return await this.activateProvider(e.scheme),this.hasProvider(e)}hasProvider(e){return this.provider.has(e.scheme)}hasCapability(e,n){let r=this.provider.get(e.scheme);return!!(r&&r.capabilities&n)}listCapabilities(){return ei.map(this.provider,([e,n])=>({scheme:e,capabilities:n.capabilities}))}async withProvider(e){if(!eu(e))throw new Ce(g(2141,null,this.resourceForError(e)),8);await this.activateProvider(e.scheme);let n=this.provider.get(e.scheme);if(!n){let r=new vt;throw r.message=g(2143,null,e.toString()),r}return n}async withReadProvider(e){let n=await this.withProvider(e);if(qt(n)||nt(n)||Xo(n))return n;throw new Error(`Filesystem provider for scheme '${e.scheme}' neither has FileReadWrite, FileReadStream nor FileOpenReadWriteClose capability which is needed for the read operation.`)}async withWriteProvider(e){let n=await this.withProvider(e);if(qt(n)||nt(n))return n;throw new Error(`Filesystem provider for scheme '${e.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`)}async resolve(e,n){try{return await this.doResolveFile(e,n)}catch(r){throw xt(r)==="EntryNotFound"?new Ce(g(2138,null,this.resourceForError(e)),1):Kt(r)}}async doResolveFile(e,n){let r=await this.withProvider(e),o=this.isPathCaseSensitive(r),s=n?.resolveTo,a=n?.resolveSingleChildDescendants,l=n?.resolveMetadata,c=await r.stat(e),p;return this.toFileStat(r,e,c,void 0,!!l,(u,f)=>(p||(p=ln.forUris(()=>!o),p.set(e,!0),s&&p.fill(!0,s)),p.get(u.resource)||p.findSuperstr(u.resource.with({query:null,fragment:null}))?!0:u.isDirectory&&a?f===1:!1))}async toFileStat(e,n,r,o,s,a){let{providerExtUri:l}=this.getExtUri(e),c={resource:n,name:l.basename(n),isFile:(r.type&1)!==0,isDirectory:(r.type&2)!==0,isSymbolicLink:(r.type&64)!==0,mtime:r.mtime,ctime:r.ctime,size:r.size,readonly:!!((r.permissions??0)&1)||!!(e.capabilities&2048),locked:!!((r.permissions??0)&2),executable:!!((r.permissions??0)&4),etag:Fl({mtime:r.mtime,size:r.size}),children:void 0};if(c.isDirectory&&a(c,o)){try{let p=await e.readdir(n),u=await wn.settled(p.map(async([f,m])=>{try{let v=l.joinPath(n,f),h=s?await e.stat(v):{type:m};return await this.toFileStat(e,v,h,p.length,s,a)}catch(v){return this.logService.trace(v),null}}));c.children=no(u)}catch(p){this.logService.trace(p),c.children=[]}return c}return c}async resolveAll(e){return wn.settled(e.map(async n=>{try{return{stat:await this.doResolveFile(n.resource,n.options),success:!0}}catch(r){return this.logService.trace(r),{stat:void 0,success:!1}}}))}async stat(e){let n=await this.withProvider(e),r=await n.stat(e);return this.toFileStat(n,e,r,void 0,!0,()=>!1)}async realpath(e){let n=await this.withProvider(e);if(rp(n)){let r=await n.realpath(e);return e.with({path:r})}}async exists(e){let n=await this.withProvider(e);try{return!!await n.stat(e)}catch{return!1}}async canCreateFile(e,n){try{await this.doValidateCreateFile(e,n)}catch(r){return r}return!0}async doValidateCreateFile(e,n){if(!n?.overwrite&&await this.exists(e))throw new Ce(g(2134,null,this.resourceForError(e)),3,n)}async createFile(e,n=_.fromString(""),r){await this.doValidateCreateFile(e,r);let o=await this.writeFile(e,n);return this._onDidRunOperation.fire(new $t(e,0,o)),o}async writeFile(e,n,r){let o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),{providerExtUri:s}=this.getExtUri(o),a=r;if(Ol(o)&&!a?.atomic){let l=o.enforceAtomicWriteFile?.(e);l&&(a={...r,atomic:l})}try{let{stat:l,buffer:c}=await this.validateWriteFile(o,e,n,a);l||await this.mkdirp(o,s.dirname(e)),c||(c=await this.peekBufferForWriting(o,n)),!qt(o)||nt(o)&&c instanceof _||nt(o)&&Ol(o)&&a?.atomic?await this.doWriteUnbuffered(o,e,a,c):await this.doWriteBuffered(o,e,a,c instanceof _?gu(c):c),this._onDidRunOperation.fire(new $t(e,4))}catch(l){throw new Ce(g(2133,null,this.resourceForError(e),Kt(l).toString()),Ll(l),a)}return this.resolve(e,{resolveMetadata:!0})}async peekBufferForWriting(e,n){let r;if(nt(e)&&!(n instanceof _))if(pi(n)){let o=await cu(n,3);o.ended?r=_.concat(o.buffer):r=o}else r=lu(n,o=>_.concat(o),3);else r=n;return r}async validateWriteFile(e,n,r,o){let s=!!o?.unlock;if(s&&!(e.capabilities&8192))throw new Error(g(2151,null,this.resourceForError(n)));if(o?.append&&!tp(e))throw new Ce(g(2130,null,this.resourceForError(n)),6);if(!!o?.atomic){if(!(e.capabilities&32768))throw new Error(g(2149,null,this.resourceForError(n)));if(!(e.capabilities&2))throw new Error(g(2150,null,this.resourceForError(n)));if(s)throw new Error(g(2148,null,this.resourceForError(n)))}let l;try{l=await e.stat(n)}catch{return Object.create(null)}if((l.type&2)!==0)throw new Ce(g(2136,null,this.resourceForError(n)),0,o);this.throwIfFileIsReadonly(n,l);let c;if(typeof o?.mtime=="number"&&typeof o.etag=="string"&&o.etag!==es&&typeof l.mtime=="number"&&typeof l.size=="number"&&o.mtime<l.mtime&&o.etag!==Fl({mtime:o.mtime,size:l.size})){if(c=await this.peekBufferForWriting(e,r),c instanceof _&&c.byteLength===l.size)try{let{value:p}=await this.readFile(n,{limits:{size:l.size}});if(c.equals(p))return{stat:l,buffer:c}}catch{}throw new Ce(g(2137,null),3,o)}return{stat:l,buffer:c}}async readFile(e,n,r){let o=await this.withReadProvider(e);return n?.atomic?this.doReadFileAtomic(o,e,n,r):this.doReadFile(o,e,n,r)}async doReadFileAtomic(e,n,r,o){return new Promise((s,a)=>{this.writeQueue.queueFor(n,async()=>{try{let l=await this.doReadFile(e,n,r,o);s(l)}catch(l){a(l)}},this.getExtUri(e).providerExtUri)})}async doReadFile(e,n,r,o){let s=await this.doReadFileStream(e,n,{...r,preferUnbuffered:!0},o);return{...s,value:await gi(s.value)}}async readFileStream(e,n,r){let o=await this.withReadProvider(e);return this.doReadFileStream(o,e,n,r)}async doReadFileStream(e,n,r,o){let s=new _e(o),a=r;Zo(e)&&e.enforceAtomicReadFile?.(n)&&(a={...r,atomic:!0});let l=this.validateReadFile(n,a).then(p=>p,p=>{throw s.dispose(!0),p}),c;try{return typeof a?.etag=="string"&&a.etag!==es&&await l,a?.atomic&&Zo(e)||!(qt(e)||Xo(e))||nt(e)&&a?.preferUnbuffered?c=this.readFileUnbuffered(e,n,a):Xo(e)?c=this.readFileStreamed(e,n,s.token,a):c=this.readFileBuffered(e,n,s.token,a),c.on("end",()=>s.dispose()),c.on("error",()=>s.dispose()),{...await l,value:c}}catch(p){throw c&&await Ao(c),this.restoreReadError(p,n,a)}}restoreReadError(e,n,r){let o=g(2131,null,this.resourceForError(n),Kt(e).toString());return e instanceof Ir?new Ir(o,e.stat,r):e instanceof yr?new yr(o,e.fileOperationResult,e.size,e.options):new Ce(o,Ll(e),r)}readFileStreamed(e,n,r,o=Object.create(null)){let s=e.readFileStream(n,o,r);return al(s,{data:a=>a instanceof _?a:_.wrap(a),error:a=>this.restoreReadError(a,n,o)},a=>_.concat(a))}readFileBuffered(e,n,r,o=Object.create(null)){let s=hu();return ia(e,n,s,a=>a,{...o,bufferSize:this.BUFFER_SIZE,errorTransformer:a=>this.restoreReadError(a,n,o)},r),s}readFileUnbuffered(e,n,r){let o=Nt(s=>_.concat(s));return(async()=>{try{let s;r?.atomic&&Zo(e)?s=await e.readFile(n,{atomic:!0}):s=await e.readFile(n),typeof r?.position=="number"&&(s=s.slice(r.position)),typeof r?.length=="number"&&(s=s.slice(0,r.length)),this.validateReadFileLimits(n,s.byteLength,r),o.end(_.wrap(s))}catch(s){o.error(s),o.end()}})(),o}async validateReadFile(e,n){let r=await this.resolve(e,{resolveMetadata:!0});if(r.isDirectory)throw new Ce(g(2135,null,this.resourceForError(e)),0,n);if(typeof n?.etag=="string"&&n.etag!==es&&n.etag===r.etag)throw new Ir(g(2139,null),r,n);return this.validateReadFileLimits(e,r.size,n),r}validateReadFileLimits(e,n,r){if(typeof r?.limits?.size=="number"&&n>r.limits.size)throw new yr(g(2140,null,this.resourceForError(e)),7,n,r)}async canMove(e,n,r){return this.doCanMoveCopy(e,n,"move",r)}async canCopy(e,n,r){return this.doCanMoveCopy(e,n,"copy",r)}async doCanMoveCopy(e,n,r,o){if(e.toString()!==n.toString())try{let s=r==="move"?this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e):await this.withReadProvider(e),a=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n);await this.doValidateMoveCopy(s,e,a,n,r,o)}catch(s){return s}return!0}async move(e,n,r){let o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n),a=await this.doMoveCopy(o,e,s,n,"move",!!r),l=await this.resolve(n,{resolveMetadata:!0});return this._onDidRunOperation.fire(new $t(e,a==="move"?2:3,l)),l}async copy(e,n,r){let o=await this.withReadProvider(e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n),a=await this.doMoveCopy(o,e,s,n,"copy",!!r),l=await this.resolve(n,{resolveMetadata:!0});return this._onDidRunOperation.fire(new $t(e,a==="copy"?3:2,l)),l}async doMoveCopy(e,n,r,o,s,a){if(n.toString()===o.toString())return s;let{exists:l,isSameResourceWithDifferentPathCase:c}=await this.doValidateMoveCopy(e,n,r,o,s,a);if(l&&!c&&a&&await this.del(o,{recursive:!0}),await this.mkdirp(r,this.getExtUri(r).providerExtUri.dirname(o)),s==="copy"){if(e===r&&Dl(e))await e.copy(n,o,{overwrite:a});else{let p=await this.resolve(n);p.isDirectory?await this.doCopyFolder(e,p,r,o):await this.doCopyFile(e,n,r,o)}return s}else return e===r?(await e.rename(n,o,{overwrite:a}),s):(await this.doMoveCopy(e,n,r,o,"copy",a),await this.del(n,{recursive:!0}),"copy")}async doCopyFile(e,n,r,o){if(qt(e)&&qt(r))return this.doPipeBuffered(e,n,r,o);if(qt(e)&&nt(r))return this.doPipeBufferedToUnbuffered(e,n,r,o);if(nt(e)&&qt(r))return this.doPipeUnbufferedToBuffered(e,n,r,o);if(nt(e)&&nt(r))return this.doPipeUnbuffered(e,n,r,o)}async doCopyFolder(e,n,r,o){await r.mkdir(o),Array.isArray(n.children)&&await wn.settled(n.children.map(async s=>{let a=this.getExtUri(r).providerExtUri.joinPath(o,s.name);return s.isDirectory?this.doCopyFolder(e,await this.resolve(s.resource),r,a):this.doCopyFile(e,s.resource,r,a)}))}async doValidateMoveCopy(e,n,r,o,s,a){let l=!1;if(e===r){let{providerExtUri:p,isPathCaseSensitive:u}=this.getExtUri(e);if(u||(l=p.isEqual(n,o)),l&&s==="copy")throw new Error(g(2144,null,this.resourceForError(n),this.resourceForError(o)));if(!l&&p.isEqualOrParent(o,n))throw new Error(g(2145,null,this.resourceForError(n),this.resourceForError(o)))}let c=await this.exists(o);if(c&&!l){if(!a)throw new Ce(g(2146,null,this.resourceForError(n),this.resourceForError(o)),4);if(e===r){let{providerExtUri:p}=this.getExtUri(e);if(p.isEqualOrParent(n,o))throw new Error(g(2147,null,this.resourceForError(n),this.resourceForError(o)))}}return{exists:c,isSameResourceWithDifferentPathCase:l}}getExtUri(e){let n=this.isPathCaseSensitive(e);return{providerExtUri:n?j:el,isPathCaseSensitive:n}}isPathCaseSensitive(e){return!!(e.capabilities&1024)}async createFolder(e){let n=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e);await this.mkdirp(n,e);let r=await this.resolve(e,{resolveMetadata:!0});return this._onDidRunOperation.fire(new $t(e,0,r)),r}async mkdirp(e,n){let r=[],{providerExtUri:o}=this.getExtUri(e);for(;!o.isEqual(n,o.dirname(n));)try{if(((await e.stat(n)).type&2)===0)throw new Error(g(2142,null,this.resourceForError(n)));break}catch(s){if(xt(s)!=="EntryNotFound")throw s;r.push(o.basename(n)),n=o.dirname(n)}for(let s=r.length-1;s>=0;s--){n=o.joinPath(n,r[s]);try{await e.mkdir(n)}catch(a){if(xt(a)!=="EntryExists")throw a}}}async canDelete(e,n){try{await this.doValidateDelete(e,n)}catch(r){return r}return!0}async doValidateDelete(e,n){let r=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e),o=!!n?.useTrash;if(o&&!(r.capabilities&4096))throw new Error(g(2129,null,this.resourceForError(e)));let s=n?.atomic;if(s&&!(r.capabilities&65536))throw new Error(g(2125,null,this.resourceForError(e)));if(o&&s)throw new Error(g(2128,null,this.resourceForError(e)));let a;try{a=await r.stat(e)}catch{}if(a)this.throwIfFileIsReadonly(e,a);else throw new Ce(g(2127,null,this.resourceForError(e)),1);if(!!!n?.recursive){let c=await this.resolve(e);if(c.isDirectory&&Array.isArray(c.children)&&c.children.length>0)throw new Error(g(2126,null,this.resourceForError(e)))}return r}async del(e,n){let r=await this.doValidateDelete(e,n),o=n;if(ip(r)&&!o?.atomic){let c=r.enforceAtomicDelete?.(e);c&&(o={...n,atomic:c})}let s=!!o?.useTrash,a=!!o?.recursive,l=o?.atomic??!1;await r.delete(e,{recursive:a,useTrash:s,atomic:l}),this._onDidRunOperation.fire(new $t(e,1))}async cloneFile(e,n){let r=await this.withProvider(e),o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n);if(!(r===o&&this.getExtUri(r).providerExtUri.isEqual(e,n)))return r===o&&np(r)?r.cloneFile(e,n):(await this.mkdirp(o,this.getExtUri(o).providerExtUri.dirname(n)),r===o&&Dl(r)?this.writeQueue.queueFor(e,()=>r.copy(e,n,{overwrite:!0}),this.getExtUri(r).providerExtUri):this.writeQueue.queueFor(e,()=>this.doCopyFile(r,e,o,n),this.getExtUri(r).providerExtUri))}static{this.WATCHER_CORRELATION_IDS=0}createWatcher(e,n){return this.watch(e,{...n,correlationId:mn.WATCHER_CORRELATION_IDS++})}watch(e,n={recursive:!1,excludes:[]}){let r=new N,o=!1,s=()=>{o=!0};r.add(w(()=>s())),(async()=>{try{let l=await this.doWatch(e,n);o?Ke(l):s=()=>Ke(l)}catch(l){this.logService.error(l)}})();let a=n.correlationId;if(typeof a=="number"){let l=r.add(new x);return r.add(this.internalOnDidFilesChange.event(p=>{p.correlates(a)&&l.fire(p)})),{onDidChange:l.event,dispose:()=>r.dispose()}}return r}async doWatch(e,n){let r=await this.withProvider(e),o=Er([this.getExtUri(r).providerExtUri.getComparisonKey(e),n]),s=this.activeWatchers.get(o);return s||(s={count:0,disposable:r.watch(e,n)},this.activeWatchers.set(o,s)),s.count+=1,w(()=>{s&&(s.count--,s.count===0&&(Ke(s.disposable),this.activeWatchers.delete(o)))})}dispose(){super.dispose();for(let[,e]of this.activeWatchers)Ke(e.disposable);this.activeWatchers.clear()}async doWriteBuffered(e,n,r,o){return this.writeQueue.queueFor(n,async()=>{let s=await e.open(n,{create:!0,unlock:r?.unlock??!1,append:r?.append??!1});try{pi(o)||Po(o)?await this.doWriteStreamBufferedQueued(e,s,o):await this.doWriteReadableBufferedQueued(e,s,o)}catch(a){throw Kt(a)}finally{await e.close(s)}},this.getExtUri(e).providerExtUri)}async doWriteStreamBufferedQueued(e,n,r){let o=0,s;if(Po(r)){if(r.buffer.length>0){let a=_.concat(r.buffer);await this.doWriteBuffer(e,n,a,a.byteLength,o,0),o+=a.byteLength}if(r.ended)return;s=r.stream}else s=r;return new Promise((a,l)=>{ko(s,{onData:async c=>{s.pause();try{await this.doWriteBuffer(e,n,c,c.byteLength,o,0)}catch(p){return l(p)}o+=c.byteLength,setTimeout(()=>s.resume())},onError:c=>l(c),onEnd:()=>a()})})}async doWriteReadableBufferedQueued(e,n,r){let o=0,s;for(;(s=r.read())!==null;)await this.doWriteBuffer(e,n,s,s.byteLength,o,0),o+=s.byteLength}async doWriteBuffer(e,n,r,o,s,a){let l=0;for(;l<o;){let c=await e.write(n,s+l,r.buffer,a+l,o-l);l+=c}}async doWriteUnbuffered(e,n,r,o){return this.writeQueue.queueFor(n,()=>this.doWriteUnbufferedQueued(e,n,r,o),this.getExtUri(e).providerExtUri)}async doWriteUnbufferedQueued(e,n,r,o){let s;o instanceof _?s=o:pi(o)?s=await gi(o):Po(o)?s=await mu(o):s=fu(o),await e.writeFile(n,s.buffer,{create:!0,overwrite:!0,unlock:r?.unlock??!1,atomic:r?.atomic??!1,append:r?.append??!1})}async doPipeBuffered(e,n,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeBufferedQueued(e,n,r,o),this.getExtUri(r).providerExtUri)}async doPipeBufferedQueued(e,n,r,o){let s,a;try{s=await e.open(n,{create:!1}),a=await r.open(o,{create:!0,unlock:!1});let l=_.alloc(this.BUFFER_SIZE),c=0,p=0,u=0;do u=await e.read(s,c,l.buffer,p,l.byteLength-p),await this.doWriteBuffer(r,a,l,u,c,p),c+=u,p+=u,p===l.byteLength&&(p=0);while(u>0)}catch(l){throw Kt(l)}finally{await wn.settled([typeof s=="number"?e.close(s):Promise.resolve(),typeof a=="number"?r.close(a):Promise.resolve()])}}async doPipeUnbuffered(e,n,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedQueued(e,n,r,o),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedQueued(e,n,r,o){return r.writeFile(o,await e.readFile(n),{create:!0,overwrite:!0,unlock:!1,atomic:!1})}async doPipeUnbufferedToBuffered(e,n,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedToBufferedQueued(e,n,r,o),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedToBufferedQueued(e,n,r,o){let s=await r.open(o,{create:!0,unlock:!1});try{let a=await e.readFile(n);await this.doWriteBuffer(r,s,_.wrap(a),a.byteLength,0,0)}catch(a){throw Kt(a)}finally{await r.close(s)}}async doPipeBufferedToUnbuffered(e,n,r,o){let s=await gi(this.readFileBuffered(e,n,Ze.None));await this.doWriteUnbuffered(r,o,void 0,s)}throwIfFileSystemIsReadonly(e,n){if(e.capabilities&2048)throw new Ce(g(2132,null,this.resourceForError(n)),6);return e}throwIfFileIsReadonly(e,n){if((n.permissions??0)&1)throw new Ce(g(2132,null,this.resourceForError(e)),6)}resourceForError(e){return e.scheme===ee.file?e.fsPath:e.toString(!0)}};mn=O([K(0,ue)],mn);import{constants as Uc,promises as Kn}from"fs";function la(i){return typeof i.correlationId=="number"}function rg(i){return i.recursive===!0}var oa=class i extends L{constructor(e,n,r,o){super();this.onFileChanges=e;this.onLogMessage=n;this.verboseLogging=r;this.options=o;this.watcherDisposables=this._register(new Qt);this.requests=void 0;this.restartCounter=0}static{this.MAX_RESTARTS=5}init(){let e=new N;this.watcherDisposables.value=e,this.watcher=this.createWatcher(e),this.watcher.setVerboseLogging(this.verboseLogging),e.add(this.watcher.onDidChangeFile(n=>this.onFileChanges(n))),e.add(this.watcher.onDidLogMessage(n=>this.onLogMessage(n))),e.add(this.watcher.onDidError(n=>this.onError(n.error,n.request)))}onError(e,n){this.canRestart(e,n)?this.restartCounter<i.MAX_RESTARTS&&this.requests?(this.error(`restarting watcher after unexpected error: ${e}`),this.restart(this.requests)):this.error(`gave up attempting to restart watcher after unexpected error: ${e}`):this.error(e)}canRestart(e,n){return!(!this.options.restartOnError||n||e.indexOf("No space left on device")!==-1||e.indexOf("EMFILE")!==-1)}restart(e){this.restartCounter++,this.init(),this.watch(e)}async watch(e){this.requests=e,await this.watcher?.watch(e)}async setVerboseLogging(e){this.verboseLogging=e,await this.watcher?.setVerboseLogging(e)}error(e){this.onLogMessage({type:"error",message:`[File Watcher (${this.options.type})] ${e}`})}trace(e){this.onLogMessage({type:"trace",message:`[File Watcher (${this.options.type})] ${e}`})}dispose(){return this.watcher=void 0,super.dispose()}},sa=class extends oa{constructor(t,e,n){super(t,e,n,{type:"node.js",restartOnError:!1})}},aa=class extends oa{constructor(t,e,n){super(t,e,n,{type:"universal",restartOnError:!0})}};function Lc(i){return i.map(t=>({type:t.type,resource:b.revive(t.resource),cId:t.cId}))}function ig(i){let t=new Oc;for(let e of i)t.processEvent(e);return t.coalesce()}function xb(i,t){return typeof t=="string"&&!t.startsWith(_r)&&!Xn(t)?{base:i,pattern:t}:t}function Fc(i,t,e){let n=[];for(let r of t)n.push(ql(xb(i,r),{ignoreCase:e}));return n}var Oc=class{constructor(){this.coalesced=new Set;this.mapPathToChange=new Map}toKey(t){return ve?t.resource.fsPath:t.resource.fsPath.toLowerCase()}processEvent(t){let e=this.mapPathToChange.get(this.toKey(t)),n=!1;if(e){let r=e.type,o=t.type;e.resource.fsPath!==t.resource.fsPath&&(t.type===2||t.type===1)?n=!0:r===1&&o===2?(this.mapPathToChange.delete(this.toKey(t)),this.coalesced.delete(e)):r===2&&o===1?e.type=0:r===1&&o===0||(e.type=o)}else n=!0;n&&(this.coalesced.add(t),this.mapPathToChange.set(this.toKey(t),t))}coalesce(){let t=[],e=[];return Array.from(this.coalesced).filter(n=>n.type!==2?(t.push(n),!1):!0).sort((n,r)=>n.resource.fsPath.length-r.resource.fsPath.length).filter(n=>e.some(r=>op(n.resource.fsPath,r,!ve))?!1:(e.push(n.resource.fsPath),!0)).concat(t)}};function og(i,t){if(typeof t=="number")switch(i.type){case 1:return(t&4)===0;case 2:return(t&8)===0;case 0:return(t&2)===0}return!1}function sg(i){if(typeof i=="number"){let t=[];return i&4&&t.push("Added"),i&8&&t.push("Deleted"),i&2&&t.push("Updated"),t.length===0?"<all>":`[${t.join(", ")}]`}return"<none>"}var ca=class extends L{constructor(e,n){super();this.logService=e;this.options=n;this._onDidChangeFile=this._register(new x);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new x);this.onDidWatchError=this._onDidWatchError.event;this.universalWatchRequests=[];this.universalWatchRequestDelayer=this._register(new Rn(this.getRefreshWatchersDelay(this.universalWatchRequests.length)));this.nonRecursiveWatchRequests=[];this.nonRecursiveWatchRequestDelayer=this._register(new Rn(this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)))}watch(e,n){return n.recursive||this.options?.watcher?.forceUniversal?this.watchUniversal(e,n):this.watchNonRecursive(e,n)}getRefreshWatchersDelay(e){return e>200?500:0}watchUniversal(e,n){let r=this.toWatchRequest(e,n),o=Ta(this.universalWatchRequests,r);return this.refreshUniversalWatchers(),w(()=>{o(),this.refreshUniversalWatchers()})}toWatchRequest(e,n){let r={path:this.toWatchPath(e),excludes:n.excludes,includes:n.includes,recursive:n.recursive,filter:n.filter,correlationId:n.correlationId};if(rg(r)){let o=this.options?.watcher?.recursive?.usePolling;o===!0?r.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3:Array.isArray(o)&&o.includes(r.path)&&(r.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3)}return r}refreshUniversalWatchers(){this.universalWatchRequestDelayer.trigger(()=>this.doRefreshUniversalWatchers(),this.getRefreshWatchersDelay(this.universalWatchRequests.length)).catch(e=>fe(e))}doRefreshUniversalWatchers(){return this.universalWatcher||(this.universalWatcher=this._register(this.createUniversalWatcher(e=>this._onDidChangeFile.fire(Lc(e)),e=>this.onWatcherLogMessage(e),this.logService.getLevel()===1)),this._register(this.logService.onDidChangeLogLevel(()=>{this.universalWatcher?.setVerboseLogging(this.logService.getLevel()===1)}))),this.universalWatcher.watch(this.universalWatchRequests)}watchNonRecursive(e,n){let r={path:this.toWatchPath(e),excludes:n.excludes,includes:n.includes,recursive:!1,filter:n.filter,correlationId:n.correlationId},o=Ta(this.nonRecursiveWatchRequests,r);return this.refreshNonRecursiveWatchers(),w(()=>{o(),this.refreshNonRecursiveWatchers()})}refreshNonRecursiveWatchers(){this.nonRecursiveWatchRequestDelayer.trigger(()=>this.doRefreshNonRecursiveWatchers(),this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)).catch(e=>fe(e))}doRefreshNonRecursiveWatchers(){return this.nonRecursiveWatcher||(this.nonRecursiveWatcher=this._register(this.createNonRecursiveWatcher(e=>this._onDidChangeFile.fire(Lc(e)),e=>this.onWatcherLogMessage(e),this.logService.getLevel()===1)),this._register(this.logService.onDidChangeLogLevel(()=>{this.nonRecursiveWatcher?.setVerboseLogging(this.logService.getLevel()===1)}))),this.nonRecursiveWatcher.watch(this.nonRecursiveWatchRequests)}onWatcherLogMessage(e){e.type==="error"&&this._onDidWatchError.fire(e.message),this.logWatcherMessage(e)}logWatcherMessage(e){this.logService[e.type](e.message)}toFilePath(e){return ot(e.fsPath)}toWatchPath(e){let n=this.toFilePath(e);return Vd(n)}};var da=class extends aa{constructor(t,e,n){super(t,e,n),this.init()}createWatcher(t){let e=t.add(new Mo(Xe.asFileUri("bootstrap-fork").fsPath,{serverName:"File Watcher",args:["--type=fileWatcher"],env:{VSCODE_ESM_ENTRYPOINT:"vs/platform/files/node/watcher/watcherMain",VSCODE_PIPE_LOGGING:"true",VSCODE_VERBOSE_LOGGING:"true"}}));return t.add(e.onDidProcessExit(({code:n,signal:r})=>this.onError(`terminated by itself with code ${n}, signal: ${r} (ETERM)`))),dr.toService(bu(e.getChannel("watcher")))}};import{watchFile as _b,unwatchFile as Eb}from"fs";var ua=class extends L{constructor(){super();this._onDidChangeFile=this._register(new x);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidLogMessage=this._register(new x);this.onDidLogMessage=this._onDidLogMessage.event;this._onDidWatchFail=this._register(new x);this.onDidWatchFail=this._onDidWatchFail.event;this.correlatedWatchRequests=new Map;this.nonCorrelatedWatchRequests=new Map;this.suspendedWatchRequests=this._register(new it);this.suspendedWatchRequestsWithPolling=new Set;this.updateWatchersDelayer=this._register(new Rn(this.getUpdateWatchersDelay()));this.suspendedWatchRequestPollingInterval=5007;this.joinWatch=new Be;this.verboseLogging=!1;this._register(this.onDidWatchFail(e=>this.suspendWatchRequest({id:this.computeId(e),correlationId:this.isCorrelated(e)?e.correlationId:void 0,path:e.path})))}isCorrelated(e){return la(e)}computeId(e){return this.isCorrelated(e)?e.correlationId:Er(e)}async watch(e){this.joinWatch.isSettled||this.joinWatch.complete(),this.joinWatch=new Be;try{this.correlatedWatchRequests.clear(),this.nonCorrelatedWatchRequests.clear();for(let n of e)this.isCorrelated(n)?this.correlatedWatchRequests.set(n.correlationId,n):this.nonCorrelatedWatchRequests.set(this.computeId(n),n);for(let[n]of this.suspendedWatchRequests)!this.nonCorrelatedWatchRequests.has(n)&&!this.correlatedWatchRequests.has(n)&&(this.suspendedWatchRequests.deleteAndDispose(n),this.suspendedWatchRequestsWithPolling.delete(n));return await this.updateWatchers(!1)}finally{this.joinWatch.complete()}}updateWatchers(e){let n=[];for(let[r,o]of[...this.nonCorrelatedWatchRequests,...this.correlatedWatchRequests])this.suspendedWatchRequests.has(r)||n.push(o);return this.updateWatchersDelayer.trigger(()=>this.doWatch(n),e?this.getUpdateWatchersDelay():0).catch(r=>fe(r))}getUpdateWatchersDelay(){return 800}isSuspended(e){let n=this.computeId(e);return this.suspendedWatchRequestsWithPolling.has(n)?"polling":this.suspendedWatchRequests.has(n)}async suspendWatchRequest(e){if(this.suspendedWatchRequests.has(e.id))return;let n=new N;this.suspendedWatchRequests.set(e.id,n),await this.joinWatch.p,!n.isDisposed&&(this.monitorSuspendedWatchRequest(e,n),this.updateWatchers(!0))}resumeWatchRequest(e){this.suspendedWatchRequests.deleteAndDispose(e.id),this.suspendedWatchRequestsWithPolling.delete(e.id),this.updateWatchers(!1)}monitorSuspendedWatchRequest(e,n){this.doMonitorWithExistingWatcher(e,n)?(this.trace(`reusing an existing recursive watcher to monitor ${e.path}`),this.suspendedWatchRequestsWithPolling.delete(e.id)):(this.doMonitorWithNodeJS(e,n),this.suspendedWatchRequestsWithPolling.add(e.id))}doMonitorWithExistingWatcher(e,n){let r=this.recursiveWatcher?.subscribe(e.path,(o,s)=>{n.isDisposed||(o?this.monitorSuspendedWatchRequest(e,n):s?.type===1&&this.onMonitoredPathAdded(e))});return r?(n.add(r),!0):!1}doMonitorWithNodeJS(e,n){let r=!1,o=(s,a)=>{if(n.isDisposed)return;let l=this.isPathNotFound(s),c=this.isPathNotFound(a),p=r;r=l,!l&&(c||p)&&this.onMonitoredPathAdded(e)};this.trace(`starting fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{_b(e.path,{persistent:!1,interval:this.suspendedWatchRequestPollingInterval},o)}catch(s){this.warn(`fs.watchFile() failed with error ${s} on path ${e.path} (correlationId: ${e.correlationId})`)}n.add(w(()=>{this.trace(`stopping fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{Eb(e.path,o)}catch(s){this.warn(`fs.unwatchFile() failed with error ${s} on path ${e.path} (correlationId: ${e.correlationId})`)}}))}onMonitoredPathAdded(e){this.trace(`detected ${e.path} exists again, resuming watcher (correlationId: ${e.correlationId})`);let n={resource:b.file(e.path),type:1,cId:e.correlationId};this._onDidChangeFile.fire([n]),this.traceEvent(n,e),this.resumeWatchRequest(e)}isPathNotFound(e){return e.ctimeMs===0&&e.ino===0}async stop(){this.suspendedWatchRequests.clearAndDisposeAll(),this.suspendedWatchRequestsWithPolling.clear()}traceEvent(e,n){if(this.verboseLogging){let r=` >> normalized ${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`;this.traceWithCorrelation(r,n)}}traceWithCorrelation(e,n){this.verboseLogging&&this.trace(`${e}${typeof n.correlationId=="number"?` <${n.correlationId}> `:""}`)}requestToString(e){return`${e.path} (excludes: ${e.excludes.length>0?e.excludes:"<none>"}, includes: ${e.includes&&e.includes.length>0?JSON.stringify(e.includes):"<all>"}, filter: ${sg(e.filter)}, correlationId: ${typeof e.correlationId=="number"?e.correlationId:"<none>"})`}async setVerboseLogging(e){this.verboseLogging=e}};import{watch as Cb,promises as Rb}from"fs";var pa=class i extends L{constructor(e,n,r,o,s,a){super();this.request=e;this.recursiveWatcher=n;this.onDidFilesChange=r;this.onDidWatchFail=o;this.onLogMessage=s;this.verboseLogging=a;this.throttledFileChangesEmitter=this._register(new rr({maxWorkChunkSize:100,throttleDelay:200,maxBufferedWork:1e4},e=>this.onDidFilesChange(e)));this.fileChangesAggregator=this._register(new Co(e=>this.handleFileChanges(e),i.FILE_CHANGES_HANDLER_DELAY));this.cts=new _e;this.realPath=new He(async()=>{let e=this.request.path;try{e=await he.realpath(this.request.path),this.request.path!==e&&this.trace(`correcting a path to watch that seems to be a symbolic link (original: ${this.request.path}, real: ${e})`)}catch{}return e});this._isReusingRecursiveWatcher=!1;this.didFail=!1;let l=!ve;this.excludes=Fc(this.request.path,this.request.excludes,l),this.includes=this.request.includes?Fc(this.request.path,this.request.includes,l):void 0,this.filter=la(this.request)?this.request.filter:void 0,this.ready=this.watch()}static{this.FILE_DELETE_HANDLER_DELAY=100}static{this.FILE_CHANGES_HANDLER_DELAY=75}get isReusingRecursiveWatcher(){return this._isReusingRecursiveWatcher}get failed(){return this.didFail}async watch(){try{let e=await Rb.stat(this.request.path);if(this.cts.token.isCancellationRequested)return;this._register(await this.doWatch(e.isDirectory()))}catch(e){e.code!=="ENOENT"?this.error(e):this.trace(`ignoring a path for watching who's stat info failed to resolve: ${this.request.path} (error: ${e})`),this.notifyWatchFailed()}}notifyWatchFailed(){this.didFail=!0,this.onDidWatchFail?.()}async doWatch(e){let n=new N;return this.doWatchWithExistingWatcher(e,n)?(this.trace(`reusing an existing recursive watcher for ${this.request.path}`),this._isReusingRecursiveWatcher=!0):(this._isReusingRecursiveWatcher=!1,await this.doWatchWithNodeJS(e,n)),n}doWatchWithExistingWatcher(e,n){if(e)return!1;let r=b.file(this.request.path),o=this.recursiveWatcher?.subscribe(this.request.path,async(s,a)=>{n.isDisposed||(s?await cd(this.doWatch(e),n):a&&(typeof a.cId=="number"||typeof this.request.correlationId=="number")&&this.onFileChange({resource:r,type:a.type,cId:this.request.correlationId},!0))});return o?(n.add(o),!0):!1}async doWatchWithNodeJS(e,n){let r=await this.realPath.value;if(this.cts.token.isCancellationRequested)return;if(Je&&Ot(r,"/Volumes/",!0)){this.error(`Refusing to watch ${r} for changes using fs.watch() for possibly being a network share where watching is unreliable and unstable.`);return}let o=new _e(this.cts.token);n.add(w(()=>o.dispose(!0)));let s=new N;n.add(s);try{let a=b.file(this.request.path),l=Te(r),c=Cb(r);s.add(w(()=>{c.removeAllListeners(),c.close()})),this.trace(`Started watching: '${r}'`);let p=new Set;if(e)try{for(let f of await he.readdir(r))p.add(f)}catch(f){this.error(f)}if(o.token.isCancellationRequested)return;let u=new Map;s.add(w(()=>{for(let[,f]of u)f.dispose();u.clear()})),c.on("error",(f,m)=>{o.token.isCancellationRequested||(this.error(`Failed to watch ${r} for changes using fs.watch() (${f}, ${m})`),this.notifyWatchFailed())}),c.on("change",(f,m)=>{if(o.token.isCancellationRequested)return;this.verboseLogging&&this.traceWithCorrelation(`[raw] ["${f}"] ${m}`);let v="";if(m&&(v=m.toString(),Je&&(v=yi(v))),!(!v||f!=="change"&&f!=="rename"))if(e)if(f==="rename"){u.get(v)?.dispose();let h=setTimeout(async()=>{if(u.delete(v),er(v,l,!ve)&&!await he.exists(r)){this.onWatchedPathDeleted(a);return}if(o.token.isCancellationRequested)return;let I=await this.existsChildStrictCase(q(r,v));if(o.token.isCancellationRequested)return;let y;I?p.has(v)?y=0:(y=1,p.add(v)):(p.delete(v),y=2),this.onFileChange({resource:te(a,v),type:y,cId:this.request.correlationId})},i.FILE_DELETE_HANDLER_DELAY);u.set(v,w(()=>clearTimeout(h)))}else{let h;p.has(v)?h=0:(h=1,p.add(v)),this.onFileChange({resource:te(a,v),type:h,cId:this.request.correlationId})}else if(f==="rename"||!er(v,l,!ve)){let h=setTimeout(async()=>{let I=await he.exists(r);o.token.isCancellationRequested||(I?(this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0),s.add(await this.doWatch(!1))):this.onWatchedPathDeleted(a))},i.FILE_DELETE_HANDLER_DELAY);s.clear(),s.add(w(()=>clearTimeout(h)))}else this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0)})}catch(a){if(o.token.isCancellationRequested)return;this.error(`Failed to watch ${r} for changes using fs.watch() (${a.toString()})`),this.notifyWatchFailed()}}onWatchedPathDeleted(e){this.warn("Watcher shutdown because watched path got deleted"),this.onFileChange({resource:e,type:2,cId:this.request.correlationId},!0),this.fileChangesAggregator.flush(),this.notifyWatchFailed()}onFileChange(e,n=!1){this.cts.token.isCancellationRequested||(this.verboseLogging&&this.traceWithCorrelation(`${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`),!n&&this.excludes.some(r=>r(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (excluded) ${e.resource.fsPath}`):!n&&this.includes&&this.includes.length>0&&!this.includes.some(r=>r(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (not included) ${e.resource.fsPath}`):this.fileChangesAggregator.work(e))}handleFileChanges(e){let n=ig(e),r=[];for(let s of n){if(og(s,this.filter)){this.verboseLogging&&this.traceWithCorrelation(` >> ignored (filtered) ${s.resource.fsPath}`);continue}r.push(s)}if(r.length===0)return;if(this.verboseLogging)for(let s of r)this.traceWithCorrelation(` >> normalized ${s.type===1?"[ADDED]":s.type===2?"[DELETED]":"[CHANGED]"} ${s.resource.fsPath}`);this.throttledFileChangesEmitter.work(r)?this.throttledFileChangesEmitter.pending>0&&this.trace(`started throttling events due to large amount of file change events at once (pending: ${this.throttledFileChangesEmitter.pending}, most recent change: ${r[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`):this.warn(`started ignoring events due to too many file change events at once (incoming: ${r.length}, most recent change: ${r[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`)}async existsChildStrictCase(e){if(ve)return he.exists(e);try{let n=Te(e);return(await he.readdir(me(e))).some(o=>o===n)}catch(n){return this.trace(n),!1}}setVerboseLogging(e){this.verboseLogging=e}error(e){this.cts.token.isCancellationRequested||this.onLogMessage?.({type:"error",message:`[File Watcher (node.js)] ${e}`})}warn(e){this.cts.token.isCancellationRequested||this.onLogMessage?.({type:"warn",message:`[File Watcher (node.js)] ${e}`})}trace(e){!this.cts.token.isCancellationRequested&&this.verboseLogging&&this.onLogMessage?.({type:"trace",message:`[File Watcher (node.js)] ${e}`})}traceWithCorrelation(e){!this.cts.token.isCancellationRequested&&this.verboseLogging&&this.trace(`${e}${typeof this.request.correlationId=="number"?` <${this.request.correlationId}> `:""}`)}dispose(){this.cts.dispose(!0),super.dispose()}};var fa=class extends ua{constructor(e){super();this.recursiveWatcher=e;this.onDidError=Q.None;this._watchers=new Map;this.worker=this._register(new Qt)}get watchers(){return this._watchers.values()}async doWatch(e){e=this.removeDuplicateRequests(e);let n=[],r=new Set(Array.from(this.watchers));for(let o of e){let s=this._watchers.get(this.requestToWatcherKey(o));s&&Kl(s.request.excludes,o.excludes)&&Kl(s.request.includes,o.includes)?r.delete(s):n.push(o)}n.length&&this.trace(`Request to start watching: ${n.map(o=>this.requestToString(o)).join(",")}`),r.size&&this.trace(`Request to stop watching: ${Array.from(r).map(o=>this.requestToString(o.request)).join(",")}`),this.worker.clear();for(let o of r)this.stopWatching(o);this.createWatchWorker().work(n)}createWatchWorker(){return this.worker.value=new rr({maxWorkChunkSize:100,throttleDelay:100,maxBufferedWork:Number.MAX_VALUE},e=>{for(let n of e)this.startWatching(n)}),this.worker.value}requestToWatcherKey(e){return typeof e.correlationId=="number"?e.correlationId:this.pathToWatcherKey(e.path)}pathToWatcherKey(e){return ve?e:e.toLowerCase()}startWatching(e){let n=new pa(e,this.recursiveWatcher,o=>this._onDidChangeFile.fire(o),()=>this._onDidWatchFail.fire(e),o=>this._onDidLogMessage.fire(o),this.verboseLogging),r={request:e,instance:n};this._watchers.set(this.requestToWatcherKey(e),r)}async stop(){await super.stop();for(let e of this.watchers)this.stopWatching(e)}stopWatching(e){this.trace("stopping file watcher",e),this._watchers.delete(this.requestToWatcherKey(e.request)),e.instance.dispose()}removeDuplicateRequests(e){let n=new Map;for(let r of e){let o=n.get(r.correlationId);o||(o=new Map,n.set(r.correlationId,o));let s=this.pathToWatcherKey(r.path);o.has(s)&&this.trace(`ignoring a request for watching who's path is already watched: ${this.requestToString(r)}`),o.set(s,r)}return Array.from(n.values()).flatMap(r=>Array.from(r.values()))}async setVerboseLogging(e){super.setVerboseLogging(e);for(let n of this.watchers)n.instance.setVerboseLogging(e)}trace(e,n){this.verboseLogging&&this._onDidLogMessage.fire({type:"trace",message:this.toMessage(e,n)})}warn(e){this._onDidLogMessage.fire({type:"warn",message:this.toMessage(e)})}toMessage(e,n){return n?`[File Watcher (node.js)] ${e} (${this.requestToString(n.request)})`:`[File Watcher (node.js)] ${e}`}};var ga=class extends sa{constructor(t,e,n){super(t,e,n),this.init()}createWatcher(t){return t.add(new fa(void 0))}};var ma=class i extends ca{constructor(){super(...arguments);this.onDidChangeCapabilities=Q.None;this.resourceLocks=new ut(e=>It.getComparisonKey(e));this.mapHandleToPos=new Map;this.mapHandleToLock=new Map;this.writeHandles=new Map}static{this.TRACE_LOG_RESOURCE_LOCKS=!1}get capabilities(){return this._capabilities||(this._capabilities=1040414,ve&&(this._capabilities|=1024)),this._capabilities}async stat(e){try{let{stat:n,symbolicLink:r}=await Tt.stat(this.toFilePath(e)),o;return(n.mode&128)===0&&(o=2),(n.mode&Uc.S_IXUSR||n.mode&Uc.S_IXGRP||n.mode&Uc.S_IXOTH)&&(o=(o??0)|4),{type:this.toType(n,r),ctime:n.birthtime.getTime(),mtime:n.mtime.getTime(),size:n.size,permissions:o}}catch(n){throw this.toFileSystemProviderError(n)}}async statIgnoreError(e){try{return await this.stat(e)}catch{return}}async realpath(e){let n=this.toFilePath(e);return he.realpath(n)}async readdir(e){try{let n=await he.readdir(this.toFilePath(e),{withFileTypes:!0}),r=[];return await Promise.all(n.map(async o=>{try{let s;o.isSymbolicLink()?s=(await this.stat(te(e,o.name))).type:s=this.toType(o),r.push([o.name,s])}catch(s){this.logService.trace(s)}})),r}catch(n){throw this.toFileSystemProviderError(n)}}toType(e,n){let r;return n?.dangling?r=0:e.isFile()?r=1:e.isDirectory()?r=2:r=0,n&&(r|=64),r}async createResourceLock(e){let n=this.toFilePath(e);this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - request to acquire resource lock (${n})`);let r;for(;r=this.resourceLocks.get(e);)this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - waiting for resource lock to be released (${n})`),await r.wait();let o=new Eo;return this.resourceLocks.set(e,o),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${n})`),w(()=>{this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock dispose() (${n})`),this.resourceLocks.get(e)===o&&(this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock removed from resource-lock map (${n})`),this.resourceLocks.delete(e)),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock barrier open() (${n})`),o.open()})}async readFile(e,n){let r;try{n?.atomic&&(this.traceLock(`[Disk FileSystemProvider]: atomic read operation started (${this.toFilePath(e)})`),r=await this.createResourceLock(e));let o=this.toFilePath(e);return await Kn.readFile(o)}catch(o){throw this.toFileSystemProviderError(o)}finally{r?.dispose()}}traceLock(e){i.TRACE_LOG_RESOURCE_LOCKS&&this.logService.trace(e)}readFileStream(e,n,r){let o=Nt(s=>_.concat(s.map(a=>_.wrap(a))).buffer);return ia(this,e,o,s=>s.buffer,{...n,bufferSize:256*1024},r),o}async writeFile(e,n,r){return r?.atomic!==!1&&r?.atomic?.postfix&&await this.canWriteFileAtomic(e)?this.doWriteFileAtomic(e,te(on(e),`${Ee(e)}${r.atomic.postfix}`),n,r):this.doWriteFile(e,n,r)}async canWriteFileAtomic(e){try{let n=this.toFilePath(e),{symbolicLink:r}=await Tt.stat(n);if(r)return!1}catch{}return!0}async doWriteFileAtomic(e,n,r,o){let s=new N;try{s.add(await this.createResourceLock(e)),s.add(await this.createResourceLock(n)),await this.doWriteFile(n,r,{...o,create:!0,overwrite:!0},!0);try{await this.rename(n,e,{overwrite:!0})}catch(a){try{await this.delete(n,{recursive:!1,useTrash:!1,atomic:!1})}catch{}throw a}}finally{s.dispose()}}async doWriteFile(e,n,r,o){let s;try{let a=this.toFilePath(e);if(!r.create||!r.overwrite){if(await he.exists(a)){if(!r.overwrite)throw Y(g(2155,null),"EntryExists")}else if(!r.create)throw Y(g(2158,null),"EntryNotFound")}s=await this.open(e,{create:!0,append:r.append,unlock:r.unlock},o),await this.write(s,0,n,0,n.byteLength)}catch(a){throw await this.toFileSystemProviderWriteError(e,a)}finally{typeof s=="number"&&await this.close(s)}}static{this.canFlush=!0}static configureFlushOnWrite(e){i.canFlush=e}async open(e,n,r){let o=this.toFilePath(e),s;Vt(n)&&!r&&(s=await this.createResourceLock(e));let a;try{if(Vt(n)&&n.unlock)try{let{stat:l}=await Tt.stat(o);l.mode&128||await Kn.chmod(o,l.mode|128)}catch(l){l.code!=="ENOENT"&&this.logService.trace(l)}if(B&&Vt(n)&&!n.append)try{a=await he.open(o,"r+"),await he.ftruncate(a,0)}catch(l){if(l.code!=="ENOENT"&&this.logService.trace(l),typeof a=="number"){try{await he.close(a)}catch(c){this.logService.trace(c)}a=void 0}}typeof a!="number"&&(a=await he.open(o,Vt(n)?n.append?"a":"w":"r"))}catch(l){throw s?.dispose(),Vt(n)?await this.toFileSystemProviderWriteError(e,l):this.toFileSystemProviderError(l)}if(this.mapHandleToPos.set(a,0),Vt(n)&&this.writeHandles.set(a,e),s){let l=this.mapHandleToLock.get(a);this.traceLock(`[Disk FileSystemProvider]: open() - storing lock for handle ${a} (${o})`),this.mapHandleToLock.set(a,s),l&&(this.traceLock(`[Disk FileSystemProvider]: open() - disposing a previous lock that was still stored on same handle ${a} (${o})`),l.dispose())}return a}async close(e){let n=this.mapHandleToLock.get(e);try{if(this.mapHandleToPos.delete(e),this.writeHandles.delete(e)&&i.canFlush)try{await he.fdatasync(e)}catch(r){i.configureFlushOnWrite(!1),this.logService.error(r)}return await he.close(e)}catch(r){throw this.toFileSystemProviderError(r)}finally{n&&(this.mapHandleToLock.get(e)===n&&(this.traceLock(`[Disk FileSystemProvider]: close() - resource lock removed from handle-lock map ${e}`),this.mapHandleToLock.delete(e)),this.traceLock(`[Disk FileSystemProvider]: close() - disposing lock for handle ${e}`),n.dispose())}}async read(e,n,r,o,s){let a=this.normalizePos(e,n),l=null;try{l=(await he.read(e,r,o,s,a)).bytesRead}catch(c){throw this.toFileSystemProviderError(c)}finally{this.updatePos(e,a,l)}return l}normalizePos(e,n){return n===this.mapHandleToPos.get(e)?null:n}updatePos(e,n,r){let o=this.mapHandleToPos.get(e);typeof o=="number"&&(typeof n=="number"||(typeof r=="number"?this.mapHandleToPos.set(e,o+r):this.mapHandleToPos.delete(e)))}async write(e,n,r,o,s){return su(()=>this.doWrite(e,n,r,o,s),100,3)}async doWrite(e,n,r,o,s){let a=this.normalizePos(e,n),l=null;try{l=(await he.write(e,r,o,s,a)).bytesWritten}catch(c){throw await this.toFileSystemProviderWriteError(this.writeHandles.get(e),c)}finally{this.updatePos(e,a,l)}return l}async mkdir(e){try{await Kn.mkdir(this.toFilePath(e))}catch(n){throw this.toFileSystemProviderError(n)}}async delete(e,n){try{let r=this.toFilePath(e);if(n.recursive){let o;n?.atomic!==!1&&n.atomic.postfix&&(o=q(me(r),`${Te(r)}${n.atomic.postfix}`)),await he.rm(r,1,o)}else try{await Kn.unlink(r)}catch(o){if(o.code==="EPERM"||o.code==="EISDIR"){let s=!1;try{let{stat:a,symbolicLink:l}=await Tt.stat(r);s=a.isDirectory()&&!l}catch{}if(s)await Kn.rmdir(r);else throw o}else throw o}}catch(r){throw this.toFileSystemProviderError(r)}}async rename(e,n,r){let o=this.toFilePath(e),s=this.toFilePath(n);if(o!==s)try{await this.validateMoveCopy(e,n,"move",r.overwrite),await he.rename(o,s)}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(g(2159,null,Te(o),Te(me(s)),a.toString()))),this.toFileSystemProviderError(a)}}async copy(e,n,r){let o=this.toFilePath(e),s=this.toFilePath(n);if(o!==s)try{await this.validateMoveCopy(e,n,"copy",r.overwrite),await he.copy(o,s,{preserveSymlinks:!0})}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(g(2153,null,Te(o),Te(me(s)),a.toString()))),this.toFileSystemProviderError(a)}}async validateMoveCopy(e,n,r,o){let s=this.toFilePath(e),a=this.toFilePath(n),l=!1;if(this.capabilities&1024||(l=er(s,a,!0)),l){if(r==="copy")throw Y(g(2154,null),"EntryExists");if(r==="move")return}let p=await this.statIgnoreError(e);if(!p)throw Y(g(2157,null),"EntryNotFound");let u=await this.statIgnoreError(n);if(u){if(!o)throw Y(g(2156,null),"EntryExists");(p.type&1)!==0&&(u.type&1)!==0||await this.delete(n,{recursive:!0,useTrash:!1,atomic:!1})}}async cloneFile(e,n){return this.doCloneFile(e,n,!1)}async doCloneFile(e,n,r){let o=this.toFilePath(e),s=this.toFilePath(n),a=!!(this.capabilities&1024);if(er(o,s,!a))return;let l=new N;try{l.add(await this.createResourceLock(e)),l.add(await this.createResourceLock(n)),r&&await Kn.mkdir(me(s),{recursive:!0}),await Kn.copyFile(o,s)}catch(c){if(c.code==="ENOENT"&&!r)return this.doCloneFile(e,n,!0);throw this.toFileSystemProviderError(c)}finally{l.dispose()}}createUniversalWatcher(e,n,r){return new da(o=>e(o),o=>n(o),r)}createNonRecursiveWatcher(e,n,r){return new ga(o=>e(o),o=>n(o),r)}toFileSystemProviderError(e){if(e instanceof br)return e;let n=e,r;switch(e.code){case"ENOENT":r="EntryNotFound";break;case"EISDIR":r="EntryIsADirectory";break;case"ENOTDIR":r="EntryNotADirectory";break;case"EEXIST":r="EntryExists";break;case"EPERM":case"EACCES":r="NoPermissions";break;case"ERR_UNC_HOST_NOT_ALLOWED":n=`${e.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`,r="Unknown";break;default:r="Unknown"}return Y(n,r)}async toFileSystemProviderWriteError(e,n){let r=this.toFileSystemProviderError(n);if(e&&r.code==="NoPermissions")try{let{stat:o}=await Tt.stat(this.toFilePath(e));o.mode&128||(r=Y(n,"EntryWriteLocked"))}catch(o){this.logService.trace(o)}return r}};var Gt=class{constructor(t,e=[],n=!1){this.ctor=t,this.staticArguments=e,this.supportsDelayedInstantiation=n}};var Nc=class{constructor(t,e){this.key=t;this.data=e;this.incoming=new Map;this.outgoing=new Map}},Gi=class{constructor(t){this._hashFn=t;this._nodes=new Map}roots(){let t=[];for(let e of this._nodes.values())e.outgoing.size===0&&t.push(e);return t}insertEdge(t,e){let n=this.lookupOrInsertNode(t),r=this.lookupOrInsertNode(e);n.outgoing.set(r.key,r),r.incoming.set(n.key,n)}removeNode(t){let e=this._hashFn(t);this._nodes.delete(e);for(let n of this._nodes.values())n.outgoing.delete(e),n.incoming.delete(e)}lookupOrInsertNode(t){let e=this._hashFn(t),n=this._nodes.get(e);return n||(n=new Nc(e,t),this._nodes.set(e,n)),n}lookup(t){return this._nodes.get(this._hashFn(t))}isEmpty(){return this._nodes.size===0}toString(){let t=[];for(let[e,n]of this._nodes)t.push(`${e}
	(-> incoming)[${[...n.incoming.keys()].join(", ")}]
	(outgoing ->)[${[...n.outgoing.keys()].join(",")}]
`);return t.join(`
`)}findCycleSlow(){for(let[t,e]of this._nodes){let n=new Set([t]),r=this._findCycle(e,n);if(r)return r}}_findCycle(t,e){for(let[n,r]of t.outgoing){if(e.has(n))return[...e,n].join(" -> ");e.add(n);let o=this._findCycle(r,e);if(o)return o;e.delete(n)}}};var zr=class{constructor(...t){this._entries=new Map;for(let[e,n]of t)this.set(e,n)}set(t,e){let n=this._entries.get(t);return this._entries.set(t,e),n}has(t){return this._entries.has(t)}get(t){return this._entries.get(t)}};var wb=!1,ha=class extends Error{constructor(t){super("cyclic dependency between services"),this.message=t.findCycleSlow()??`UNABLE to detect cycle, dumping graph: 
${t.toString()}`}},va=class i{constructor(t=new zr,e=!1,n,r=wb){this._services=t;this._strict=e;this._parent=n;this._enableTracing=r;this._isDisposed=!1;this._servicesToMaybeDispose=new Set;this._children=new Set;this._activeInstantiations=new Set;this._services.set(pr,this),this._globalGraph=r?n?._globalGraph??new Gi(o=>o):void 0}dispose(){if(!this._isDisposed){this._isDisposed=!0,Ke(this._children),this._children.clear();for(let t of this._servicesToMaybeDispose)lo(t)&&t.dispose();this._servicesToMaybeDispose.clear()}}_throwIfDisposed(){if(this._isDisposed)throw new Error("InstantiationService has been disposed")}createChild(t,e){this._throwIfDisposed();let n=this,r=new class extends i{dispose(){n._children.delete(r),super.dispose()}}(t,this._strict,this,this._enableTracing);return this._children.add(r),e?.add(r),r}invokeFunction(t,...e){this._throwIfDisposed();let n=Ji.traceInvocation(this._enableTracing,t),r=!1;try{return t({get:s=>{if(r)throw to("service accessor is only valid during the invocation of its target method");let a=this._getOrCreateServiceInstance(s,n);return a||this._throwIfStrict(`[invokeFunction] unknown service '${s}'`,!1),a}},...e)}finally{r=!0,n.stop()}}createInstance(t,...e){this._throwIfDisposed();let n,r;return t instanceof Gt?(n=Ji.traceCreation(this._enableTracing,t.ctor),r=this._createInstance(t.ctor,t.staticArguments.concat(e),n)):(n=Ji.traceCreation(this._enableTracing,t),r=this._createInstance(t,e,n)),n.stop(),r}_createInstance(t,e=[],n){let r=ft.getServiceDependencies(t).sort((a,l)=>a.index-l.index),o=[];for(let a of r){let l=this._getOrCreateServiceInstance(a.id,n);l||this._throwIfStrict(`[createInstance] ${t.name} depends on UNKNOWN service ${a.id}.`,!1),o.push(l)}let s=r.length>0?r[0].index:e.length;if(e.length!==s){console.trace(`[createInstance] First service dependency of ${t.name} at position ${s+1} conflicts with ${e.length} static arguments`);let a=s-e.length;a>0?e=e.concat(new Array(a)):e=e.slice(0,s)}return Reflect.construct(t,e.concat(o))}_setCreatedServiceInstance(t,e){if(this._services.get(t)instanceof Gt)this._services.set(t,e);else if(this._parent)this._parent._setCreatedServiceInstance(t,e);else throw new Error("illegalState - setting UNKNOWN service instance")}_getServiceInstanceOrDescriptor(t){let e=this._services.get(t);return!e&&this._parent?this._parent._getServiceInstanceOrDescriptor(t):e}_getOrCreateServiceInstance(t,e){this._globalGraph&&this._globalGraphImplicitDependency&&this._globalGraph.insertEdge(this._globalGraphImplicitDependency,String(t));let n=this._getServiceInstanceOrDescriptor(t);return n instanceof Gt?this._safeCreateAndCacheServiceInstance(t,n,e.branch(t,!0)):(e.branch(t,!1),n)}_safeCreateAndCacheServiceInstance(t,e,n){if(this._activeInstantiations.has(t))throw new Error(`illegal state - RECURSIVELY instantiating service '${t}'`);this._activeInstantiations.add(t);try{return this._createAndCacheServiceInstance(t,e,n)}finally{this._activeInstantiations.delete(t)}}_createAndCacheServiceInstance(t,e,n){let r=new Gi(l=>l.id.toString()),o=0,s=[{id:t,desc:e,_trace:n}],a=new Set;for(;s.length;){let l=s.pop();if(!a.has(String(l.id))){if(a.add(String(l.id)),r.lookupOrInsertNode(l),o++>1e3)throw new ha(r);for(let c of ft.getServiceDependencies(l.desc.ctor)){let p=this._getServiceInstanceOrDescriptor(c.id);if(p||this._throwIfStrict(`[createInstance] ${t} depends on ${c.id} which is NOT registered.`,!0),this._globalGraph?.insertEdge(String(l.id),String(c.id)),p instanceof Gt){let u={id:c.id,desc:p,_trace:l._trace.branch(c.id,!0)};r.insertEdge(l,u),s.push(u)}}}}for(;;){let l=r.roots();if(l.length===0){if(!r.isEmpty())throw new ha(r);break}for(let{data:c}of l){if(this._getServiceInstanceOrDescriptor(c.id)instanceof Gt){let u=this._createServiceInstanceWithOwner(c.id,c.desc.ctor,c.desc.staticArguments,c.desc.supportsDelayedInstantiation,c._trace);this._setCreatedServiceInstance(c.id,u)}r.removeNode(c)}}return this._getServiceInstanceOrDescriptor(t)}_createServiceInstanceWithOwner(t,e,n=[],r,o){if(this._services.get(t)instanceof Gt)return this._createServiceInstance(t,e,n,r,o,this._servicesToMaybeDispose);if(this._parent)return this._parent._createServiceInstanceWithOwner(t,e,n,r,o);throw new Error(`illegalState - creating UNKNOWN service instance ${e.name}`)}_createServiceInstance(t,e,n=[],r,o,s){if(r){let a=new i(void 0,this._strict,this,this._enableTracing);a._globalGraphImplicitDependency=String(t);let l=new Map,c=new Ro(()=>{let p=a._createInstance(e,n,o);for(let[u,f]of l){let m=p[u];if(typeof m=="function")for(let v of f)v.disposable=m.apply(p,v.listener)}return l.clear(),s.add(p),p});return new Proxy(Object.create(null),{get(p,u){if(!c.isInitialized&&typeof u=="string"&&(u.startsWith("onDid")||u.startsWith("onWill"))){let v=l.get(u);return v||(v=new ti,l.set(u,v)),(I,y,S)=>{if(c.isInitialized)return c.value[u](I,y,S);{let C={listener:[I,y,S],disposable:void 0},X=v.push(C);return w(()=>{X(),C.disposable?.dispose()})}}}if(u in p)return p[u];let f=c.value,m=f[u];return typeof m!="function"||(m=m.bind(f),p[u]=m),m},set(p,u,f){return c.value[u]=f,!0},getPrototypeOf(p){return e.prototype}})}else{let a=this._createInstance(e,n,o);return s.add(a),a}}_throwIfStrict(t,e){if(e&&console.warn(t),this._strict)throw new Error(t)}};var Ji=class i{constructor(t,e){this.type=t;this.name=e;this._start=Date.now();this._dep=[]}static{this.all=new Set}static{this._None=new class extends i{constructor(){super(0,null)}stop(){}branch(){return this}}}static traceInvocation(t,e){return t?new i(2,e.name||new Error().stack.split(`
`).slice(3,4).join(`
`)):i._None}static traceCreation(t,e){return t?new i(1,e.name):i._None}static{this._totals=0}branch(t,e){let n=new i(3,t.toString());return this._dep.push([t,e,n]),n}stop(){let t=Date.now()-this._start;i._totals+=t;let e=!1;function n(o,s){let a=[],l=new Array(o+1).join("	");for(let[c,p,u]of s._dep)if(p&&u){e=!0,a.push(`${l}CREATES -> ${c}`);let f=n(o+1,u);f&&a.push(f)}else a.push(`${l}uses -> ${c}`);return a.join(`
`)}let r=[`${this.type===1?"CREATE":"CALL"} ${this.name}`,`${n(1,this)}`,`DONE, took ${t.toFixed(2)}ms (grand total ${i._totals.toFixed(2)}ms)`];(t>2||e)&&i.all.add(r.join(`
`))}};import*as dg from"fs";var ag=[{version:1,sql:[`CREATE TABLE IF NOT EXISTS turns (
				id TEXT PRIMARY KEY NOT NULL
			)`,`CREATE TABLE IF NOT EXISTS file_edits (
				turn_id        TEXT    NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
				tool_call_id   TEXT    NOT NULL,
				file_path      TEXT    NOT NULL,
				before_content BLOB   NOT NULL,
				after_content  BLOB   NOT NULL,
				added_lines    INTEGER,
				removed_lines  INTEGER,
				PRIMARY KEY (tool_call_id, file_path)
			)`].join(`;
`)},{version:2,sql:`CREATE TABLE IF NOT EXISTS session_metadata (
			key   TEXT PRIMARY KEY NOT NULL,
			value TEXT NOT NULL
		)`},{version:3,sql:[`CREATE TABLE file_edits_v3 (
				turn_id        TEXT    NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
				tool_call_id   TEXT    NOT NULL,
				file_path      TEXT    NOT NULL,
				edit_type      TEXT    NOT NULL DEFAULT 'edit',
				original_path  TEXT,
				before_content BLOB,
				after_content  BLOB,
				added_lines    INTEGER,
				removed_lines  INTEGER,
				PRIMARY KEY (tool_call_id, file_path)
			)`,`INSERT INTO file_edits_v3 (turn_id, tool_call_id, file_path, edit_type, before_content, after_content, added_lines, removed_lines)
				SELECT turn_id, tool_call_id, file_path, 'edit', before_content, after_content, added_lines, removed_lines FROM file_edits`,"DROP TABLE file_edits","ALTER TABLE file_edits_v3 RENAME TO file_edits"].join(`;
`)},{version:4,sql:["ALTER TABLE turns ADD COLUMN event_id TEXT","CREATE INDEX IF NOT EXISTS idx_turns_event_id ON turns(event_id)"].join(`;
`)}];function ht(i,t){return new Promise((e,n)=>{i.exec(t,r=>r?n(r):e())})}function dt(i,t,e){return new Promise((n,r)=>{i.run(t,e,function(o){if(o)return r(o);n({changes:this.changes,lastID:this.lastID})})})}function jr(i,t,e){return new Promise((n,r)=>{i.get(t,e,(o,s)=>{if(o)return r(o);n(s)})})}function Qi(i,t,e){return new Promise((n,r)=>{i.all(t,e,(o,s)=>{if(o)return r(o);n(s)})})}function lg(i){return new Promise((t,e)=>{i.close(n=>n?e(n):t())})}function Pb(i){return new Promise((t,e)=>{import("@vscode/sqlite3").then(n=>{let r=new n.default.Database(i,o=>{if(o)return e(o);t(r)})},e)})}async function Ab(i,t){await ht(i,"PRAGMA foreign_keys = ON");let n=(await jr(i,"PRAGMA user_version",[]))?.user_version??0,r=t.filter(o=>o.version>n).sort((o,s)=>o.version-s.version);if(r.length!==0){await ht(i,"BEGIN TRANSACTION");try{for(let o of r)await ht(i,o.sql),await ht(i,`PRAGMA user_version = ${o.version}`);await ht(i,"COMMIT")}catch(o){throw await ht(i,"ROLLBACK"),o}}}var ba=class i{constructor(t,e=ag){this._path=t;this._migrations=e;this._fileEditSequencer=new St}static async open(t,e=ag){let n=new i(t,e);return await n._ensureDb(),n}_ensureDb(){return this._closed?Promise.reject(new Error("SessionDatabase has been disposed")):(this._dbPromise||(this._dbPromise=(async()=>{await dg.promises.mkdir(me(this._path),{recursive:!0});let t=await Pb(this._path);try{await Ab(t,this._migrations)}catch(e){throw await lg(t),this._dbPromise=void 0,e}if(this._closed)throw await lg(t),new Error("SessionDatabase has been disposed");return t})()),this._dbPromise)}async getAllTables(){let t=await this._ensureDb();return(await Qi(t,"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name",[])).map(n=>n.name)}async createTurn(t){let e=await this._ensureDb();await dt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t])}async deleteTurn(t){let e=await this._ensureDb();await dt(e,"DELETE FROM turns WHERE id = ?",[t])}async setTurnEventId(t,e){let n=await this._ensureDb();await dt(n,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t]),await dt(n,"UPDATE turns SET event_id = ? WHERE id = ? AND event_id IS NULL",[e,t])}async getTurnEventId(t){let e=await this._ensureDb();return(await jr(e,"SELECT event_id FROM turns WHERE id = ?",[t]))?.event_id??void 0}async getNextTurnEventId(t){let e=await this._ensureDb();return(await jr(e,"SELECT event_id FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?) ORDER BY rowid LIMIT 1",[t]))?.event_id??void 0}async getFirstTurnEventId(){let t=await this._ensureDb();return(await jr(t,"SELECT event_id FROM turns ORDER BY rowid LIMIT 1",[]))?.event_id??void 0}async truncateFromTurn(t){let e=await this._ensureDb();await dt(e,"DELETE FROM turns WHERE rowid >= (SELECT rowid FROM turns WHERE id = ?)",[t])}async deleteTurnsAfter(t){let e=await this._ensureDb();await dt(e,"DELETE FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?)",[t])}async deleteAllTurns(){let t=await this._ensureDb();await ht(t,"DELETE FROM turns")}async storeFileEdit(t){return this._fileEditSequencer.queue(t.filePath,async()=>{let e=await this._ensureDb();await dt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t.turnId]),await dt(e,`INSERT OR REPLACE INTO file_edits
					(turn_id, tool_call_id, file_path, edit_type, original_path, before_content, after_content, added_lines, removed_lines)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.turnId,t.toolCallId,t.filePath,t.kind,t.originalPath??null,t.beforeContent?Buffer.from(t.beforeContent):null,t.afterContent?Buffer.from(t.afterContent):null,t.addedLines??null,t.removedLines??null])})}async getFileEdits(t){if(t.length===0)return[];let e=await this._ensureDb(),n=t.map(()=>"?").join(",");return(await Qi(e,`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
				FROM file_edits
				WHERE tool_call_id IN (${n})
				ORDER BY rowid`,t)).map(o=>({turnId:o.turn_id,toolCallId:o.tool_call_id,filePath:o.file_path,kind:o.edit_type??"edit",originalPath:o.original_path??void 0,addedLines:o.added_lines??void 0,removedLines:o.removed_lines??void 0}))}async getAllFileEdits(){let t=await this._ensureDb();return(await Qi(t,`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
				FROM file_edits
				ORDER BY rowid`,[])).map(n=>({turnId:n.turn_id,toolCallId:n.tool_call_id,filePath:n.file_path,kind:n.edit_type??"edit",originalPath:n.original_path??void 0,addedLines:n.added_lines??void 0,removedLines:n.removed_lines??void 0}))}async getFileEditsByTurn(t){let e=await this._ensureDb();return(await Qi(e,`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
				FROM file_edits
				WHERE turn_id = ?
				ORDER BY rowid`,[t])).map(r=>({turnId:r.turn_id,toolCallId:r.tool_call_id,filePath:r.file_path,kind:r.edit_type??"edit",originalPath:r.original_path??void 0,addedLines:r.added_lines??void 0,removedLines:r.removed_lines??void 0}))}async readFileEditContent(t,e){return this._fileEditSequencer.queue(e,async()=>{let n=await this._ensureDb(),r=await jr(n,`SELECT before_content, after_content
					FROM file_edits
					WHERE tool_call_id = ? AND file_path = ?`,[t,e]);if(r)return{beforeContent:r.before_content?cg(r.before_content):void 0,afterContent:r.after_content?cg(r.after_content):void 0}})}async getMetadata(t){let e=await this._ensureDb();return(await jr(e,"SELECT value FROM session_metadata WHERE key = ?",[t]))?.value}async getMetadataObject(t){let e=Object.keys(t),n={};if(e.length===0)return n;let r=await this._ensureDb(),o=e.map(()=>"?").join(","),s=await Qi(r,`SELECT key, value FROM session_metadata WHERE key IN (${o})`,e);for(let a of e)n[a]=void 0;for(let a of s)n[a.key]=a.value;return n}async setMetadata(t,e){let n=await this._ensureDb();await dt(n,"INSERT OR REPLACE INTO session_metadata (key, value) VALUES (?, ?)",[t,e])}async remapTurnIds(t){let e=await this._ensureDb();await ht(e,"PRAGMA defer_foreign_keys = ON"),await ht(e,"BEGIN TRANSACTION");try{let n=[...t.keys()];if(n.length>0){let r=n.map(()=>"?").join(",");await dt(e,`DELETE FROM turns WHERE id NOT IN (${r})`,n)}for(let[r,o]of t)await dt(e,"UPDATE turns SET id = ? WHERE id = ?",[o,r]),await dt(e,"UPDATE file_edits SET turn_id = ? WHERE turn_id = ?",[o,r]);await ht(e,"COMMIT")}catch(n){throw await ht(e,"ROLLBACK"),n}}async close(){await(this._closed??=this._dbPromise?.then(t=>t.close()).catch(()=>{})||!0)}dispose(){this.close()}};function cg(i){return i instanceof Buffer?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i instanceof Uint8Array?i:typeof i=="string"?new TextEncoder().encode(i):new Uint8Array(0)}var Mc=class extends ao{constructor(e,n){super();this._getDbPath=e;this._logService=n}createReferencedObject(e){let n=this._getDbPath(e);return this._logService.trace(`[SessionDataService] Opening database: ${n}`),new ba(n)}destroyReferencedObject(e,n){n.dispose()}},Hr=class{constructor(t,e,n,r){this._fileService=e;this._logService=n;this._basePath=b.joinPath(t,"agentSessionData"),this._databases=new Mc(r??(o=>b.joinPath(this._basePath,o,Nr).fsPath),this._logService)}getSessionDataDir(t){return this.getSessionDataDirById(ce.id(t))}getSessionDataDirById(t){let e=t.replace(/[^a-zA-Z0-9_.-]/g,"-");return b.joinPath(this._basePath,e)}_sanitizedSessionKey(t){return ce.id(t).replace(/[^a-zA-Z0-9_.-]/g,"-")}openDatabase(t){return this._databases.acquire(this._sanitizedSessionKey(t))}async tryOpenDatabase(t){let e=this._sanitizedSessionKey(t),n=b.joinPath(this._basePath,e,Nr);if(await this._fileService.exists(n))return this._databases.acquire(e)}async deleteSessionData(t){let e=this.getSessionDataDir(t);try{await this._fileService.exists(e)&&(await this._fileService.del(e,{recursive:!0}),this._logService.trace(`[SessionDataService] Deleted session data: ${e.toString()}`))}catch(n){this._logService.warn(`[SessionDataService] Failed to delete session data: ${e.toString()}`,n)}}async cleanupOrphanedData(t){try{if(!await this._fileService.exists(this._basePath))return;let n=await this._fileService.resolve(this._basePath);if(!n.children)return;let r=[];for(let o of n.children){if(!o.isDirectory)continue;let s=o.name;t.has(s)||(this._logService.trace(`[SessionDataService] Cleaning up orphaned session data: ${s}`),r.push(this._fileService.del(o.resource,{recursive:!0}).catch(a=>{this._logService.warn(`[SessionDataService] Failed to clean up orphaned data: ${s}`,a)})))}await Promise.all(r)}catch(e){this._logService.warn("[SessionDataService] Failed to run orphan cleanup",e)}}};Hr=O([K(1,tt),K(2,ue)],Hr);var ya=class extends L{constructor(){super(...arguments);this.capabilities=1026;this._onDidChangeCapabilities=this._register(new x);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._onDidChangeFile=this._register(new x);this.onDidChangeFile=this._onDidChangeFile.event;this._authorityToConnection=new Map}registerAuthority(e,n){return this._authorityToConnection.set(e,n),w(()=>this._authorityToConnection.delete(e))}watch(){return L.None}async stat(e){let n=e.path;if(n==="/"||n==="")return{type:2,mtime:0,ctime:0,size:0,permissions:1};let r=this._decodeUri(e);if(r.scheme==="session-db")return{type:1,mtime:0,ctime:0,size:0,permissions:1};if(r.path==="/"||r.path==="")return{type:2,mtime:0,ctime:0,size:0,permissions:1};let o=on(e),s=Ee(e),l=(await this._listDirectory(e.authority,o)).find(c=>c.name===s);if(!l)throw Y(`File not found: ${n}`,"EntryNotFound");return{type:l.type==="directory"?2:1,mtime:0,ctime:0,size:0,permissions:1}}async readdir(e){return(await this._listDirectory(e.authority,e)).map(r=>[r.name,r.type==="directory"?2:1])}async readFile(e){let n=this._getConnection(e.authority);try{let r=this._decodeUri(e),o=await n.resourceRead(r);return o.encoding==="base64"?Do(o.data).buffer:_.fromString(o.data).buffer}catch(r){throw Y(r instanceof Error?r.message:String(r),"EntryNotFound")}}async writeFile(e,n,r){let o=this._getConnection(e.authority);try{let s=this._decodeUri(e);await o.resourceWrite({uri:s.toString(),data:_.wrap(n).toString(),encoding:"utf-8"})}catch(s){throw Y(s instanceof Error?s.message:String(s),"NoPermissions")}}async mkdir(){throw Y("mkdir not supported on remote filesystem","NoPermissions")}async delete(e,n){let r=this._getConnection(e.authority);try{let o=this._decodeUri(e);await r.resourceDelete({uri:o.toString(),recursive:n.recursive})}catch(o){throw Y(o instanceof Error?o.message:String(o),"NoPermissions")}}async rename(e,n,r){let o=this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(n);await o.resourceMove({source:s.toString(),destination:a.toString(),failIfExists:!r.overwrite})}catch(s){throw Y(s instanceof Error?s.message:String(s),"NoPermissions")}}_getConnection(e){let n=this._authorityToConnection.get(e);if(!n)throw Y(`No connection for authority: ${e}`,"Unavailable");return n}async _listDirectory(e,n){let r=this._getConnection(e);try{let o=this._decodeUri(n);return(await r.resourceList(o)).entries}catch(o){throw Y(o instanceof Error?o.message:String(o),"Unavailable")}}};var Ia="vscode-agent-client";function ug(i,t){let e=i.authority||"-";return b.from({scheme:Ia,authority:t,path:`/${i.scheme}/${e}${i.path}`})}function pg(i){let t=i.path,e=t.indexOf("/",1);if(e===-1)return b.from({scheme:"file",path:t});let n=t.substring(1,e),r=t.indexOf("/",e+1);if(r===-1){let a=t.substring(e+1);return b.from({scheme:n,authority:a==="-"?"":a,path:"/"})}let o=t.substring(e+1,r);o==="-"&&(o="");let s=t.substring(r);return b.from({scheme:n,authority:o||void 0,path:s})}var Yi=class extends ya{_decodeUri(t){return pg(t)}};var kb=20,Gr=class{constructor(t,e,n,r=kb){this._fileService=e;this._logService=n;this._sequencer=new St;this._cachedNonces=new Map;this._lruOrder=[];this._cacheLoaded=!1;this._basePath=b.joinPath(t,"agentPlugins"),this._cachePath=b.joinPath(this._basePath,"cache.json"),this._maxPlugins=r}async syncCustomizations(t,e,n){await this._ensureCacheLoaded();let r=e.map(s=>({customization:s,enabled:!0,status:"loading"}));return n?.([...r]),await Promise.all(e.map((s,a)=>this._sequencer.queue(s.uri,async()=>{try{let l=await this._syncPlugin(t,s);return r[a]={customization:s,enabled:!0,status:"loaded"},n?.([...r]),{customization:r[a],pluginDir:l}}catch(l){let c=l instanceof Error?l.message:String(l);return this._logService.error(`[AgentPluginManager] Failed to sync plugin ${s.uri}: ${c}`),r[a]={customization:s,enabled:!0,status:"error",statusMessage:c},n?.([...r]),{customization:r[a]}}})))}async _syncPlugin(t,e){let n=ug(b.parse(e.uri),t),r=this._keyForUri(e.uri),o=b.joinPath(this._basePath,r);return e.nonce&&this._cachedNonces.get(e.uri)===e.nonce?(this._touchLru(e.uri),this._logService.trace(`[AgentPluginManager] Nonce match for ${e.uri}, skipping copy`),o):(this._logService.info(`[AgentPluginManager] Syncing plugin: ${e.uri} \u2192 ${o.toString()}`),await this._fileService.copy(n,o,!0),e.nonce&&this._cachedNonces.set(e.uri,e.nonce),this._touchLru(e.uri),await this._evictIfNeeded(),await this._persistCache(),o)}_keyForUri(t){return t.replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,128)}_touchLru(t){let e=this._lruOrder.indexOf(t);e!==-1&&this._lruOrder.splice(e,1),this._lruOrder.push(t)}async _evictIfNeeded(){for(;this._lruOrder.length>this._maxPlugins;){let t=this._lruOrder.shift();if(!t)break;this._cachedNonces.delete(t);let e=this._keyForUri(t),n=b.joinPath(this._basePath,e);this._logService.info(`[AgentPluginManager] Evicting plugin: ${t}`);try{await this._fileService.del(n,{recursive:!0})}catch(r){this._logService.warn(`[AgentPluginManager] Failed to evict plugin: ${t}`,r)}}}async _ensureCacheLoaded(){if(!this._cacheLoaded){this._cacheLoaded=!0;try{if(!await this._fileService.exists(this._cachePath))return;let t=await this._fileService.readFile(this._cachePath),e=JSON.parse(t.value.toString());if(!Array.isArray(e))return;for(let n of e)typeof n.uri=="string"&&typeof n.nonce=="string"&&(this._cachedNonces.set(n.uri,n.nonce),this._lruOrder.push(n.uri));this._logService.trace(`[AgentPluginManager] Loaded ${e.length} cache entries from disk`)}catch(t){this._logService.warn("[AgentPluginManager] Failed to load cache from disk",t)}}}async _persistCache(){try{let t=[];for(let e of this._lruOrder){let n=this._cachedNonces.get(e);n&&t.push({uri:e,nonce:n})}await this._fileService.createFolder(this._basePath),await this._fileService.writeFile(this._cachePath,_.fromString(JSON.stringify(t)))}catch(t){this._logService.warn("[AgentPluginManager] Failed to persist cache to disk",t)}}};Gr=O([K(1,tt),K(2,ue)],Gr);Db();function Db(){let i;Wo(process)?i=new Bo:i=new No("agentHost");let t=new N,e={_serviceBrand:void 0,...eg},n=new Zs(wc(process.argv,Qf),e),r=new na(Up(n),n.logsHome);i.registerChannel("agentHostLogger",new ra(r,()=>Zf));let o=r.createLogger("agenthost",{name:g(1817,null)}),s=new ea(o);s.info("Agent Host process started successfully");let a=t.add(new mn(s));t.add(a.registerProvider(ee.file,t.add(new ma(s)))),t.add(Af(a));let l=new Hr(b.file(n.userDataPath),a,s),c;try{c=new Ps(s,a,l,e);let h=new Gr(b.file(n.userDataPath),a,s),I=new zr;I.set(Bs,n),I.set(ue,s),I.set(tt,a),I.set(Ur,l),I.set(Ns,h);let y=t.add(new un(s));I.set(bs,y),I.set(kr,c.terminalManager);let S=new va(I);I.set(Ws,S.createInstance(Ms)),c.registerProvider(S.createInstance(Ie))}catch(h){throw s.error("Failed to create AgentService",h),h}let p=dr.fromService(c,t);i.registerChannel("agentHost",p);let u=t.add(new x),f,m={onDidChangeConnectionCount:u.event,async startWebSocketServer(){if(f)return f;let h=B?`\\\\.\\pipe\\vscode-agent-host-${ne().replace(/-/g,"")}`:q(Xi.tmpdir(),`vscode-agent-host-${ne().replace(/-/g,"")}.sock`),I=t.add(await Hi.create({socketPath:h},s)),y=t.add(new Yi);t.add(a.registerProvider(Ia,y));let S=t.add(new qn(c,c.stateManager,I,{defaultDirectory:b.file(Xi.homedir()).toString()},y,s));return t.add(S.onDidChangeConnectionCount(C=>u.fire(C))),s.info(`[AgentHost] Dynamic WebSocket server listening on ${h}`),f={socketPath:h},f}},v=dr.fromService(m,t);i.registerChannel("agentHostConnectionTracker",v),Ob(c,a,s,t,h=>u.fire(h)).catch(h=>{s.error("Failed to start WebSocket server",h)}),process.once("exit",()=>{c.dispose(),s.dispose(),t.dispose()})}async function Ob(i,t,e,n,r){let o=process.env.VSCODE_AGENT_HOST_PORT,s=process.env.VSCODE_AGENT_HOST_SOCKET_PATH;if(!o&&!s)return;let a=process.env.VSCODE_AGENT_HOST_CONNECTION_TOKEN,l=process.env.VSCODE_AGENT_HOST_HOST||"localhost",c=n.add(await Hi.create(s?{socketPath:s,connectionTokenValidate:a?m=>m===a:void 0}:{port:parseInt(o,10),host:l,connectionTokenValidate:a?m=>m===a:void 0},e)),p=n.add(new Yi);n.add(t.registerProvider(Ia,p));let u=n.add(new qn(i,i.stateManager,c,{defaultDirectory:b.file(Xi.homedir()).toString()},p,e));n.add(u.onDidChangeConnectionCount(r));let f=s??`${l}:${o}`;e.info(`[AgentHost] WebSocket server listening on ${f}`),console.log(`Agent host server listening on ${f}`)}
