/*!--------------------------------------------------------
 * 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, Iterator */

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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), 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;
};

var ownKeys = function(o) {
    ownKeys = Object.getOwnPropertyNames || function (o) {
        var ar = [];
        for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
        return ar;
    };
    return ownKeys(o);
};

export function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
    __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;
    }
    var r, s = 0;
    function next() {
        while (r = env.stack.pop()) {
            try {
                if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                if (r.dispose) {
                    var result = r.dispose.call(r.value);
                    if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                }
                else s |= 1;
            }
            catch (e) {
                fail(e);
            }
        }
        if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
        if (env.hasError) throw env.error;
    }
    return next();
}

export function __rewriteRelativeImportExtension(path, preserveJsx) {
    if (typeof path === "string" && /^\.\.?\//.test(path)) {
        return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
            return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
        });
    }
    return path;
}

export default {
    __extends: __extends,
    __assign: __assign,
    __rest: __rest,
    __decorate: __decorate,
    __param: __param,
    __esDecorate: __esDecorate,
    __runInitializers: __runInitializers,
    __propKey: __propKey,
    __setFunctionName: __setFunctionName,
    __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,
    __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,
};

var ZC=Object.defineProperty;var e1=Object.getOwnPropertyDescriptor;var w=(r,t,e,n)=>{for(var i=n>1?void 0:n?e1(t,e):t,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=(n?s(t,e,i):s(i))||i);return n&&i&&ZC(t,e,i),i},C=(r,t)=>(e,n)=>t(e,n,r);function t1(r,t,e=0,n=r.length){let i=e,o=n;for(;i<o;){let s=Math.floor((i+o)/2);t(r[s])?i=s+1:o=s}return i-1}var dh=class r{constructor(t){this._array=t;this._findLastMonotonousLastIdx=0}static{this.assertInvariants=!1}findLastMonotonous(t){if(r.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=t1(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=e+1,e===-1?void 0:this._array[e]}};var bp=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(t){setTimeout(()=>{throw t.stack?mn.isErrorNoTelemetry(t)?new mn(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)}},Sp=new bp;function hi(r){Sp.onUnexpectedError(r)}function Ue(r){Xi(r)||Sp.onUnexpectedError(r)}function ph(r){Xi(r)||Sp.onUnexpectedExternalError(r)}var yl="Canceled";function Xi(r){return r instanceof re?!0:r instanceof Error&&r.name===yl&&r.message===yl}var re=class extends Error{constructor(){super(yl),this.name=this.message}},uh=class r extends Error{static{this._name="PendingMigrationError"}static is(t){return t instanceof r||t instanceof Error&&t.name===r._name}constructor(t){super(t),this.name=r._name}};function vl(){let r=new Error(yl);return r.name=r.message,r}function Ip(r){return r?new Error(`Illegal argument: ${r}`):new Error("Illegal argument")}function bl(r){return r?new Error(`Illegal state: ${r}`):new Error("Illegal state")}function Sl(r){return r?r.message?r.message:r.stack?r.stack.split(`
`)[0]:String(r):"Error"}var mn=class r extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof r)return t;let e=new r;return e.message=t.message,e.stack=t.stack,e}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},we=class r extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,r.prototype)}};function Vt(r,t,e=(n,i)=>n===i){if(r===t)return!0;if(!r||!t||r.length!==t.length)return!1;for(let n=0,i=r.length;n<i;n++)if(!e(r[n],t[n]))return!1;return!0}function Or(r){return r.filter(t=>!!t)}function Bn(r,t=e=>e){let e=new Set;return r.filter(n=>{let i=t(n);return e.has(i)?!1:(e.add(i),!0)})}function _p(r,t){return r.push(t),()=>n1(r,t)}function n1(r,t){let e=r.indexOf(t);if(e>-1)return r.splice(e,1),t}function Cp(r,t){let e;if(typeof t=="number"){let n=t;e=()=>{let i=Math.sin(n++)*179426549;return i-Math.floor(i)}}else e=Math.random;for(let n=r.length-1;n>0;n-=1){let i=Math.floor(e()*(n+1)),o=r[n];r[n]=r[i],r[i]=o}}function mh(r){return r[Math.floor(Math.random()*r.length)]}var hh;(a=>{function r(l){return l<0}a.isLessThan=r;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})(hh||={});function yh(r,t){return(e,n)=>t(r(e),r(n))}var vh=(r,t)=>r-t;var gh=class r{constructor(t){this.iterate=t}static{this.empty=new r(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 r(e=>this.iterate(n=>t(n)?e(n):!0))}map(t){return new r(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(i=>((n||hh.isGreaterThan(t(i,e)))&&(n=!1,e=i),!0)),e}};function _h(r,t){let e=Object.create(null);for(let n of r){let i=t(n),o=e[i];o||(o=e[i]=[]),o.push(n)}return e}var Sh,Ih,bh=class{constructor(t,e){this.toKey=e;this._map=new Map;this[Sh]="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))}[(Ih=Symbol.iterator,Sh=Symbol.toStringTag,Ih)](){return this.values()}};function Lr(r,t){let e=this,n=!1,i;return function(){if(n)return i;if(n=!0,t)try{i=r.apply(e,arguments)}finally{t()}else i=r.apply(e,arguments);return i}}var xp=class{constructor(t,e){this.uri=t;this.value=e}};function i1(r){return Array.isArray(r)}var Ch,Fe=class r{constructor(t,e){this[Ch]="ResourceMap";if(t instanceof r)this.map=new Map(t.map),this.toKey=e??r.defaultToKey;else if(i1(t)){this.map=new Map,this.toKey=e??r.defaultToKey;for(let[n,i]of t)this.set(n,i)}else this.map=new Map,this.toKey=t??r.defaultToKey}static{this.defaultToKey=t=>t.toString()}set(t,e){return this.map.set(this.toKey(t),new xp(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,i]of this.map)t(i.value,i.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]}*[(Ch=Symbol.toStringTag,Symbol.iterator)](){for(let[,t]of this.map)yield[t.uri,t.value]}},Th,Il=class{constructor(t,e){this[Th]="ResourceSet";!t||typeof t=="function"?this._map=new Fe(t):(this._map=new Fe(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,i)=>t.call(e,i,i,this))}has(t){return this._map.has(t)}entries(){return this._map.entries()}keys(){return this._map.keys()}values(){return this._map.keys()}[(Th=Symbol.toStringTag,Symbol.iterator)](){return this.keys()}};var xh,Ms=class{constructor(){this[xh]="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 i=this._map.get(t);if(i)i.value=e,n!==0&&this.touch(i,n);else{switch(i={key:t,value:e,next:void 0,previous:void 0},n){case 0:this.addItemLast(i);break;case 1:this.addItemFirst(i);break;case 2:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(t,i),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,i=this._head;for(;i;){if(e?t.bind(e)(i.value,i.key,this):t(i.value,i.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");i=i.next}}keys(){let t=this,e=this._state,n=this._head,i={[Symbol.iterator](){return i},[Symbol.dispose](){},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 i}values(){let t=this,e=this._state,n=this._head,i={[Symbol.iterator](){return i},[Symbol.dispose](){},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 i}entries(){let t=this,e=this._state,n=this._head,i={[Symbol.iterator](){return i},[Symbol.dispose](){},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 i}[(xh=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,i=t.previous;t===this._tail?(i.next=void 0,this._tail=i):(n.previous=i,i.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,i=t.previous;t===this._head?(n.previous=void 0,this._head=n):(n.previous=i,i.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)}},wp=class extends Ms{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))}},hn=class extends wp{constructor(t,e=1){super(t,e)}trim(t){this.trimOld(t)}set(t,e){return super.set(t,e),this.checkTrim(),this}};var _l=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 Cl(r,t){if(!r)throw new Error(t?`Assertion failed (${t})`:"Assertion Failed")}function Tl(r,t="unexpected state"){if(!r)throw typeof t=="string"?new we(`Assertion Failed: ${t}`):t}function Ns(r){if(!r()){debugger;r(),Ue(new we("Assertion Failed"))}}function Pe(r){return typeof r=="string"}function Oe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&!(r instanceof RegExp)&&!(r instanceof Date)}function wh(r){let t=Object.getPrototypeOf(Uint8Array);return typeof r=="object"&&r instanceof t}function Us(r){return typeof r=="number"&&!isNaN(r)}function Rh(r){return!!r&&typeof r[Symbol.iterator]=="function"}function Mr(r){return typeof r>"u"}function yi(r){return!sn(r)}function sn(r){return Mr(r)||r===null}function Eh(r,t){if(!r)throw new Error(t?`Unexpected type, expected '${t}'`:"Unexpected type")}var o1=Object.prototype.hasOwnProperty;function xl(r){if(!Oe(r))return!1;for(let t in r)if(o1.call(r,t))return!1;return!0}function Fs(r){return typeof r=="function"}function Le(r,t){for(let e in t)if(!(e in r))return!1;return!0}var Ur;(j=>{function r(E){return!!E&&typeof E=="object"&&typeof E[Symbol.iterator]=="function"}j.is=r;let t=Object.freeze([]);function e(){return t}j.empty=e;function*n(E){yield E}j.single=n;function i(E){return r(E)?E:n(E)}j.wrap=i;function o(E){return E??t}j.from=o;function*s(E){for(let M=E.length-1;M>=0;M--)yield E[M]}j.reverse=s;function a(E){return!E||E[Symbol.iterator]().next().done===!0}j.isEmpty=a;function l(E){return E[Symbol.iterator]().next().value}j.first=l;function c(E,M){let O=0;for(let G of E)if(M(G,O++))return!0;return!1}j.some=c;function u(E,M){let O=0;for(let G of E)if(!M(G,O++))return!1;return!0}j.every=u;function d(E,M){for(let O of E)if(M(O))return O}j.find=d;function*f(E,M){for(let O of E)M(O)&&(yield O)}j.filter=f;function*m(E,M){let O=0;for(let G of E)yield M(G,O++)}j.map=m;function*h(E,M){let O=0;for(let G of E)yield*M(G,O++)}j.flatMap=h;function*v(...E){for(let M of E)Rh(M)?yield*M:yield M}j.concat=v;function S(E,M,O){let G=O;for(let te of E)G=M(G,te);return G}j.reduce=S;function _(E){let M=0;for(let O of E)M++;return M}j.length=_;function*b(E,M,O=E.length){for(M<-E.length&&(M=0),M<0&&(M+=E.length),O<0?O+=E.length:O>E.length&&(O=E.length);M<O;M++)yield E[M]}j.slice=b;function I(E,M=Number.POSITIVE_INFINITY){let O=[];if(M===0)return[O,E];let G=E[Symbol.iterator]();for(let te=0;te<M;te++){let ye=G.next();if(ye.done)return[O,j.empty()];O.push(ye.value)}return[O,{[Symbol.iterator](){return G}}]}j.consume=I;async function R(E){let M=[];for await(let O of E)M.push(O);return M}j.asyncToArray=R;async function P(E){let M=[];for await(let O of E)M=M.concat(O);return M}j.asyncToArrayFlat=P})(Ur||={});var s1=!1,Fr=null;var Ph=class r{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:r.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 i=t.parent?this.getRootParent(this.getDisposableData(t.parent),e):t;return e.set(t,i),i}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(d=>d.source!==null&&!this.getRootParent(d,l).isSingleton);if(c.length===0)return;let u=new Set(c.map(d=>d.value));if(n=c.filter(d=>!(d.parent&&u.has(d.parent))),n.length===0)throw new Error("There are cyclic diposable chains!")}if(!n)return;function i(l){function c(d,f){for(;d.length>0&&f.some(m=>typeof m=="string"?m===d[0]:d[0].match(m));)d.shift()}let u=l.source.split(`
`).map(d=>d.trim().replace("at ","")).filter(d=>d!=="");return c(u,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),u.reverse()}let o=new _l;for(let l of n){let c=i(l);for(let u=0;u<=c.length;u++)o.add(c.slice(0,u).join(`
`),l)}n.sort(yh(l=>l.idx,vh));let s="",a=0;for(let l of n.slice(0,t)){a++;let c=i(l),u=[];for(let d=0;d<c.length;d++){let f=c[d];f=`(shared with ${o.get(c.slice(0,d+1).join(`
`)).size}/${n.length} leaks) at ${f}`;let h=o.get(c.slice(0,d).join(`
`)),v=_h([...h].map(S=>i(S)[d]),S=>S);delete v[c[d]];for(let[S,_]of Object.entries(v))_&&u.unshift(`    - stacktraces of ${_.length} other leaks continue with ${S}`);u.unshift(f)}s+=`


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

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


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

`),{leaks:n,details:s}}};function a1(r){Fr=r}if(s1){let r="__is_disposable_tracked__";a1(new class{trackDisposable(t){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[r]||console.log(e)},3e3)}setParent(t,e){if(t&&t!==T.None)try{t[r]=!0}catch{}}markAsDisposed(t){if(t&&t!==T.None)try{t[r]=!0}catch{}}markAsSingleton(t){}})}function vi(r){return Fr?.trackDisposable(r),r}function bi(r){Fr?.markAsDisposed(r)}function Zi(r,t){Fr?.setParent(r,t)}function l1(r,t){if(Fr)for(let e of r)Fr.setParent(e,t)}function $r(r){return typeof r=="object"&&r!==null&&typeof r.dispose=="function"&&r.dispose.length===0}function gt(r){if(Ur.is(r)){let t=[];for(let e of r)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(r)?[]:r}else if(r)return r.dispose(),r}function kh(...r){let t=A(()=>gt(r));return l1(r,t),t}var Rp=class{constructor(t){this._isDisposed=!1,this._fn=t,vi(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,bi(this),this._fn()}}};function A(r){return new Rp(r)}var z=class r{constructor(){this._toDispose=new Set;this._isDisposed=!1;vi(this)}static{this.DISABLE_DISPOSED_WARNING=!1}dispose(){this._isDisposed||(bi(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{gt(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t||t===T.None)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return Zi(t,this),this._isDisposed?r.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)&&Zi(t,null)}assertNotDisposed(){this._isDisposed&&Ue(new we("Object disposed"))}},T=class{constructor(){this._store=new z;vi(this),Zi(this._store,this)}static{this.None=Object.freeze({dispose(){}})}dispose(){bi(this),this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}},Rt=class{constructor(){this._isDisposed=!1;vi(this)}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),t&&Zi(t,this),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,bi(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let t=this._value;return this._value=void 0,t&&Zi(t,null),t}};var Wr=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:i}=n,o=Lr(()=>{--n.counter===0&&(this.destroyReferencedObject(t,n.object),this.references.delete(t))});return n.counter++,{object:i,dispose:o}}};var We=class{constructor(t=new Map){this._isDisposed=!1;this._store=t,vi(this)}dispose(){bi(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{gt(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),Zi(e,this)}deleteAndDispose(t){this._store.get(t)?.dispose(),this._store.delete(t)}deleteAndLeak(t){let e=this._store.get(t);return e&&Zi(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 Ah(r,t){return r.then(e=>(t.isDisposed?e.dispose():t.add(e),e))}var wl=class extends We{constructor(){super(new Fe)}};var Re=class r{static{this.Undefined=new r(void 0)}constructor(t){this.element=t,this.next=r.Undefined,this.prev=r.Undefined}},Ws=class{constructor(){this._first=Re.Undefined;this._last=Re.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===Re.Undefined}clear(){let t=this._first;for(;t!==Re.Undefined;){let e=t.next;t.prev=Re.Undefined,t.next=Re.Undefined,t=e}this._first=Re.Undefined,this._last=Re.Undefined,this._size=0}unshift(t){return this._insert(t,!1)}push(t){return this._insert(t,!0)}_insert(t,e){let n=new Re(t);if(this._first===Re.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 i=!1;return()=>{i||(i=!0,this._remove(n))}}shift(){if(this._first!==Re.Undefined){let t=this._first.element;return this._remove(this._first),t}}pop(){if(this._last!==Re.Undefined){let t=this._last.element;return this._remove(this._last),t}}peek(){if(this._last!==Re.Undefined)return this._last.element}_remove(t){if(t.prev!==Re.Undefined&&t.next!==Re.Undefined){let e=t.prev;e.next=t.next,t.next.prev=e}else t.prev===Re.Undefined&&t.next===Re.Undefined?(this._first=Re.Undefined,this._last=Re.Undefined):t.next===Re.Undefined?(this._last=this._last.prev,this._last.next=Re.Undefined):t.prev===Re.Undefined&&(this._first=this._first.next,this._first.prev=Re.Undefined);this._size-=1}*[Symbol.iterator](){let t=this._first;for(;t!==Re.Undefined;)yield t.element,t=t.next}};function c1(){return globalThis._VSCODE_NLS_MESSAGES}function Ep(){return globalThis._VSCODE_NLS_LANGUAGE}var d1=Ep()==="pseudo"||typeof document<"u"&&document.location&&typeof document.location.hash=="string"&&document.location.hash.indexOf("pseudo=true")>=0;function Dh(r,t){let e;return t.length===0?e=r:e=r.replace(/\{(\d+)\}/g,(n,i)=>{let o=i[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}),d1&&(e="\uFF3B"+e.replace(/[aouei]/g,"$&$&")+"\uFF3D"),e}function g(r,t,...e){return Dh(typeof r=="number"?u1(r,t):t,e)}function u1(r,t){let e=c1()?.[r];if(typeof e!="string"){if(typeof t=="string")return t;throw new Error(`!!! NLS MISSING: ${r} !!!`)}return e}var Ii="en",Vs=!1,Bs=!1,$s=!1,Lh=!1,Mh=!1,Pp=!1,p1=!1,Nh=!1,f1=!1,g1=!1,El,Pl=Ii,Oh=Ii,m1,Hn,zn=globalThis,Et;typeof zn.vscode<"u"&&typeof zn.vscode.process<"u"?Et=zn.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(Et=process);var Uh=typeof Et?.versions?.electron=="string",h1=Uh&&Et?.type==="renderer";if(typeof Et=="object"){Vs=Et.platform==="win32",Bs=Et.platform==="darwin",$s=Et.platform==="linux",Lh=$s&&!!Et.env.SNAP&&!!Et.env.SNAP_REVISION,p1=Uh,f1=!!Et.env.CI||!!Et.env.BUILD_ARTIFACTSTAGINGDIRECTORY||!!Et.env.GITHUB_WORKSPACE,El=Ii,Pl=Ii;let r=Et.env.VSCODE_NLS_CONFIG;if(r)try{let t=JSON.parse(r);El=t.userLocale,Oh=t.osLocale,Pl=t.resolvedLanguage||Ii,m1=t.languagePack?.translationsConfigFile}catch{}Mh=!0}else typeof navigator=="object"&&!h1?(Hn=navigator.userAgent,Vs=Hn.indexOf("Windows")>=0,Bs=Hn.indexOf("Macintosh")>=0,Nh=(Hn.indexOf("Macintosh")>=0||Hn.indexOf("iPad")>=0||Hn.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,$s=Hn.indexOf("Linux")>=0,g1=Hn?.indexOf("Mobi")>=0,Pp=!0,Pl=Ep()||Ii,El=navigator.language.toLowerCase(),Oh=El):console.error("Unable to resolve platform.");function Fh(r){switch(r){case 0:return"Web";case 1:return"Mac";case 2:return"Linux";case 3:return"Windows"}}var kl=0;Bs?kl=1:Vs?kl=3:$s&&(kl=2);var K=Vs,Ye=Bs,ve=$s,Wh=Lh,$h=Mh;var It=Pp,y1=Pp&&typeof zn.importScripts=="function",Vh=y1?zn.origin:void 0;var kp=kl,yn=Hn,Si=Pl,v1;(n=>{function r(){return Si}n.value=r;function t(){return Si.length===2?Si==="en":Si.length>=3?Si[0]==="e"&&Si[1]==="n"&&Si[2]==="-":!1}n.isDefaultVariant=t;function e(){return Si==="en"}n.isDefault=e})(v1||={});var b1=typeof zn.postMessage=="function"&&!zn.importScripts,Bh=(()=>{if(b1){let r=[];zn.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let n=0,i=r.length;n<i;n++){let o=r[n];if(o.id===e.data.vscodeScheduleAsyncWork){r.splice(n,1),o.callback();return}}});let t=0;return e=>{let n=++t;r.push({id:n,callback:e}),zn.postMessage({vscodeScheduleAsyncWork:n},"*")}}return r=>setTimeout(r)})();var mt=Bs||Nh?2:Vs?1:3;var Ap=!!(yn&&yn.indexOf("Chrome")>=0),Hh=!!(yn&&yn.indexOf("Firefox")>=0),zh=!!(!Ap&&yn&&yn.indexOf("Safari")>=0),qh=!!(yn&&yn.indexOf("Edg/")>=0),o2=!!(yn&&yn.indexOf("Android")>=0);var tr,Dp=globalThis.vscode;if(typeof Dp<"u"&&typeof Dp.process<"u"){let r=Dp.process;tr={get platform(){return r.platform},get arch(){return r.arch},get env(){return r.env},cwd(){return r.cwd()}}}else typeof process<"u"&&typeof process?.versions?.node=="string"?tr={get platform(){return process.platform},get arch(){return process.arch},get env(){return process.env},cwd(){return process.env.VSCODE_CWD||process.cwd()}}:tr={get platform(){return K?"win32":Ye?"darwin":"linux"},get arch(){},get env(){return{}},cwd(){return"/"}};var nr=tr.cwd,ke=tr.env,Vr=tr.platform,Kh=tr.arch;var S1=globalThis.performance.now.bind(globalThis.performance),Al=class r{static create(t){return new r(t)}constructor(t){this._now=t===!1?Date.now:S1,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 jh=!1,I1=!1,_1=100,Gh=6e4;function Jh(){return!!ke.VSCODE_DEV}var Q;($n=>{$n.None=()=>T.None;function t(W){if(I1){let{onDidAddListener:D}=W,U=Hr.create(),F=0;W.onDidAddListener=()=>{++F===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),U.print()),D?.()}}}function e(W,D,U){return m(W,()=>{},0,void 0,D??!0,void 0,U)}$n.defer=e;function n(W){return(D,U=null,F)=>{let $=!1,J;return J=W(ne=>{if(!$)return J?J.dispose():$=!0,D.call(U,ne)},null,F),$&&J.dispose(),J}}$n.once=n;function i(W,D){return $n.once($n.filter(W,D))}$n.onceIf=i;function o(W,D,U){return d((F,$=null,J)=>W(ne=>F.call($,D(ne)),null,J),U)}$n.map=o;function s(W,D,U){return d((F,$=null,J)=>W(ne=>{D(ne),F.call($,ne)},null,J),U)}$n.forEach=s;function a(W,D,U){return d((F,$=null,J)=>W(ne=>D(ne)&&F.call($,ne),null,J),U)}$n.filter=a;function l(W){return W}$n.signal=l;function c(...W){return(D,U=null,F)=>{let $=kh(...W.map(J=>J(ne=>D.call(U,ne))));return f($,F)}}$n.any=c;function u(W,D,U,F){let $=U;return o(W,J=>($=D($,J),$),F)}$n.reduce=u;function d(W,D){let U,F={onWillAddFirstListener(){U=W($.fire,$)},onDidRemoveLastListener(){U?.dispose()}};D||t(F);let $=new x(F);return D?.add($),$.event}function f(W,D){return D instanceof Array?D.push(W):D&&D.add(W),W}function m(W,D,U=100,F=!1,$=!1,J,ne){let tt,Ie,dt,nt=0,ft,Vn={leakWarningThreshold:J,onWillAddFirstListener(){tt=W(lh=>{nt++,Ie=D(Ie,lh),F&&!dt&&(Yi.fire(Ie),Ie=void 0),ft=()=>{let ch=Ie;Ie=void 0,dt=void 0,(!F||nt>1)&&Yi.fire(ch),nt=0},typeof U=="number"?(dt&&clearTimeout(dt),dt=setTimeout(ft,U)):dt===void 0&&(dt=null,queueMicrotask(ft))})},onWillRemoveListener(){$&&nt>0&&ft?.()},onDidRemoveLastListener(){ft=void 0,tt.dispose()}};ne||t(Vn);let Yi=new x(Vn);return ne?.add(Yi),Yi.event}$n.debounce=m;function h(W,D=0,U,F){return $n.debounce(W,($,J)=>$?($.push(J),$):[J],D,void 0,U??!0,void 0,F)}$n.accumulate=h;function v(W,D,U=100,F=!0,$=!0,J,ne){let tt,Ie,dt,nt=0,ft={leakWarningThreshold:J,onWillAddFirstListener(){tt=W(Yi=>{nt++,Ie=D(Ie,Yi),dt===void 0&&(F&&(Vn.fire(Ie),Ie=void 0,nt=0),typeof U=="number"?dt=setTimeout(()=>{$&&nt>0&&Vn.fire(Ie),Ie=void 0,dt=void 0,nt=0},U):(dt=0,queueMicrotask(()=>{$&&nt>0&&Vn.fire(Ie),Ie=void 0,dt=void 0,nt=0})))})},onDidRemoveLastListener(){tt.dispose()}};ne||t(ft);let Vn=new x(ft);return ne?.add(Vn),Vn.event}$n.throttle=v;function S(W,D=(F,$)=>F===$,U){let F=!0,$;return a(W,J=>{let ne=F||!D(J,$);return F=!1,$=J,ne},U)}$n.latch=S;function _(W,D,U){return[$n.filter(W,D,U),$n.filter(W,F=>!D(F),U)]}$n.split=_;function b(W,D,U=!1,F=[],$){let J=F.slice(),ne;Jh()&&(ne={stack:Hr.create(),timerId:setTimeout(()=>{J&&J.length>0&&ne&&!ne.warned&&(ne.warned=!0,console.warn(`[Event.buffer][${D}] potential LEAK detected: ${J.length} events buffered for ${Gh/1e3}s without being consumed. Buffered here:`),ne.stack.print())},Gh),warned:!1},$&&$.add(A(()=>clearTimeout(ne.timerId))));let tt=()=>{ne&&clearTimeout(ne.timerId)},Ie=W(ft=>{J?(J.push(ft),Jh()&&ne&&!ne.warned&&J.length>=_1&&(ne.warned=!0,console.warn(`[Event.buffer][${D}] potential LEAK detected: ${J.length} events buffered without being consumed. Buffered here:`),ne.stack.print())):nt.fire(ft)});$&&$.add(Ie);let dt=()=>{J?.forEach(ft=>nt.fire(ft)),J=null,tt()},nt=new x({onWillAddFirstListener(){Ie||(Ie=W(ft=>nt.fire(ft)),$&&$.add(Ie))},onDidAddFirstListener(){J&&(U?setTimeout(dt):dt())},onDidRemoveLastListener(){Ie&&Ie.dispose(),Ie=null,tt()}});return $&&$.add(nt),nt.event}$n.buffer=b;function I(W,D){return(F,$,J)=>{let ne=D(new P);return W(function(tt){let Ie=ne.evaluate(tt);Ie!==R&&F.call($,Ie)},void 0,J)}}$n.chain=I;let R=Symbol("HaltChainable");class P{constructor(){this.steps=[]}map(D){return this.steps.push(D),this}forEach(D){return this.steps.push(U=>(D(U),U)),this}filter(D){return this.steps.push(U=>D(U)?U:R),this}reduce(D,U){let F=U;return this.steps.push($=>(F=D(F,$),F)),this}latch(D=(U,F)=>U===F){let U=!0,F;return this.steps.push($=>{let J=U||!D($,F);return U=!1,F=$,J?$:R}),this}evaluate(D){for(let U of this.steps)if(D=U(D),D===R)break;return D}}function j(W,D,U=F=>F){let F=(...tt)=>ne.fire(U(...tt)),$=()=>W.on(D,F),J=()=>W.removeListener(D,F),ne=new x({onWillAddFirstListener:$,onDidRemoveLastListener:J});return ne.event}$n.fromNodeEventEmitter=j;function E(W,D,U=F=>F){let F=(...tt)=>ne.fire(U(...tt)),$=()=>W.addEventListener(D,F),J=()=>W.removeEventListener(D,F),ne=new x({onWillAddFirstListener:$,onDidRemoveLastListener:J});return ne.event}$n.fromDOMEventEmitter=E;function M(W,D){let U,F,$=new Promise(J=>{F=n(W)(J),Fp(F,D),U=()=>{Yh(F,D)}});return $.cancel=U,D&&$.finally(()=>Yh(F,D)),$}$n.toPromise=M;function O(W,D){return W(U=>D.fire(U))}$n.forward=O;function G(W,D,U){return D(U),W(F=>D(F))}$n.runAndSubscribe=G;class te{constructor(D,U){this._observable=D;this._counter=0;this._hasChanged=!1;let F={onWillAddFirstListener:()=>{D.addObserver(this),this._observable.reportChanges()},onDidRemoveLastListener:()=>{D.removeObserver(this)}};U||t(F),this.emitter=new x(F),U&&U.add(this.emitter)}beginUpdate(D){this._counter++}handlePossibleChange(D){}handleChange(D,U){this._hasChanged=!0}endUpdate(D){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function ye(W,D){return new te(W,D).emitter.event}$n.fromObservable=ye;function Ls(W){return(D,U,F)=>{let $=0,J=!1,ne={beginUpdate(){$++},endUpdate(){$--,$===0&&(W.reportChanges(),J&&(J=!1,D.call(U)))},handlePossibleChange(){},handleChange(){J=!0}};W.addObserver(ne),W.reportChanges();let tt={dispose(){W.removeObserver(ne)}};return Fp(tt,F),tt}}$n.fromObservableLight=Ls})(Q||={});var Lp=class r{constructor(t){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${t}_${r._idPool++}`,r.all.add(this)}static{this.all=new Set}static{this._idPool=0}start(t){this._stopWatch=new Al,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}}},Qh=-1;var Mp=class r{constructor(t,e,n=(r._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 i=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,i+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=n*.5;let[o,s]=this.getMostFrequentStack(),a=/^[0-9a-f]+$/i.test(this.name)?void 0:this.name,l=`[${this.name}] potential listener LEAK detected, having ${e} listeners already. MOST frequent listener (${s}):`;console.warn(l),console.warn(o);let c=s/e>.3?"dominated":"popular",u=new Dl(c,l,o,e,a);this._errorHandler(u)}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,i]of this._stacks)(!t||e<i)&&(t=[n,i],e=i);return t}},Hr=class r{constructor(t){this.value=t}static create(){let t=new Error;return new r(t.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},Dl=class r extends Error{constructor(t,e,n,i,o){super(o?`[${o}] potential listener LEAK detected, ${t}`:`potential listener LEAK detected, ${t}`),this.name="ListenerLeakError",this.kind=t,this.listenerCount=i,this.details=e,this.stack=n}static is(t){return t instanceof r||t instanceof Error&&typeof t.kind=="string"&&typeof t.listenerCount=="number"}},Np=class extends Dl{constructor(t,e,n,i,o){super(t,e,n,i,o),this.name="ListenerRefusalError"}},C1=0,Br=class{constructor(t){this.value=t;this.id=C1++}},T1=2,x1=(r,t)=>{if(r instanceof Br)t(r);else for(let e=0;e<r.length;e++){let n=r[e];n&&t(n)}},x=class{constructor(t){this._size=0;this._options=t,this._leakageMon=Qh>0||this._options?.leakWarningThreshold?new Mp(t?.onListenerError??Ue,this._options?.leakWarningThreshold??Qh,this._options?.leakWarningName):void 0,this._perfMon=this._options?._profName?new Lp(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(jh){let t=this._listeners;queueMicrotask(()=>{x1(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],u=c[1]/this._size>.3?"dominated":"popular",d=new Np(u,`${l}. HINT: Stack shows most frequent listener (${c[1]}-times)`,c[0],this._size,this._options?.leakWarningName);return(this._options?.onListenerError||Ue)(d),T.None}if(this._disposed)return T.None;e&&(t=t.bind(e));let i=new Br(t),o,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(i.stack=Hr.create(),o=this._leakageMon.check(i.stack,this._size+1)),jh&&(i.stack=s??Hr.create()),this._listeners?this._listeners instanceof Br?(this._deliveryQueue??=new Up,this._listeners=[this._listeners,i]):this._listeners.push(i):(this._options?.onWillAddFirstListener?.(this),this._listeners=i,this._options?.onDidAddFirstListener?.(this)),this._options?.onDidAddListener?.(this),this._size++;let a=A(()=>{o?.(),this._removeListener(i)});return Fp(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 i=this._deliveryQueue.current===this;if(this._size*T1<=e.length){let o=0;for(let s=0;s<e.length;s++)e[s]?e[o++]=e[s]:i&&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||Ue;if(!n){t.value(e);return}try{t.value(e)}catch(i){n(i)}}_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 Br)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 Up=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 Ol=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),A(Lr(()=>{this.hasListeners&&this.unhook(e);let i=this.events.indexOf(e);this.events.splice(i,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 Hs=class{constructor(){this.listening=!1;this.inputEvent=Q.None;this.inputEventListener=T.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 Fp(r,t){t instanceof z?t.add(r):Array.isArray(t)&&t.push(r)}function Yh(r,t){if(t instanceof z)t.delete(r);else if(Array.isArray(t)){let e=t.indexOf(r);e!==-1&&t.splice(e,1)}r.dispose()}var Xh=Object.freeze(function(r,t){let e=setTimeout(r.bind(t),0);return{dispose(){clearTimeout(e)}}}),ze;(n=>{function r(i){return i===n.None||i===n.Cancelled||i instanceof zr?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}n.isCancellationToken=r,n.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Q.None}),n.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Xh})})(ze||={});var zr=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?Xh:(this._emitter||(this._emitter=new x),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Xe=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 zr),this._token}cancel(){this._token?this._token instanceof zr&&this._token.cancel():this._token=ze.Cancelled}dispose(t=!1){t&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof zr&&this._token.dispose():this._token=ze.None}};var w1=65,R1=97,E1=90,P1=122,ir=46,it=47,Pt=92,qn=58,k1=63,Ll=class extends Error{constructor(t,e,n){let i;typeof e=="string"&&e.indexOf("not ")===0?(i="must not be",e=e.replace(/^not /,"")):i="must be";let o=t.indexOf(".")!==-1?"property":"argument",s=`The "${t}" ${o} ${i} of type ${e}`;s+=`. Received type ${typeof n}`,super(s),this.code="ERR_INVALID_ARG_TYPE"}};function A1(r,t){if(r===null||typeof r!="object")throw new Ll(t,"Object",r)}function $e(r,t){if(typeof r!="string")throw new Ll(t,"string",r)}var kt=Vr==="win32";function ie(r){return r===it||r===Pt}function Wp(r){return r===it}function Kn(r){return r>=w1&&r<=E1||r>=R1&&r<=P1}function Ml(r,t,e,n){let i="",o=0,s=-1,a=0,l=0;for(let c=0;c<=r.length;++c){if(c<r.length)l=r.charCodeAt(c);else{if(n(l))break;l=it}if(n(l)){if(!(s===c-1||a===1))if(a===2){if(i.length<2||o!==2||i.charCodeAt(i.length-1)!==ir||i.charCodeAt(i.length-2)!==ir){if(i.length>2){let u=i.lastIndexOf(e);u===-1?(i="",o=0):(i=i.slice(0,u),o=i.length-1-i.lastIndexOf(e)),s=c,a=0;continue}else if(i.length!==0){i="",o=0,s=c,a=0;continue}}t&&(i+=i.length>0?`${e}..`:"..",o=2)}else i.length>0?i+=`${e}${r.slice(s+1,c)}`:i=r.slice(s+1,c),o=c-s-1;s=c,a=0}else l===ir&&a!==-1?++a:a=-1}return i}function D1(r){return r?`${r[0]==="."?"":"."}${r}`:""}function Zh(r,t){A1(t,"pathObject");let e=t.dir||t.root,n=t.base||`${t.name||""}${D1(t.ext)}`;return e?e===t.root?`${e}${n}`:`${e}${r}${n}`:n}var ae={resolve(...r){let t="",e="",n=!1;for(let i=r.length-1;i>=-1;i--){let o;if(i>=0){if(o=r[i],$e(o,`paths[${i}]`),o.length===0)continue}else t.length===0?o=nr():(o=ke[`=${t}`]||nr(),(o===void 0||o.slice(0,2).toLowerCase()!==t.toLowerCase()&&o.charCodeAt(2)===Pt)&&(o=`${t}\\`));let s=o.length,a=0,l="",c=!1,u=o.charCodeAt(0);if(s===1)ie(u)&&(a=1,c=!0);else if(ie(u))if(c=!0,ie(o.charCodeAt(1))){let d=2,f=d;for(;d<s&&!ie(o.charCodeAt(d));)d++;if(d<s&&d!==f){let m=o.slice(f,d);for(f=d;d<s&&ie(o.charCodeAt(d));)d++;if(d<s&&d!==f){for(f=d;d<s&&!ie(o.charCodeAt(d));)d++;(d===s||d!==f)&&(l=`\\\\${m}\\${o.slice(f,d)}`,a=d)}}}else a=1;else Kn(u)&&o.charCodeAt(1)===qn&&(l=o.slice(0,2),a=2,s>2&&ie(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=Ml(e,!n,"\\",ie),n?`${t}\\${e}`:`${t}${e}`||"."},normalize(r){$e(r,"path");let t=r.length;if(t===0)return".";let e=0,n,i=!1,o=r.charCodeAt(0);if(t===1)return Wp(o)?"\\":r;if(ie(o))if(i=!0,ie(r.charCodeAt(1))){let a=2,l=a;for(;a<t&&!ie(r.charCodeAt(a));)a++;if(a<t&&a!==l){let c=r.slice(l,a);for(l=a;a<t&&ie(r.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&!ie(r.charCodeAt(a));)a++;if(a===t)return`\\\\${c}\\${r.slice(l)}\\`;a!==l&&(n=`\\\\${c}\\${r.slice(l,a)}`,e=a)}}}else e=1;else Kn(o)&&r.charCodeAt(1)===qn&&(n=r.slice(0,2),e=2,t>2&&ie(r.charCodeAt(2))&&(i=!0,e=3));let s=e<t?Ml(r.slice(e),!i,"\\",ie):"";if(s.length===0&&!i&&(s="."),s.length>0&&ie(r.charCodeAt(t-1))&&(s+="\\"),!i&&n===void 0&&r.includes(":")){if(s.length>=2&&Kn(s.charCodeAt(0))&&s.charCodeAt(1)===qn)return`.\\${s}`;let a=r.indexOf(":");do if(a===t-1||ie(r.charCodeAt(a+1)))return`.\\${s}`;while((a=r.indexOf(":",a+1))!==-1)}return n===void 0?i?`\\${s}`:s:i?`${n}\\${s}`:`${n}${s}`},isAbsolute(r){$e(r,"path");let t=r.length;if(t===0)return!1;let e=r.charCodeAt(0);return ie(e)||t>2&&Kn(e)&&r.charCodeAt(1)===qn&&ie(r.charCodeAt(2))},join(...r){if(r.length===0)return".";let t,e;for(let o=0;o<r.length;++o){let s=r[o];$e(s,"path"),s.length>0&&(t===void 0?t=e=s:t+=`\\${s}`)}if(t===void 0)return".";let n=!0,i=0;if(typeof e=="string"&&ie(e.charCodeAt(0))){++i;let o=e.length;o>1&&ie(e.charCodeAt(1))&&(++i,o>2&&(ie(e.charCodeAt(2))?++i:n=!1))}if(n){for(;i<t.length&&ie(t.charCodeAt(i));)i++;i>=2&&(t=`\\${t.slice(i)}`)}return ae.normalize(t)},relative(r,t){if($e(r,"from"),$e(t,"to"),r===t)return"";let e=ae.resolve(r),n=ae.resolve(t);if(e===n||(r=e.toLowerCase(),t=n.toLowerCase(),r===t))return"";if(e.length!==r.length||n.length!==t.length){let h=e.split("\\"),v=n.split("\\");h[h.length-1]===""&&h.pop(),v[v.length-1]===""&&v.pop();let S=h.length,_=v.length,b=S<_?S:_,I;for(I=0;I<b&&h[I].toLowerCase()===v[I].toLowerCase();I++);return I===0?n:I===b?_>b?v.slice(I).join("\\"):S>b?"..\\".repeat(S-1-I)+"..":"":"..\\".repeat(S-I)+v.slice(I).join("\\")}let i=0;for(;i<r.length&&r.charCodeAt(i)===Pt;)i++;let o=r.length;for(;o-1>i&&r.charCodeAt(o-1)===Pt;)o--;let s=o-i,a=0;for(;a<t.length&&t.charCodeAt(a)===Pt;)a++;let l=t.length;for(;l-1>a&&t.charCodeAt(l-1)===Pt;)l--;let c=l-a,u=s<c?s:c,d=-1,f=0;for(;f<u;f++){let h=r.charCodeAt(i+f);if(h!==t.charCodeAt(a+f))break;h===Pt&&(d=f)}if(f!==u){if(d===-1)return n}else{if(c>u){if(t.charCodeAt(a+f)===Pt)return n.slice(a+f+1);if(f===2)return n.slice(a+f)}s>u&&(r.charCodeAt(i+f)===Pt?d=f:f===2&&(d=3)),d===-1&&(d=0)}let m="";for(f=i+d+1;f<=o;++f)(f===o||r.charCodeAt(f)===Pt)&&(m+=m.length===0?"..":"\\..");return a+=d,m.length>0?`${m}${n.slice(a,l)}`:(n.charCodeAt(a)===Pt&&++a,n.slice(a,l))},toNamespacedPath(r){if(typeof r!="string"||r.length===0)return r;let t=ae.resolve(r);if(t.length<=2)return r;if(t.charCodeAt(0)===Pt){if(t.charCodeAt(1)===Pt){let e=t.charCodeAt(2);if(e!==k1&&e!==ir)return`\\\\?\\UNC\\${t.slice(2)}`}}else if(Kn(t.charCodeAt(0))&&t.charCodeAt(1)===qn&&t.charCodeAt(2)===Pt)return`\\\\?\\${t}`;return t},dirname(r){$e(r,"path");let t=r.length;if(t===0)return".";let e=-1,n=0,i=r.charCodeAt(0);if(t===1)return ie(i)?r:".";if(ie(i)){if(e=n=1,ie(r.charCodeAt(1))){let a=2,l=a;for(;a<t&&!ie(r.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&ie(r.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&!ie(r.charCodeAt(a));)a++;if(a===t)return r;a!==l&&(e=n=a+1)}}}}else Kn(i)&&r.charCodeAt(1)===qn&&(e=t>2&&ie(r.charCodeAt(2))?3:2,n=e);let o=-1,s=!0;for(let a=t-1;a>=n;--a)if(ie(r.charCodeAt(a))){if(!s){o=a;break}}else s=!1;if(o===-1){if(e===-1)return".";o=e}return r.slice(0,o)},basename(r,t){t!==void 0&&$e(t,"suffix"),$e(r,"path");let e=0,n=-1,i=!0,o;if(r.length>=2&&Kn(r.charCodeAt(0))&&r.charCodeAt(1)===qn&&(e=2),t!==void 0&&t.length>0&&t.length<=r.length){if(t===r)return"";let s=t.length-1,a=-1;for(o=r.length-1;o>=e;--o){let l=r.charCodeAt(o);if(ie(l)){if(!i){e=o+1;break}}else a===-1&&(i=!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=r.length),r.slice(e,n)}for(o=r.length-1;o>=e;--o)if(ie(r.charCodeAt(o))){if(!i){e=o+1;break}}else n===-1&&(i=!1,n=o+1);return n===-1?"":r.slice(e,n)},extname(r){$e(r,"path");let t=0,e=-1,n=0,i=-1,o=!0,s=0;r.length>=2&&r.charCodeAt(1)===qn&&Kn(r.charCodeAt(0))&&(t=n=2);for(let a=r.length-1;a>=t;--a){let l=r.charCodeAt(a);if(ie(l)){if(!o){n=a+1;break}continue}i===-1&&(o=!1,i=a+1),l===ir?e===-1?e=a:s!==1&&(s=1):e!==-1&&(s=-1)}return e===-1||i===-1||s===0||s===1&&e===i-1&&e===n+1?"":r.slice(e,i)},format:Zh.bind(null,"\\"),parse(r){$e(r,"path");let t={root:"",dir:"",base:"",ext:"",name:""};if(r.length===0)return t;let e=r.length,n=0,i=r.charCodeAt(0);if(e===1)return ie(i)?(t.root=t.dir=r,t):(t.base=t.name=r,t);if(ie(i)){if(n=1,ie(r.charCodeAt(1))){let d=2,f=d;for(;d<e&&!ie(r.charCodeAt(d));)d++;if(d<e&&d!==f){for(f=d;d<e&&ie(r.charCodeAt(d));)d++;if(d<e&&d!==f){for(f=d;d<e&&!ie(r.charCodeAt(d));)d++;d===e?n=d:d!==f&&(n=d+1)}}}}else if(Kn(i)&&r.charCodeAt(1)===qn){if(e<=2)return t.root=t.dir=r,t;if(n=2,ie(r.charCodeAt(2))){if(e===3)return t.root=t.dir=r,t;n=3}}n>0&&(t.root=r.slice(0,n));let o=-1,s=n,a=-1,l=!0,c=r.length-1,u=0;for(;c>=n;--c){if(i=r.charCodeAt(c),ie(i)){if(!l){s=c+1;break}continue}a===-1&&(l=!1,a=c+1),i===ir?o===-1?o=c:u!==1&&(u=1):o!==-1&&(u=-1)}return a!==-1&&(o===-1||u===0||u===1&&o===a-1&&o===s+1?t.base=t.name=r.slice(s,a):(t.name=r.slice(s,o),t.base=r.slice(s,a),t.ext=r.slice(o,a))),s>0&&s!==n?t.dir=r.slice(0,s-1):t.dir=t.root,t},sep:"\\",delimiter:";",win32:null,posix:null},O1=(()=>{if(kt){let r=/\\/g;return()=>{let t=nr().replace(r,"/");return t.slice(t.indexOf("/"))}}return()=>nr()})(),Z={resolve(...r){let t="",e=!1;for(let n=r.length-1;n>=0&&!e;n--){let i=r[n];$e(i,`paths[${n}]`),i.length!==0&&(t=`${i}/${t}`,e=i.charCodeAt(0)===it)}if(!e){let n=O1();t=`${n}/${t}`,e=n.charCodeAt(0)===it}return t=Ml(t,!e,"/",Wp),e?`/${t}`:t.length>0?t:"."},normalize(r){if($e(r,"path"),r.length===0)return".";let t=r.charCodeAt(0)===it,e=r.charCodeAt(r.length-1)===it;return r=Ml(r,!t,"/",Wp),r.length===0?t?"/":e?"./":".":(e&&(r+="/"),t?`/${r}`:r)},isAbsolute(r){return $e(r,"path"),r.length>0&&r.charCodeAt(0)===it},join(...r){if(r.length===0)return".";let t=[];for(let e=0;e<r.length;++e){let n=r[e];$e(n,"path"),n.length>0&&t.push(n)}return t.length===0?".":Z.normalize(t.join("/"))},relative(r,t){if($e(r,"from"),$e(t,"to"),r===t||(r=Z.resolve(r),t=Z.resolve(t),r===t))return"";let e=1,n=r.length,i=n-e,o=1,s=t.length-o,a=i<s?i:s,l=-1,c=0;for(;c<a;c++){let d=r.charCodeAt(e+c);if(d!==t.charCodeAt(o+c))break;d===it&&(l=c)}if(c===a)if(s>a){if(t.charCodeAt(o+c)===it)return t.slice(o+c+1);if(c===0)return t.slice(o+c)}else i>a&&(r.charCodeAt(e+c)===it?l=c:c===0&&(l=0));let u="";for(c=e+l+1;c<=n;++c)(c===n||r.charCodeAt(c)===it)&&(u+=u.length===0?"..":"/..");return`${u}${t.slice(o+l)}`},toNamespacedPath(r){return r},dirname(r){if($e(r,"path"),r.length===0)return".";let t=r.charCodeAt(0)===it,e=-1,n=!0;for(let i=r.length-1;i>=1;--i)if(r.charCodeAt(i)===it){if(!n){e=i;break}}else n=!1;return e===-1?t?"/":".":t&&e===1?"//":r.slice(0,e)},basename(r,t){t!==void 0&&$e(t,"suffix"),$e(r,"path");let e=0,n=-1,i=!0,o;if(t!==void 0&&t.length>0&&t.length<=r.length){if(t===r)return"";let s=t.length-1,a=-1;for(o=r.length-1;o>=0;--o){let l=r.charCodeAt(o);if(l===it){if(!i){e=o+1;break}}else a===-1&&(i=!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=r.length),r.slice(e,n)}for(o=r.length-1;o>=0;--o)if(r.charCodeAt(o)===it){if(!i){e=o+1;break}}else n===-1&&(i=!1,n=o+1);return n===-1?"":r.slice(e,n)},extname(r){$e(r,"path");let t=-1,e=0,n=-1,i=!0,o=0;for(let s=r.length-1;s>=0;--s){let a=r[s];if(a==="/"){if(!i){e=s+1;break}continue}n===-1&&(i=!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?"":r.slice(t,n)},format:Zh.bind(null,"/"),parse(r){$e(r,"path");let t={root:"",dir:"",base:"",ext:"",name:""};if(r.length===0)return t;let e=r.charCodeAt(0)===it,n;e?(t.root="/",n=1):n=0;let i=-1,o=0,s=-1,a=!0,l=r.length-1,c=0;for(;l>=n;--l){let u=r.charCodeAt(l);if(u===it){if(!a){o=l+1;break}continue}s===-1&&(a=!1,s=l+1),u===ir?i===-1?i=l:c!==1&&(c=1):i!==-1&&(c=-1)}if(s!==-1){let u=o===0&&e?1:o;i===-1||c===0||c===1&&i===s-1&&i===o+1?t.base=t.name=r.slice(u,s):(t.name=r.slice(u,i),t.base=r.slice(u,s),t.ext=r.slice(i,s))}return o>0?t.dir=r.slice(0,o-1):e&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};Z.win32=ae.win32=ae;Z.posix=ae.posix=Z;var Qt=kt?ae.normalize:Z.normalize,Yt=kt?ae.isAbsolute:Z.isAbsolute,B=kt?ae.join:Z.join,an=kt?ae.resolve:Z.resolve,ey=kt?ae.relative:Z.relative,de=kt?ae.dirname:Z.dirname,_e=kt?ae.basename:Z.basename,Nl=kt?ae.extname:Z.extname,T2=kt?ae.format:Z.format,ty=kt?ae.parse:Z.parse,x2=kt?ae.toNamespacedPath:Z.toNamespacedPath,Ce=kt?ae.sep:Z.sep,qr=kt?ae.delimiter:Z.delimiter;function L1(r){return r}var Ul=class{constructor(t,e){this.lastCache=void 0;this.lastArgKey=void 0;typeof t=="function"?(this._fn=t,this._computeKey=L1):(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 Ee=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 sy(r){return!r||typeof r!="string"?!0:r.trim().length===0}var M1=/{(\d+)}/g;function or(r,...t){return t.length===0?r:r.replace(M1,function(e,n){let i=parseInt(n,10);return isNaN(i)||i<0||i>=t.length?e:t[i]})}function Bt(r){return r.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function Gn(r,t,e=B1){return r.length<=t?r:`${r.substr(0,t)}${e}`}function $p(r,t){if(!r||!t)return r;let e=t.length,n=0;if(e===1){let i=t.charCodeAt(0);for(;n<r.length&&r.charCodeAt(n)===i;)n++}else for(;r.startsWith(t,n);)n+=e;return r.substring(n)}function Kr(r,t){if(!r||!t)return r;let e=t.length,n=r.length;if(e===1){let o=n,s=t.charCodeAt(0);for(;o>0&&r.charCodeAt(o-1)===s;)o--;return r.substring(0,o)}let i=n;for(;i>0&&r.endsWith(t,i);)i-=e;return r.substring(0,i)}function ay(r){return r.source==="^"||r.source==="^$"||r.source==="$"||r.source==="^\\s*$"?!1:!!(r.exec("")&&r.lastIndex===0)}function ly(r){let t=[],e=r.split(/(\r\n|\r|\n)/);for(let n=0;n<Math.ceil(e.length/2);n++)t.push(e[2*n]+(e[2*n+1]??""));return t}function zs(r,t){return r<t?-1:r>t?1:0}function Fl(r,t,e=0,n=r.length,i=0,o=t.length){for(;e<n&&i<o;e++,i++){let l=r.charCodeAt(e),c=t.charCodeAt(i);if(l<c)return-1;if(l>c)return 1}let s=n-e,a=o-i;return s<a?-1:s>a?1:0}function Vp(r,t){return sr(r,t,0,r.length,0,t.length)}function sr(r,t,e=0,n=r.length,i=0,o=t.length){for(;e<n&&i<o;e++,i++){let l=r.charCodeAt(e),c=t.charCodeAt(i);if(l===c)continue;if(l>=128||c>=128)return Fl(r.toLowerCase(),t.toLowerCase(),e,n,i,o);ny(l)&&(l-=32),ny(c)&&(c-=32);let u=l-c;if(u!==0)return u}let s=n-e,a=o-i;return s<a?-1:s>a?1:0}function ny(r){return r>=97&&r<=122}function Bp(r){return r>=65&&r<=90}function Jn(r,t){return r.length===t.length&&sr(r,t)===0}function _i(r,t){let e=t.length;return e<=r.length&&sr(r,t,0,e)===0}function cy(r,t){let e=r.length,n=e-t.length;return n>=0&&sr(r,t,n,e)===0}function dy(r){return 55296<=r&&r<=56319}function Hp(r){return 56320<=r&&r<=57343}function uy(r,t){return(r-55296<<10)+(t-56320)+65536}var N1=/(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/,U1=/(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/,F1=/\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/,W1=new RegExp("(?:"+[N1.source,U1.source,F1.source].join("|")+")","g");function py(r){return r&&(r=r.replace(W1,"")),r}var N2=String.fromCharCode(65279);function $1(r){return!!(r&&r.length>0&&r.charCodeAt(0)===65279)}function fy(r){return $1(r)?r.substr(1):r}var iy=class r{static{this._INSTANCE=null}static getInstance(){return r._INSTANCE||(r._INSTANCE=new r),r._INSTANCE}constructor(){this._data=V1()}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,i=1;for(;i<=n;)if(t<e[3*i])i=2*i;else if(t>e[3*i+1])i=2*i+1;else return e[3*i+2];return 0}};function V1(){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 ry=class r{constructor(t){this.confusableDictionary=t}static{this.ambiguousCharacterData=new Ee(()=>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 Ul(t=>{let e=t.split(",");function n(d){let f=new Map;for(let m=0;m<d.length;m+=2)f.set(d[m],d[m+1]);return f}function i(d,f){let m=new Map(d);for(let[h,v]of f)m.set(h,v);return m}function o(d,f){if(!d)return f;let m=new Map;for(let[h,v]of d)f.has(h)&&m.set(h,v);return m}let s=this.ambiguousCharacterData.value,a=e.filter(d=>!d.startsWith("_")&&Object.hasOwn(s,d));a.length===0&&(a=["_default"]);let l;for(let d of a){let f=n(s[d]);l=o(l,f)}let c=n(s._common),u=i(c,l);return new r(u)})}static getInstance(t){return r.cache.get(Array.from(t).join(","))}static{this._locales=new Ee(()=>Object.keys(r.ambiguousCharacterData.value).filter(t=>!t.startsWith("_")))}static getLocales(){return r._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())}},oy=class r{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(r.getRawData())].flat())),this._data}static isInvisibleCharacter(t){return r.getData().has(t)}static containsInvisibleCharacter(t){for(let e=0;e<t.length;e++){let n=t.codePointAt(e);if(typeof n=="number"&&(r.isInvisibleCharacter(n)||n===32))return!0}return!1}static get codePoints(){return r.getData()}},B1="\u2026";function Ci(r){return r===47||r===92}function Wl(r){return r.replace(/[\\/]/g,Z.sep)}function gy(r){return r.indexOf("/")===-1&&(r=Wl(r)),/^[a-zA-Z]:(\/|$)/.test(r)&&(r="/"+r),r}function qp(r,t=Z.sep){if(!r)return"";let e=r.length,n=r.charCodeAt(0);if(Ci(n)){if(Ci(r.charCodeAt(1))&&!Ci(r.charCodeAt(2))){let o=3,s=o;for(;o<e&&!Ci(r.charCodeAt(o));o++);if(s!==o&&!Ci(r.charCodeAt(o+1))){for(o+=1;o<e;o++)if(Ci(r.charCodeAt(o)))return r.slice(0,o+1).replace(/[\\/]/g,t)}}return t}else if(my(n)&&r.charCodeAt(1)===58)return Ci(r.charCodeAt(2))?r.slice(0,2)+t:r.slice(0,2);let i=r.indexOf("://");if(i!==-1){for(i+=3;i<e;i++)if(Ci(r.charCodeAt(i)))return r.slice(0,i+1)}return""}function jr(r,t,e){let n=r===t;return!e||n?n:!r||!t?!1:Jn(r,t)}function Qn(r,t,e,n=Ce){if(r===t)return!0;if(!r||!t||t.length>r.length)return!1;if(e){if(!_i(r,t))return!1;if(t.length===r.length)return!0;let o=t.length;return t.charAt(t.length-1)===n&&o--,r.charAt(o)===n}return t.charAt(t.length-1)!==n&&(t+=n),r.indexOf(t)===0}function my(r){return r>=65&&r<=90||r>=97&&r<=122}function hy(r){return K?(r=Kr(r,Ce),r.endsWith(":")&&(r+=Ce)):(r=Kr(r,Ce),r||(r=Ce)),r}function Kp(r){let t=Qt(r);return K?r.length>3?!1:yy(t)&&(r.length===2||t.charCodeAt(2)===92):t===Z.sep}function yy(r,t=K){return t?my(r.charCodeAt(0))&&r.charCodeAt(1)===58:!1}var H1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",z1="BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";function vy(r,t,e=8){let n="";for(let o=0;o<e;o++){let s;o===0&&K&&!t&&(e===3||e===4)?s=z1:s=H1,n+=s.charAt(Math.floor(Math.random()*s.length))}let i;return t?i=`${t}-${n}`:i=n,r?B(r,i):i}var K1=/^\w[\w\d+.-]*$/,j1=/^\//,G1=/^\/\//;function J1(r,t){if(!r.scheme&&t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${r.authority}", path: "${r.path}", query: "${r.query}", fragment: "${r.fragment}"}`);if(r.scheme&&!K1.test(r.scheme)){let e=[...r.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:${r.scheme.length})`)}if(r.path){if(r.authority){if(!j1.test(r.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(G1.test(r.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function Q1(r,t){return!r&&!t?"file":r}function Y1(r,t){switch(r){case"https":case"http":case"file":t?t[0]!==ln&&(t=ln+t):t=ln;break}return t}var Te="",ln="/",X1=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,y=class r{static isUri(t){return t instanceof r?!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,i,o,s=!1){typeof t=="object"?(this.scheme=t.scheme||Te,this.authority=t.authority||Te,this.path=t.path||Te,this.query=t.query||Te,this.fragment=t.fragment||Te):(this.scheme=Q1(t,s),this.authority=e||Te,this.path=Y1(this.scheme,n||Te),this.query=i||Te,this.fragment=o||Te,J1(this,s))}get fsPath(){return qs(this,!1)}with(t){if(!t)return this;let{scheme:e,authority:n,path:i,query:o,fragment:s}=t;return e===void 0?e=this.scheme:e===null&&(e=Te),n===void 0?n=this.authority:n===null&&(n=Te),i===void 0?i=this.path:i===null&&(i=Te),o===void 0?o=this.query:o===null&&(o=Te),s===void 0?s=this.fragment:s===null&&(s=Te),e===this.scheme&&n===this.authority&&i===this.path&&o===this.query&&s===this.fragment?this:new Ti(e,n,i,o,s)}static parse(t,e=!1){let n=X1.exec(t);return n?new Ti(n[2]||Te,$l(n[4]||Te),$l(n[5]||Te),$l(n[7]||Te),$l(n[9]||Te),e):new Ti(Te,Te,Te,Te,Te)}static file(t){let e=Te;if(K&&(t=t.replace(/\\/g,ln)),t[0]===ln&&t[1]===ln){let n=t.indexOf(ln,2);n===-1?(e=t.substring(2),t=ln):(e=t.substring(2,n),t=t.substring(n)||ln)}return new Ti("file",e,t,Te,Te)}static from(t,e){return new Ti(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 K&&t.scheme==="file"?n=r.file(ae.join(qs(t,!0),...e)).path:n=Z.join(t.path,...e),t.with({path:n})}toString(t=!1){return jp(this,t)}toJSON(){return this}static revive(t){if(t){if(t instanceof r)return t;{let e=new Ti(t);return e._formatted=t.external??null,e._fsPath=t._sep===_y?t.fsPath??null:null,e}}else return t}[Symbol.for("debug.description")](){return`URI(${this.toString()})`}};function Iy(r){return!r||typeof r!="object"?!1:typeof r.scheme=="string"&&(typeof r.authority=="string"||typeof r.authority>"u")&&(typeof r.path=="string"||typeof r.path>"u")&&(typeof r.query=="string"||typeof r.query>"u")&&(typeof r.fragment=="string"||typeof r.fragment>"u")}var _y=K?1:void 0,Ti=class extends y{constructor(){super(...arguments);this._formatted=null;this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=qs(this,!1)),this._fsPath}toString(e=!1){return e?jp(this,!0):(this._formatted||(this._formatted=jp(this,!1)),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=_y),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}},Cy={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 by(r,t,e){let n,i=-1;for(let o=0;o<r.length;o++){let s=r.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)i!==-1&&(n+=encodeURIComponent(r.substring(i,o)),i=-1),n!==void 0&&(n+=r.charAt(o));else{n===void 0&&(n=r.substr(0,o));let a=Cy[s];a!==void 0?(i!==-1&&(n+=encodeURIComponent(r.substring(i,o)),i=-1),n+=a):i===-1&&(i=o)}}return i!==-1&&(n+=encodeURIComponent(r.substring(i))),n!==void 0?n:r}function Z1(r){let t;for(let e=0;e<r.length;e++){let n=r.charCodeAt(e);n===35||n===63?(t===void 0&&(t=r.substr(0,e)),t+=Cy[n]):t!==void 0&&(t+=r[e])}return t!==void 0?t:r}function qs(r,t){let e;return r.authority&&r.path.length>1&&r.scheme==="file"?e=`//${r.authority}${r.path}`:r.path.charCodeAt(0)===47&&(r.path.charCodeAt(1)>=65&&r.path.charCodeAt(1)<=90||r.path.charCodeAt(1)>=97&&r.path.charCodeAt(1)<=122)&&r.path.charCodeAt(2)===58?t?e=r.path.substr(1):e=r.path[1].toLowerCase()+r.path.substr(2):e=r.path,K&&(e=e.replace(/\//g,"\\")),e}function jp(r,t){let e=t?Z1:by,n="",{scheme:i,authority:o,path:s,query:a,fragment:l}=r;if(i&&(n+=i,n+=":"),(o||i==="file")&&(n+=ln,n+=ln),o){let c=o.indexOf("@");if(c!==-1){let u=o.substr(0,c);o=o.substr(c+1),c=u.lastIndexOf(":"),c===-1?n+=e(u,!1,!1):(n+=e(u.substr(0,c),!1,!1),n+=":",n+=e(u.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:by(l,!1,!1)),n}function Ty(r){try{return decodeURIComponent(r)}catch{return r.length>3?r.substr(0,3)+Ty(r.substr(3)):r}}var Sy=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function $l(r){return r.match(Sy)?r.replace(Sy,t=>Ty(t)):r}var oe;(X=>(X.inMemory="inmemory",X.vscode="vscode",X.internal="private",X.walkThrough="walkThrough",X.walkThroughSnippet="walkThroughSnippet",X.http="http",X.https="https",X.file="file",X.mailto="mailto",X.untitled="untitled",X.data="data",X.command="command",X.vscodeRemote="vscode-remote",X.vscodeRemoteResource="vscode-remote-resource",X.vscodeManagedRemoteResource="vscode-managed-remote-resource",X.vscodeUserData="vscode-userdata",X.vscodeCustomEditor="vscode-custom-editor",X.vscodeNotebookCell="vscode-notebook-cell",X.vscodeNotebookCellMetadata="vscode-notebook-cell-metadata",X.vscodeNotebookCellMetadataDiff="vscode-notebook-cell-metadata-diff",X.vscodeNotebookCellOutput="vscode-notebook-cell-output",X.vscodeNotebookCellOutputDiff="vscode-notebook-cell-output-diff",X.vscodeNotebookMetadata="vscode-notebook-metadata",X.vscodeInteractiveInput="vscode-interactive-input",X.vscodeSettings="vscode-settings",X.vscodeWorkspaceTrust="vscode-workspace-trust",X.vscodeTerminal="vscode-terminal",X.vscodeImageCarousel="vscode-image-carousel",X.vscodeChatCodeBlock="vscode-chat-code-block",X.vscodeChatCodeCompareBlock="vscode-chat-code-compare-block",X.vscodeChatEditor="vscode-chat-editor",X.vscodeChatInput="chatSessionInput",X.vscodeLocalChatSession="vscode-chat-session",X.webviewPanel="webview-panel",X.vscodeWebview="vscode-webview",X.vscodeBrowser="vscode-browser",X.extension="extension",X.vscodeFileResource="vscode-file",X.tmp="tmp",X.vsls="vsls",X.vscodeSourceControl="vscode-scm",X.commentsInput="comment",X.codeSetting="code-setting",X.outputChannel="output",X.accessibleView="accessible-view",X.chatEditingSnapshotScheme="chat-editing-snapshot-text-model",X.chatEditingModel="chat-editing-text-model",X.copilotPr="copilot-pr"))(oe||={});var Yp="tkn",Jp=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??"/",tT(t))}getServerRootPath(){return this._serverRootPath}get _remoteResourcesPath(){return Z.join(this._serverRootPath,oe.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 ph(a),t}let e=t.authority,n=this._hosts[e];n&&n.indexOf(":")!==-1&&n.indexOf("[")===-1&&(n=`[${n}]`);let i=this._ports[e],o=this._connectionTokens[e],s=`path=${encodeURIComponent(t.path)}`;return typeof o=="string"&&(s+=`&${Yp}=${encodeURIComponent(o)}`),y.from({scheme:It?this._preferredWebSchema:oe.vscodeRemoteResource,authority:`${n}:${i}`,path:It?(window.location.pathname+"/"+this._remoteResourcesPath).replace(/\/\/+/g,"/"):this._remoteResourcesPath,query:s})}},eT=new Jp;function tT(r){return`${r.quality??"oss"}-${r.commit??"dev"}`}var xy="vs/../../node_modules",wy="vs/../../node_modules.asar";var Xp="vscode-app",Qp=class r{static{this.FALLBACK_AUTHORITY=Xp}asBrowserUri(t){let e=this.toUri(t);return this.uriToBrowserUri(e)}uriToBrowserUri(t){return t.scheme===oe.vscodeRemote?eT.rewrite(t):t.scheme===oe.file&&($h||Vh===`${oe.vscodeFileResource}://${r.FALLBACK_AUTHORITY}`)?t.with({scheme:oe.vscodeFileResource,authority:t.authority||r.FALLBACK_AUTHORITY,query:null,fragment:null}):t}asFileUri(t){let e=this.toUri(t);return this.uriToFileUri(e)}uriToFileUri(t){return t.scheme===oe.vscodeFileResource?t.with({scheme:oe.file,authority:t.authority!==r.FALLBACK_AUTHORITY?t.authority:null,query:null,fragment:null}):t}toUri(t){if(y.isUri(t))return t;if(globalThis._VSCODE_FILE_ROOT){let e=globalThis._VSCODE_FILE_ROOT;if(/^\w[\w\d+.-]*:\/\//.test(e))return y.joinPath(y.parse(e,!0),t);let n=B(e,t);return y.file(n)}throw new Error("Cannot determine URI for module id!")}},rt=new Qp,J2=Object.freeze({"Cache-Control":"no-cache, no-store"}),Q2=Object.freeze({"Document-Policy":"include-js-call-stacks-in-crash-reports"}),nT;(o=>{let r=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(r.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:y.isUri(s)&&(a=new URL(s.toString(!0)).searchParams);let l=a?.get(e);if(l)return r.get(l)}o.getHeadersFromQuery=n;function i(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=i})(nT||={});function Yn(r){return qs(r,!0)}var Ks=class{constructor(t){this._ignorePathCasing=t}compare(t,e,n=!1){return t===e?0:zs(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===oe.file)return Qn(Yn(t),Yn(e),this._ignorePathCasing(t))&&t.query===e.query&&(n||t.fragment===e.fragment);if(Ry(t.authority,e.authority))return Qn(t.path,e.path,this._ignorePathCasing(t),"/")&&t.query===e.query&&(n||t.fragment===e.fragment)}return!1}joinPath(t,...e){return y.joinPath(t,...e)}basenameOrAuthority(t){return pe(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===oe.file?e=y.file(de(Yn(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===oe.file?e=y.file(Qt(Yn(t))).path:e=Z.normalize(t.path),t.with({path:e})}relativePath(t,e){if(t.scheme!==e.scheme||!Ry(t.authority,e.authority))return;if(t.scheme===oe.file){let o=ey(Yn(t),Yn(e));return K?Wl(o):o}let n=t.path||"/",i=e.path||"/";if(this._ignorePathCasing(t)){let o=0;for(let s=Math.min(n.length,i.length);o<s&&!(n.charCodeAt(o)!==i.charCodeAt(o)&&n.charAt(o).toLowerCase()!==i.charAt(o).toLowerCase());o++);n=i.substr(0,o)+n.substr(o)}return Z.relative(n,i)}resolvePath(t,e){if(t.scheme===oe.file){let n=y.file(an(Yn(t),e));return t.with({authority:n.authority,path:n.path})}return e=gy(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&&Jn(t,e)}hasTrailingPathSeparator(t,e=Ce){if(t.scheme===oe.file){let n=Yn(t);return n.length>qp(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=Ce){return Ey(t,e)?t.with({path:t.path.substr(0,t.path.length-1)}):t}addTrailingPathSeparator(t,e=Ce){let n=!1;if(t.scheme===oe.file){let i=Yn(t);n=i!==void 0&&i.length===qp(i).length&&i[i.length-1]===e}else{e="/";let i=t.path;n=i.length===1&&i.charCodeAt(i.length-1)===47}return!n&&!Ey(t,e)?t.with({path:t.path+"/"}):t}},se=new Ks(()=>!1),Ve=new Ks(r=>r.scheme===oe.file?!ve:!0),Zp=new Ks(r=>!0),ef=se.isEqual.bind(se),js=se.isEqualOrParent.bind(se),iO=se.getComparisonKey.bind(se),rO=se.basenameOrAuthority.bind(se),pe=se.basename.bind(se),Gs=se.extname.bind(se),vn=se.dirname.bind(se),ee=se.joinPath.bind(se),Ht=se.normalizePath.bind(se),tf=se.relativePath.bind(se),oO=se.resolvePath.bind(se),Py=se.isAbsolutePath.bind(se),Ry=se.isEqualAuthority.bind(se),Ey=se.hasTrailingPathSeparator.bind(se),sO=se.removeTrailingPathSeparator.bind(se),aO=se.addTrailingPathSeparator.bind(se);var iT;(o=>{o.META_DATA_LABEL="label",o.META_DATA_DESCRIPTION="description",o.META_DATA_SIZE="size",o.META_DATA_MIME="mime";function i(s){let a=new Map;s.path.substring(s.path.indexOf(";")+1,s.path.lastIndexOf(";")).split(";").forEach(u=>{let[d,f]=u.split(":");d&&f&&a.set(d,f)});let c=s.path.substring(0,s.path.indexOf(";"));return c&&a.set(o.META_DATA_MIME,c),a}o.parseMetaData=i})(iT||={});var ky=Symbol("MicrotaskDelay");function ql(r){return!!r&&typeof r.then=="function"}function Yr(r){let t=new Xe,e=r(t.token),n=!1,i=new Promise((o,s)=>{let a=t.token.onCancellationRequested(()=>{n=!0,a.dispose(),s(new re)});Promise.resolve(e).then(l=>{a.dispose(),t.dispose(),n?$r(l)&&l.dispose():o(l)},l=>{a.dispose(),t.dispose(),s(l)})});return new class{cancel(){t.cancel(),t.dispose()}then(o,s){return i.then(o,s)}catch(o){return this.then(void 0,o)}finally(o){return i.finally(o)}}}function Oy(r){let t=-1,e=r.map((i,o)=>i.then(s=>(t=o,s))),n=Promise.race(e);return n.cancel=()=>{r.forEach((i,o)=>{o!==t&&i.cancel&&i.cancel()})},n.finally(()=>{n.cancel()}),n}var nf=class{constructor(){this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null,this.cancellationTokenSource=new Xe}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(i=>{this.activePromise=null,e(i)},i=>{this.activePromise=null,n(i)})})}dispose(){this.cancellationTokenSource.cancel()}};var Ze=class{constructor(){this.promiseMap=new Map}queue(t,e){let i=(this.promiseMap.get(t)??Promise.resolve()).catch(()=>{}).then(e).finally(()=>{this.promiseMap.get(t)===i&&this.promiseMap.delete(t)});return this.promiseMap.set(t,i),i}peek(t){return this.promiseMap.get(t)||void 0}keys(){return this.promiseMap.keys()}},oT=(r,t)=>{let e=!0,n=setTimeout(()=>{e=!1,t()},r);return{isTriggered:()=>e,dispose:()=>{clearTimeout(n),e=!1}}},sT=r=>{let t=!0;return queueMicrotask(()=>{t&&(t=!1,r())}),{isTriggered:()=>t,dispose:()=>{t=!1}}},ar=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((i,o)=>{this.doResolve=i,this.doReject=o}).then(()=>{if(this.completionPromise=null,this.doResolve=null,this.task){let i=this.task;return this.task=null,i()}}));let n=()=>{this.deferred=null,this.doResolve?.(null)};return this.deferred=e===ky?sT(n):oT(e,n),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject?.(new re),this.completionPromise=null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}},lr=class{constructor(t){this.delayer=new ar(t),this.throttler=new nf}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()}},Bl=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 Xn(r,t){return t?new Promise((e,n)=>{let i=setTimeout(()=>{o.dispose(),e()},r),o=t.onCancellationRequested(()=>{clearTimeout(i),o.dispose(),n(new re)})}):Yr(e=>Xn(r,e))}function Ri(r,t=0,e){let n=setTimeout(()=>{r(),e&&i.dispose()},t),i=A(()=>{clearTimeout(n),e?.delete(i)});return e?.add(i),i}var Gr=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()}},xi=class extends Gr{constructor(){super(1)}};var Jr=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 fe;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=se){let n=e.getComparisonKey(t);return this.queues.get(n)?.size??0}queueFor(t,e,n=se){let i=n.getComparisonKey(t),o=this.queues.get(i);if(!o){o=new xi;let s=this.drainListenerCount++,a=Q.once(o.onDrained)(()=>{o?.dispose(),this.queues.delete(i),this.onDidQueueDrain(),this.drainListeners?.deleteAndDispose(s),this.drainListeners?.size===0&&(this.drainListeners.dispose(),this.drainListeners=void 0)});this.drainListeners||(this.drainListeners=new We),this.drainListeners.set(s,a),this.queues.set(i,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 wi=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 Hl=class extends wi{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()}},Qr=class extends T{constructor(e,n){super();this.options=e;this.handler=n;this.pendingWork=[];this.throttler=this._register(new Rt);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 i of e)this.pendingWork.push(i);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 wi(()=>{this.throttler.clear(),this.doWork()},e),this.throttler.value.schedule()}dispose(){super.dispose(),this.pendingWork.length=0,this.disposed=!0}},aT,Vl;(function(){let r=globalThis;typeof r.requestIdleCallback!="function"||typeof r.cancelIdleCallback!="function"?Vl=(t,e,n)=>{Bh(()=>{if(i)return;let o=Date.now()+15;e(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,o-Date.now())}}))});let i=!1;return{dispose(){i||(i=!0)}}}:Vl=(t,e,n)=>{let i=t.requestIdleCallback(e,typeof n=="number"?{timeout:n}:void 0),o=!1;return{dispose(){o||(o=!0,t.cancelIdleCallback(i))}}},aT=(t,e)=>Vl(globalThis,t,e)})();var rf=class{constructor(t,e){this._didRun=!1;this._executor=()=>{try{this._value=e()}catch(n){this._error=n}finally{this._didRun=!0}},this._handle=Vl(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}},zl=class extends rf{constructor(t){super(globalThis,t)}};async function Ly(r,t,e){let n;for(let i=0;i<e;i++)try{return await r()}catch(o){n=o,await Xn(t)}throw n}var fe=class r{static fromPromise(t){let e=new r;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 re)}},cr;(e=>{async function r(n){let i,o=await Promise.all(n.map(s=>s.then(a=>a,a=>{i||(i=a)})));if(typeof i<"u")throw i;return o}e.settled=r;function t(n){return new Promise(async(i,o)=>{try{await n(i,o)}catch(s){o(s)}})}e.withAsyncBody=t})(cr||={});var Ay=class r{static fromArray(t){return new r(e=>{e.emitMany(t)})}static fromPromise(t){return new r(async e=>{e.emitMany(await t)})}static fromPromisesResolveOrder(t){return new r(async e=>{await Promise.all(t.map(async n=>e.emitOne(await n)))})}static merge(t){return new r(async e=>{await Promise.all(t.map(async n=>{for await(let i of n)e.emitOne(i)}))})}static{this.EMPTY=r.fromArray([])}constructor(t,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new x,queueMicrotask(async()=>{let n={emitOne:i=>this.emitOne(i),emitMany:i=>this.emitMany(i),reject:i=>this.reject(i)};try{await Promise.resolve(t(n)),this.resolve()}catch(i){this.reject(i)}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 r(async n=>{for await(let i of t)n.emitOne(e(i))})}map(t){return r.map(this,t)}static filter(t,e){return new r(async n=>{for await(let i of t)e(i)&&n.emitOne(i)})}filter(t){return r.filter(this,t)}static coalesce(t){return r.filter(t,e=>!!e)}coalesce(){return r.coalesce(this)}static async toPromise(t){let e=[];for await(let n of t)e.push(n);return e}toPromise(){return r.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 of=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 we("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 fe;return this._unsatisfiedConsumers.push(t),t.p}}},Dy=class r{constructor(t,e){this._onReturn=e;this._producerConsumer=new of;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:i=>this._producerConsumer.produce({ok:!0,value:{done:!1,value:i}}),emitMany:i=>{for(let o of i)this._producerConsumer.produce({ok:!0,value:{done:!1,value:o}})},reject:i=>this._finishError(i)});if(!this._producerConsumer.hasFinalValue)try{await n,this._finishOk()}catch(i){this._finishError(i)}})}static fromArray(t){return new r(e=>{e.emitMany(t)})}static fromPromise(t){return new r(async e=>{e.emitMany(await t)})}static fromPromisesResolveOrder(t){return new r(async e=>{await Promise.all(t.map(async n=>e.emitOne(await n)))})}static merge(t){return new r(async e=>{await Promise.all(t.map(async n=>{for await(let i of n)e.emitOne(i)}))})}static{this.EMPTY=r.fromArray([])}static map(t,e){return new r(async n=>{for await(let i of t)n.emitOne(e(i))})}static tee(t){let e,n,i=new fe,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{i.complete()}},s=new r(async l=>(e=l,o(),i.p)),a=new r(async l=>(n=l,o(),i.p));return[s,a]}map(t){return r.map(this,t)}static coalesce(t){return r.filter(t,e=>!!e)}coalesce(){return r.coalesce(this)}static filter(t,e){return new r(async n=>{for await(let i of t)e(i)&&n.emitOne(i)})}filter(t){return r.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 Js(r){let t=r;return t?[t.on,t.pause,t.resume,t.destroy].every(e=>typeof e=="function"):!1}function Kl(r){let t=r;return t?Js(t.stream)&&Array.isArray(t.buffer)&&typeof t.ended=="boolean":!1}function Zn(r,t){return new sf(r,t)}var sf=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?Ue(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 i=n.indexOf(e);i>=0&&n.splice(i,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 My(r,t){let e=[],n;for(;(n=r.read())!==null;)e.push(n);return t(e)}function Ny(r,t,e){let n=[],i;for(;(i=r.read())!==null&&n.length<e;)n.push(i);return i===null&&n.length>0?t(n):{read:()=>{if(n.length>0)return n.shift();if(typeof i<"u"){let o=i;return i=void 0,o}return r.read()}}}function jl(r,t){return new Promise((e,n)=>{let i=[];Gl(r,{onData:o=>{t&&i.push(o)},onError:o=>{t?n(o):e(void 0)},onEnd:()=>{e(t?t(i):void 0)}})})}function Gl(r,t,e){r.on("error",n=>{e?.isCancellationRequested||t.onError(n)}),r.on("end",()=>{e?.isCancellationRequested||t.onEnd()}),r.on("data",n=>{e?.isCancellationRequested||t.onData(n)})}function Uy(r,t){return new Promise((e,n)=>{let i=new z,o=[],s=c=>{if(o.push(c),o.length>t)return i.dispose(),r.pause(),e({stream:r,buffer:o,ended:!1})},a=c=>(i.dispose(),n(c)),l=()=>(i.dispose(),e({stream:r,buffer:o,ended:!0}));i.add(A(()=>r.removeListener("error",a))),r.on("error",a),i.add(A(()=>r.removeListener("end",l))),r.on("end",l),i.add(A(()=>r.removeListener("data",s))),r.on("data",s)})}function Fy(r){let t=!1;return{read:()=>t?null:(t=!0,r)}}function af(r,t,e){let n=Zn(e);return Gl(r,{onData:i=>n.write(t.data(i)),onError:i=>n.error(t.error?t.error(i):i),onEnd:()=>n.end()}),n}var Qs=typeof Buffer<"u",cT=new Ee(()=>new Uint8Array(256)),lf,cf,k=class r{static alloc(t){return Qs?new r(Buffer.allocUnsafe(t)):new r(new Uint8Array(t))}static wrap(t){return Qs&&!Buffer.isBuffer(t)&&(t=Buffer.from(t.buffer,t.byteOffset,t.byteLength)),new r(t)}static fromString(t,e){return!(e?.dontUseNodeBuffer||!1)&&Qs?new r(Buffer.from(t)):(lf||(lf=new TextEncoder),new r(lf.encode(t)))}static fromByteArray(t){let e=r.alloc(t.length);for(let n=0,i=t.length;n<i;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=r.alloc(e),i=0;for(let o=0,s=t.length;o<s;o++){let a=t[o];n.set(a,i),i+=a.byteLength}return n}static isNativeBuffer(t){return Qs&&Buffer.isBuffer(t)}constructor(t){this.buffer=t,this.byteLength=this.buffer.byteLength}clone(){let t=r.alloc(this.byteLength);return t.set(this),t}toString(){return Qs?this.buffer.toString():(cf||(cf=new TextDecoder(void 0,{ignoreBOM:!0})),cf.decode(this.buffer))}slice(t,e){return new r(this.buffer.subarray(t,e))}set(t,e){if(t instanceof r)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 uT(this.buffer,t)}writeUInt32BE(t,e){pT(this.buffer,t,e)}readUInt32LE(t){return fT(this.buffer,t)}writeUInt32LE(t,e){gT(this.buffer,t,e)}readUInt8(t){return mT(this.buffer,t)}writeUInt8(t,e){hT(this.buffer,t,e)}indexOf(t,e=0){return dT(this.buffer,t instanceof r?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 dT(r,t,e=0){let n=t.byteLength,i=r.byteLength;if(n===0)return 0;if(n===1)return r.indexOf(t[0],e);if(n>i-e)return-1;let o=cT.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<i;)if(r[s]===t[a]){if(a===0){l=s;break}s--,a--}else s+=Math.max(t.length-a,o[r[s]]),a=t.length-1;return l}function uT(r,t){return r[t]*2**24+r[t+1]*2**16+r[t+2]*2**8+r[t+3]}function pT(r,t,e){r[e+3]=t,t=t>>>8,r[e+2]=t,t=t>>>8,r[e+1]=t,t=t>>>8,r[e]=t}function fT(r,t){return r[t+0]<<0>>>0|r[t+1]<<8>>>0|r[t+2]<<16>>>0|r[t+3]<<24>>>0}function gT(r,t,e){r[e+0]=t&255,t=t>>>8,r[e+1]=t&255,t=t>>>8,r[e+2]=t&255,t=t>>>8,r[e+3]=t&255}function mT(r,t){return r[t]}function hT(r,t,e){r[e]=t}function Vy(r){return My(r,t=>k.concat(t))}function By(r){return Fy(r)}function Ei(r){return jl(r,t=>k.concat(t))}async function Hy(r){return r.ended?k.concat(r.buffer):k.concat([...r.buffer,await Ei(r.stream)])}function zy(r){return Zn(t=>k.concat(t),r)}function bn(r){let t=0,e=0,n=0,i=new Uint8Array(Math.floor(r.length/4*3)),o=a=>{switch(e){case 3:i[n++]=t|a,e=0;break;case 2:i[n++]=t|a>>>2,t=a<<6,e=3;break;case 1:i[n++]=t|a>>>4,t=a<<4,e=2;break;default:t=a<<2,e=1}};for(let a=0;a<r.length;a++){let l=r.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 ${r[a]}`)}}let s=n;for(;e>0;)o(0);return k.wrap(i).slice(0,s)}var yT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",vT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Xr({buffer:r},t=!0,e=!1){let n=e?vT:yT,i="",o=r.byteLength%3,s=0;for(;s<r.byteLength-o;s+=3){let a=r[s+0],l=r[s+1],c=r[s+2];i+=n[a>>>2],i+=n[(a<<4|l>>>4)&63],i+=n[(l<<2|c>>>6)&63],i+=n[c&63]}if(o===1){let a=r[s+0];i+=n[a>>>2],i+=n[a<<4&63],t&&(i+="==")}else if(o===2){let a=r[s+0],l=r[s+1];i+=n[a>>>2],i+=n[(a<<4|l>>>4)&63],i+=n[l<<2&63],t&&(i+="=")}return i}var Wy="0123456789abcdef";function cn({buffer:r}){let t="";for(let e=0;e<r.length;e++){let n=r[e];t+=Wy[n>>>4],t+=Wy[n&15]}return t}function Zr(r){if(r.length%2!==0)throw new SyntaxError("Hex string must have an even length");let t=new Uint8Array(r.length>>1);for(let e=0;e<r.length;)t[e>>1]=$y(r,e++)<<4|$y(r,e++);return k.wrap(t)}function $y(r,t){let e=r.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 ce(r,t,e){let n=null,i=null;if(typeof e.value=="function"?(n="value",i=e.value,i.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof e.get=="function"&&(n="get",i=e.get),!i)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:i.apply(this,s)}),this[o]}}function Ys(r,t=0){if(!r||t>200)return r;if(typeof r=="object"){switch(r.$mid){case 1:return y.revive(r);case 2:return new RegExp(r.source,r.flags);case 17:return new Date(r.source)}if(r instanceof k||r instanceof Uint8Array)return r;if(Array.isArray(r))for(let e=0;e<r.length;++e)r[e]=Ys(r[e],t+1);else for(let e in r)Object.hasOwnProperty.call(r,e)&&(r[e]=Ys(r[e],t+1))}return r}function no(r){switch(r){case 100:return"req";case 101:return"cancel";case 102:return"subscribe";case 103:return"unsubscribe"}}function Jl(r){switch(r){case 200:return"init";case 201:return"reply:";case 202:case 203:return"replyErr:";case 204:return"event:"}}function eo(r){let t=0;for(let e=0;;e+=7){let n=r.read(1);if(t|=(n.buffer[0]&127)<<e,!(n.buffer[0]&128))return t}}var bT=Pi(0);function to(r,t){if(t===0){r.write(bT);return}let e=0;for(let i=t;i!==0;i=i>>>7)e++;let n=k.alloc(e);for(let i=0;t!==0;i++)n.buffer[i]=t&127,t=t>>>7,t>0&&(n.buffer[i]|=128);r.write(n)}var Xs=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}},Ql=class{constructor(){this.buffers=[]}get buffer(){return k.concat(this.buffers)}write(t){this.buffers.push(t)}};function Pi(r){let t=k.alloc(1);return t.writeUInt8(r,0),t}var dr={Undefined:Pi(0),String:Pi(1),Buffer:Pi(2),VSBuffer:Pi(3),Array:Pi(4),Object:Pi(5),Uint:Pi(6)};function Zs(r,t){if(typeof t>"u")r.write(dr.Undefined);else if(typeof t=="string"){let e=k.fromString(t);r.write(dr.String),to(r,e.byteLength),r.write(e)}else if(k.isNativeBuffer(t)){let e=k.wrap(t);r.write(dr.Buffer),to(r,e.byteLength),r.write(e)}else if(t instanceof k)r.write(dr.VSBuffer),to(r,t.byteLength),r.write(t);else if(Array.isArray(t)){r.write(dr.Array),to(r,t.length);for(let e of t)Zs(r,e)}else if(typeof t=="number"&&(t|0)===t)r.write(dr.Uint),to(r,t);else{let e=k.fromString(JSON.stringify(t));r.write(dr.Object),to(r,e.byteLength),r.write(e)}}function ro(r){switch(r.read(1).readUInt8(0)){case 0:return;case 1:return r.read(eo(r)).toString();case 2:return r.read(eo(r)).buffer;case 3:return r.read(eo(r));case 4:{let e=eo(r),n=[];for(let i=0;i<e;i++)n.push(ro(r));return n}case 5:return JSON.parse(r.read(eo(r)).toString());case 6:return eo(r)}}var ea=class{constructor(t,e,n=null,i=1e3){this.protocol=t;this.ctx=e;this.logger=n;this.timeoutDelay=i;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,Jl(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,Jl(t.type),t.data);return}}}send(t,e=void 0){let n=new Ql;return Zs(n,t),Zs(n,e),this.sendBuffer(n.buffer)}sendBuffer(t){try{return this.protocol.send(t),t.byteLength}catch{return 0}}onRawMessage(t){let e=new Xs(t),n=ro(e),i=ro(e),o=n[0];switch(o){case 100:return this.logger?.logIncoming(t.byteLength,n[1],1,`${no(o)}: ${n[2]}.${n[3]}`,i),this.onPromise({type:o,id:n[1],channelName:n[2],name:n[3],arg:i});case 102:return this.logger?.logIncoming(t.byteLength,n[1],1,`${no(o)}: ${n[2]}.${n[3]}`,i),this.onEventListen({type:o,id:n[1],channelName:n[2],name:n[3],arg:i});case 101:return this.logger?.logIncoming(t.byteLength,n[1],1,`${no(o)}`),this.disposeActiveRequest({type:o,id:n[1]});case 103:return this.logger?.logIncoming(t.byteLength,n[1],1,`${no(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 Xe,i;try{i=e.call(this.ctx,t.name,t.arg,n.token)}catch(a){i=Promise.reject(a)}let o=t.id;i.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=A(()=>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),gt(this.activeRequests.values()),this.activeRequests.clear()}};var io=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,i,o){return e.isDisposed?Promise.reject(new re):e.requestPromise(t,n,i,o)},listen(n,i){return e.isDisposed?Q.None:e.requestEvent(t,n,i)}}}requestPromise(t,e,n,i=ze.None){let o=this.lastRequestId++,a={id:o,type:100,channelName:t,name:e,arg:n};if(i.isCancellationRequested)return Promise.reject(new re);let l,c;return new Promise((d,f)=>{if(i.isCancellationRequested)return f(new re);let m=()=>{let S=_=>{switch(_.type){case 201:this.handlers.delete(o),d(_.data);break;case 202:{this.handlers.delete(o);let b=new Error(_.data.message);b.stack=Array.isArray(_.data.stack)?_.data.stack.join(`
`):_.data.stack,b.name=_.data.name,f(b);break}case 203:this.handlers.delete(o),f(_.data);break}};this.handlers.set(o,S),this.sendRequest(a)},h=null;this.state===1?m():(h=Yr(S=>this.whenInitialized()),h.then(()=>{h=null,m()}));let v=()=>{h?(h.cancel(),h=null):this.sendRequest({id:o,type:101}),f(new re)};l=i.onCancellationRequested(v),c={dispose:Lr(()=>{v(),l.dispose()})},this.activeRequests.add(c)}).finally(()=>{l?.dispose(),this.activeRequests.delete(c)})}requestEvent(t,e,n){let i=this.lastRequestId++,s={id:i,type:102,channelName:t,name:e,arg:n},a=null,l=new x({onWillAddFirstListener:()=>{let u=()=>{this.activeRequests.add(l),this.sendRequest(s)};this.state===1?u():(a=Yr(d=>this.whenInitialized()),a.then(()=>{a=null,u()}))},onDidRemoveLastListener:()=>{a?(a.cancel(),a=null):(this.activeRequests.delete(l),this.sendRequest({id:i,type:103})),this.handlers.delete(i)}}),c=u=>l.fire(u.data);return this.handlers.set(i,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,`${no(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,no(t.type));return}}}send(t,e=void 0){let n=new Ql;return Zs(n,t),Zs(n,e),this.sendBuffer(n.buffer)}sendBuffer(t){try{return this.protocol.send(t),t.byteLength}catch{return 0}}onBuffer(t){let e=new Xs(t),n=ro(e),i=ro(e),o=n[0];switch(o){case 200:return this.logger?.logIncoming(t.byteLength,0,0,Jl(o)),this.onResponse({type:n[0]});case 201:case 202:case 204:case 203:return this.logger?.logIncoming(t.byteLength,n[1],0,Jl(o),i),this.onResponse({type:n[0],id:n[1],data:i})}}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),gt(this.activeRequests.values()),this.activeRequests.clear(),this._onDidInitialize.dispose()}};w([ce],io.prototype,"onDidInitializePromise",1);var Yl=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 z;this.disposables.add(t(({protocol:i,onDidClientDisconnect:o})=>{let s=Q.once(i.onMessage),a=new z,l=s(c=>{let u=new Xs(c),d=ro(u),f=new ea(i,d,e,n),m=new io(i,e);this.channels.forEach((v,S)=>f.registerChannel(S,v));let h={channelServer:f,channelClient:m,ctx:d};this._connections.add(h),this._onDidAddConnection.fire(h),a.add(o(()=>{f.dispose(),m.dispose(),this._connections.delete(h),this._onDidRemoveConnection.fire(h),this.disposables.delete(a),a.dispose()}))});a.add(l),this.disposables.add(a)}))}get connections(){let t=[];return this._connections.forEach(e=>t.push(e)),t}getChannel(t,e){let n=this;return{call(i,o,s){let a;if(Fs(e)){let c=mh(n.connections.filter(e));a=c?Promise.resolve(c):Q.toPromise(Q.filter(n.onDidAddConnection,e))}else a=e.routeCall(n,i,o);let l=a.then(c=>c.channelClient.getChannel(t));return qy(l).call(i,o,s)},listen(i,o){if(Fs(e))return n.getMulticastEvent(t,e,i,o);let s=e.routeEvent(n,i,o).then(a=>a.channelClient.getChannel(t));return qy(s).listen(i,o)}}}getMulticastEvent(t,e,n,i){let o=this,s,a=new x({onWillAddFirstListener:()=>{s=new z;let l=new Ol,c=new Map,u=f=>{let h=f.channelClient.getChannel(t).listen(n,i),v=l.add(h);c.set(f,v)},d=f=>{let m=c.get(f);m&&(m.dispose(),c.delete(f))};o.connections.filter(e).forEach(u),Q.filter(o.onDidAddConnection,e)(u,void 0,s),o.onDidRemoveConnection(d,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 qy(r){return{call(t,e,n){return r.then(i=>i.call(t,e,n))},listen(t,e){let n=new Hs;return r.then(i=>n.input=i.listen(t,e)),n.event}}}function Ky(r){let t=!1;return{call(e,n,i){return t?r.call(e,n,i):Xn(0).then(()=>t=!0).then(()=>r.call(e,n,i))},listen(e,n){if(t)return r.listen(e,n);let i=new Hs;return Xn(0).then(()=>t=!0).then(()=>i.input=r.listen(e,n)),i.event}}}var oo;(i=>{function r(o,s,a){let l=o,c=a?.disableMarshalling,u=new Map;for(let d in l)e(d)&&u.set(d,Q.buffer(l[d],d,!0,void 0,s));return new class{listen(d,f,m){let h=u.get(f);if(h)return h;let v=l[f];if(typeof v=="function"){if(n(f))return v.call(l,m);if(e(f))return u.set(f,Q.buffer(l[f],f,!0,void 0,s)),u.get(f)}throw new mn(`Event not found: ${f}`)}call(d,f,m){let h=l[f];if(typeof h=="function"){if(!c&&Array.isArray(m))for(let S=0;S<m.length;S++)m[S]=Ys(m[S]);let v=h.apply(l,m);return v instanceof Promise||(v=Promise.resolve(v)),v}throw new mn(`Method not found: ${f}`)}}}i.fromService=r;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(u){return o.listen(c,u)}:e(c)?o.listen(c):async function(...u){let d;s&&!sn(s.context)?d=[s.context,...u]:d=u;let f=await o.call(c,d);return a?f:Ys(f)};throw new mn(`Property not found: ${String(c)}`)}})}i.toService=t;function e(o){return o[0]==="o"&&o[1]==="n"&&Bp(o.charCodeAt(2))}function n(o){return/^onDynamic/.test(o)&&Bp(o.charCodeAt(9))}})(oo||={});import{fork as jT}from"child_process";function jy(r){let t=r;return t&&typeof t.type=="string"&&typeof t.severity=="string"}function ST(r){let t=[],e;try{let n=JSON.parse(r.arguments),i=n[n.length-1];i&&i.__$stack&&(n.pop(),e=i.__$stack),t.push(...n)}catch{t.push("Unable to log remote console arguments",r.arguments)}return{args:t,stack:e}}function IT(r){if(!r)return r;let t=r.indexOf(`
`);return t===-1?r:r.substring(0,t)}function Gy(r,t){let{args:e,stack:n}=ST(r),i=typeof e[0]=="string"&&e.length===1,o=IT(n);o&&(o=`(${o.trim()})`);let s=[];if(typeof e[0]=="string"?o&&i?s=[`%c[${t}] %c${e[0]} %c${o}`,so("blue"),so(""),so("grey")]:s=[`%c[${t}] %c${e[0]}`,so("blue"),so(""),...e.slice(1)]:s=[`%c[${t}]%`,so("blue"),...e],o&&!i&&s.push(o),typeof console[r.severity]!="function")throw new Error("Unknown console method");console[r.severity].apply(console,s)}function so(r){return`color: ${r}`}function Xt(r){if(!r||typeof r!="object"||r instanceof RegExp)return r;let t=Array.isArray(r)?[]:{};return Object.entries(r).forEach(([e,n])=>{t[e]=n&&typeof n=="object"?Xt(n):n}),t}function Jy(r){if(!r||typeof r!="object")return r;let t=[r];for(;t.length>0;){let e=t.shift();Object.freeze(e);for(let n in e)if(Qy.call(e,n)){let i=e[n];typeof i=="object"&&!Object.isFrozen(i)&&!wh(i)&&t.push(i)}}return r}var Qy=Object.prototype.hasOwnProperty;function ta(r,t){return df(r,t,new Set)}function df(r,t,e){if(sn(r))return r;let n=t(r);if(typeof n<"u")return n;if(Array.isArray(r)){let i=[];for(let o of r)i.push(df(o,t,e));return i}if(Oe(r)){if(e.has(r))throw new Error("Cannot clone recursive data-structure");e.add(r);let i={};for(let o in r)Qy.call(r,o)&&(i[o]=df(r[o],t,e));return e.delete(r),i}return r}function ao(r,t,e=!0){return Oe(r)?(Oe(t)&&Object.keys(t).forEach(n=>{n in r?e&&(Oe(r[n])&&Oe(t[n])?ao(r[n],t[n],e):r[n]=t[n]):r[n]=t[n]}),r):t}function Me(r,t){if(r===t)return!0;if(r==null||t===null||t===void 0||typeof r!=typeof t||typeof r!="object"||Array.isArray(r)!==Array.isArray(t))return!1;let e,n;if(Array.isArray(r)){if(r.length!==t.length)return!1;for(e=0;e<r.length;e++)if(!Me(r[e],t[e]))return!1}else{let i=[];for(n in r)i.push(n);i.sort();let o=[];for(n in t)o.push(n);if(o.sort(),!Me(i,o))return!1;for(e=0;e<i.length;e++)if(!Me(r[i[e]],t[i[e]]))return!1}return!0}function uf(r){let t=new Set;return JSON.stringify(r,(e,n)=>{if(Oe(n)||Array.isArray(n)){if(t.has(n))return"[Circular]";t.add(n)}return typeof n=="bigint"?`[BigInt ${n.toString()}]`:n})}function ei(r,t){let e=t.toLowerCase(),n=Object.keys(r).find(i=>i.toLowerCase()===e);return n?r[n]:r[t]}import*as zT from"child_process";import{promises as av}from"fs";function Yy(r){r&&(delete r.DEBUG,delete r.NODE_OPTIONS,ve&&delete r.LD_PRELOAD)}import*as Y from"fs";import{tmpdir as ET}from"os";import{promisify as ia}from"util";var CT=new hn(1e4);function na(r){return Xy(r,"NFC",CT)}var TT=new hn(1e4);function xT(r){return Xy(r,"NFD",TT)}var wT=/[^\u0000-\u0080]/;function Xy(r,t,e){if(!r)return r;let n=e.get(r);if(n)return n;let i;return wT.test(r)?i=r.normalize(t):i=r,e.set(r,i),i}var RT=(function(){let r=new hn(1e4),t=/[\u0300-\u036f]/g;return function(e){let n=r.get(e);if(n)return n;let i=xT(e).replace(t,""),o=(i.length===e.length?i:e).toLowerCase();return r.set(e,o),o}})();async function tv(r,t=0,e){if(Kp(r))throw new Error("rimraf - will refuse to recursively delete root");return t===0?pf(r):PT(r,e)}async function PT(r,t=vy(ET())){try{try{await Y.promises.rename(r,t)}catch(e){return e.code==="ENOENT"?void 0:pf(r)}pf(t).catch(()=>{})}catch(e){if(e.code!=="ENOENT")throw e}}async function pf(r){return Y.promises.rm(r,{recursive:!0,force:!0,maxRetries:3})}async function Xl(r,t){try{return await Zy(r,t)}catch(e){if(e.code==="ENOENT"&&K&&Kp(r))try{return await Zy(`${r}.`,t)}catch{}throw e}}async function Zy(r,t){return AT(await(t?kT(r):Y.promises.readdir(r)))}async function kT(r){try{return await Y.promises.readdir(r,{withFileTypes:!0})}catch(n){n.code!=="ENOENT"&&console.warn("[node.js fs] readdir with filetypes failed with error: ",n)}let t=[],e=await Xl(r);for(let n of e){let i=!1,o=!1,s=!1;try{let a=await Y.promises.lstat(B(r,n));i=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:()=>i,isDirectory:()=>o,isSymbolicLink:()=>s})}return t}function AT(r){return r.map(t=>typeof t=="string"?Ye?na(t):t:(t.name=Ye?na(t.name):t.name,t))}async function DT(r){let t=await Xl(r),e=[];for(let n of t)await _t.existsDirectory(B(r,n))&&e.push(n);return e}var _t;(n=>{async function r(i){let o;try{if(o=await Y.promises.lstat(i),!o.isSymbolicLink())return{stat:o}}catch{}try{return{stat:await Y.promises.stat(i),symbolicLink:o?.isSymbolicLink()?{dangling:!1}:void 0}}catch(s){if(s.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};if(K&&s.code==="EACCES")try{return{stat:await Y.promises.stat(await Y.promises.readlink(i)),symbolicLink:{dangling:!1}}}catch(a){if(a.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};throw a}throw s}}n.stat=r;async function t(i){try{let{stat:o,symbolicLink:s}=await n.stat(i);return o.isFile()&&s?.dangling!==!0}catch{}return!1}n.existsFile=t;async function e(i){try{let{stat:o,symbolicLink:s}=await n.stat(i);return o.isDirectory()&&s?.dangling!==!0}catch{}return!1}n.existsDirectory=e})(_t||={});var OT=new Jr;function LT(r,t,e){return OT.queueFor(y.file(r),()=>{let n=UT(e);return new Promise((i,o)=>NT(r,t,n,s=>s?o(s):i()))},Ve)}var nv=!0;function MT(r){nv=r}function NT(r,t,e,n){if(!nv)return Y.writeFile(r,t,{mode:e.mode,flag:e.flag},n);Y.open(r,e.flag,e.mode,(i,o)=>{if(i)return n(i);Y.writeFile(o,t,s=>{if(s)return Y.close(o,()=>n(s));Y.fdatasync(o,a=>(a&&(console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ",a),MT(!1)),Y.close(o,l=>n(l))))})})}function UT(r){return r?{mode:typeof r.mode=="number"?r.mode:438,flag:typeof r.flag=="string"?r.flag:"w"}:{mode:438,flag:"w"}}async function FT(r,t,e=6e4){if(r!==t)try{K&&typeof e=="number"?await iv(r,t,Date.now(),e):await Y.promises.rename(r,t)}catch(n){if(r.toLowerCase()!==t.toLowerCase()&&n.code==="EXDEV"||r.endsWith("."))await rv(r,t,{preserveSymlinks:!1}),await tv(r,1);else throw n}}async function iv(r,t,e,n,i=0){try{return await Y.promises.rename(r,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 ${i} retries with error: ${o}`),o;if(i===0){let s=!1;try{let{stat:a}=await _t.stat(t);a.isFile()||(s=!0)}catch{}if(s)throw o}return await Xn(Math.min(100,i*10)),iv(r,t,e,n,i+1)}}async function rv(r,t,e){return ov(r,t,{root:{source:r,target:t},options:e,handledSourcePaths:new Set})}var ev=511;async function ov(r,t,e){if(e.handledSourcePaths.has(r))return;e.handledSourcePaths.add(r);let{stat:n,symbolicLink:i}=await _t.stat(r);if(i){if(e.options.preserveSymlinks)try{return await VT(r,t,e)}catch{}if(i.dangling)return}return n.isDirectory()?WT(r,t,n.mode&ev,e):$T(r,t,n.mode&ev)}async function WT(r,t,e,n){await Y.promises.mkdir(t,{recursive:!0,mode:e});let i=await Xl(r);for(let o of i)await ov(B(r,o),B(t,o),n)}async function $T(r,t,e){await Y.promises.copyFile(r,t),await Y.promises.chmod(t,e)}async function VT(r,t,e){let n=await Y.promises.readlink(r);Qn(n,e.root.source,!ve)&&(n=B(e.root.target,n.substr(e.root.source.length+1))),await Y.promises.symlink(n,t)}async function BT(r){try{return await ia(Y.realpath)(r)}catch{let t=HT(r);return await Y.promises.access(t,Y.constants.R_OK),t}}function HT(r){return Kr(Qt(r),Ce)}var xe=new class{get read(){return(r,t,e,n,i)=>new Promise((o,s)=>{Y.read(r,t,e,n,i,(a,l,c)=>a?s(a):o({bytesRead:l,buffer:c}))})}get write(){return(r,t,e,n,i)=>new Promise((o,s)=>{Y.write(r,t,e,n,i,(a,l,c)=>a?s(a):o({bytesWritten:l,buffer:c}))})}get fdatasync(){return ia(Y.fdatasync)}get open(){return ia(Y.open)}get close(){return ia(Y.close)}get ftruncate(){return ia(Y.ftruncate)}async exists(r){try{return await Y.promises.access(r),!0}catch{return!1}}get readdir(){return Xl}get readDirsInDir(){return DT}get writeFile(){return LT}get rm(){return tv}get rename(){return FT}get copy(){return rv}get realpath(){return BT}};function lv(r=ke){return r.comspec||"cmd.exe"}function cv(r){let t=[],e=!1,n=function(i){if(e){t.push(i);return}(!r.send(i,s=>{if(s&&console.error(s),e=!1,t.length>0){let a=t.slice(0);t=[],a.forEach(l=>n(l))}})||K)&&(e=!0)};return{send:n}}async function qT(r){if(await xe.exists(r)){let t;try{t=await av.stat(r)}catch(e){e.message.startsWith("EACCES")&&(t=await av.lstat(r))}return t?!t.isDirectory():!1}return!1}async function Zl(r,t,e,n=ke,i=qT){if(Yt(r))return await i(r)?r:void 0;if(t===void 0&&(t=nr()),de(r)!=="."){let l=B(t,r);return await i(l)?l:void 0}let s=ei(n,"PATH");if(e===void 0&&Pe(s)&&(e=s.split(qr)),e===void 0||e.length===0){let l=B(t,r);return await i(l)?l:void 0}for(let l of e){let c;if(Yt(l)?c=B(l,r):c=B(t,l,r),K){let d=(ei(n,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").map(async f=>{let m=c+f;return await i(m)?m:void 0});for(let f of d){let m=await f;if(m)return m}}if(await i(c))return c}let a=B(t,r);return await i(a)?a:void 0}var ec=class extends ea{constructor(t){super({send:e=>{try{process.send?.(e.buffer.toString("base64"))}catch{}},onMessage:Q.fromNodeEventEmitter(process,"message",e=>k.wrap(Buffer.from(e,"base64")))},t),process.once("disconnect",()=>this.dispose())}},tc=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 ar(n),this.child=null,this._client=null}getChannel(t){let e=this;return{call(n,i,o){return e.requestPromise(t,n,i,o)},listen(n,i){return e.requestEvent(t,n,i)}}}requestPromise(t,e,n,i=ze.None){if(!this.disposeDelayer)return Promise.reject(new Error("disposed"));if(i.isCancellationRequested)return Promise.reject(vl());this.disposeDelayer.cancel();let o=this.getCachedChannel(t),s=Yr(c=>o.call(e,n,c)),a=i.onCancellationRequested(()=>s.cancel()),l=A(()=>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 i,o=new x({onWillAddFirstListener:()=>{i=this.getCachedChannel(t).listen(e,n)(o.fire,o),this.activeRequests.add(i)},onDidRemoveLastListener:()=>{this.activeRequests.delete(i),i.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={...Xt(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(d=>!/^--inspect(-brk)?=/.test(d)).filter(d=>!d.startsWith("--vscode-"))),Yy(e.env),this.child=jT(this.modulePath,t,e);let n=new x,o=Q.fromNodeEventEmitter(this.child,"message",d=>d)(d=>{if(jy(d)){Gy(d,`IPC Library: ${this.options.serverName}`);return}n.fire(k.wrap(Buffer.from(d,"base64")))}),s=this.options.useQueue?cv(this.child):this.child,a=d=>this.child?.connected&&s.send(d.buffer.toString("base64")),l=n.event,c={send:a,onMessage:l};this._client=new io(c);let u=()=>this.disposeClient();process.once("exit",u),this.child.on("error",d=>console.warn('IPC "'+this.options.serverName+'" errored with '+d)),this.child.on("exit",(d,f)=>{process.removeListener("exit",u),o.dispose(),this.activeRequests.forEach(m=>gt(m)),this.activeRequests.clear(),d!==0&&f!=="SIGTERM"&&console.warn('IPC "'+this.options.serverName+'" crashed with exit code '+d+" and signal "+f),this.disposeDelayer?.cancel(),this.disposeClient(),this._onDidProcessExit.fire({code:d,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 nc(r){return!!r.parentPort}var ff=class{constructor(t){this.port=t;this.onMessage=Q.fromNodeEventEmitter(this.port,"message",e=>e.data?k.wrap(e.data):k.alloc(0)),t.start()}send(t){this.port.postMessage(t.buffer)}disconnect(){this.port.close()}},ra=class r extends Yl{static getOnDidClientConnect(t){Eh(nc(process),"Electron Utility Process");let e=new x;return process.parentPort.on("message",n=>{if(t?.handledClientConnection(n))return;let i=n.ports.at(0);i&&e.fire(i)}),Q.map(e.event,n=>({protocol:new ff(n),onDidClientDisconnect:Q.fromNodeEventEmitter(n,"close")}))}constructor(t){super(r.getOnDidClientConnect(t))}};var q=(function(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let r=new Uint8Array(16),t=[];for(let e=0;e<256;e++)t.push(e.toString(16).padStart(2,"0"));return function(){crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128;let n=0,i="";return i+=t[r[n++]],i+=t[r[n++]],i+=t[r[n++]],i+=t[r[n++]],i+="-",i+=t[r[n++]],i+=t[r[n++]],i+="-",i+=t[r[n++]],i+=t[r[n++]],i+="-",i+=t[r[n++]],i+=t[r[n++]],i+="-",i+=t[r[n++]],i+=t[r[n++]],i+=t[r[n++]],i+=t[r[n++]],i+=t[r[n++]],i+=t[r[n++]],i}})();import*as hl from"os";import*as ml from"inspector";var dn;(i=>{i.serviceIds=new Map,i.DI_TARGET="$di$target",i.DI_DEPENDENCIES="$di$dependencies";function n(o){return o[i.DI_DEPENDENCIES]||[]}i.getServiceDependencies=n})(dn||={});var qe=V("instantiationService");function JT(r,t,e){t[dn.DI_TARGET]===t?t[dn.DI_DEPENDENCIES].push({id:r,index:e}):(t[dn.DI_DEPENDENCIES]=[{id:r,index:e}],t[dn.DI_TARGET]=t)}function V(r){if(dn.serviceIds.has(r))return dn.serviceIds.get(r);let t=function(e,n,i){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");JT(t,e,i)};return t.toString=()=>r,dn.serviceIds.set(r,t),t}var oa="VSCODE_AGENT_HOST_CLAUDE_SDK_PATH";var dv="agent-host/otel/agent-host-traces.db",g4=Object.freeze({Enabled:"COPILOT_OTEL_ENABLED",ExporterType:"COPILOT_OTEL_EXPORTER_TYPE",OtlpEndpoint:"OTEL_EXPORTER_OTLP_ENDPOINT",OtlpEndpointAlt:"COPILOT_OTEL_ENDPOINT",OtlpProtocol:"OTEL_EXPORTER_OTLP_PROTOCOL",OtlpHeaders:"OTEL_EXPORTER_OTLP_HEADERS",CaptureContent:"OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",FilePath:"COPILOT_OTEL_FILE_EXPORTER_PATH",SourceName:"COPILOT_OTEL_SOURCE_NAME",DbSpanExporterEnabled:"COPILOT_OTEL_DB_SPAN_EXPORTER_ENABLED"});var lo={resource:"https://api.github.com",resource_name:"GitHub Copilot",authorization_servers:["https://github.com/login/oauth"],scopes_supported:["read:user","user:email"],required:!0},H;(n=>{function r(i,o){return y.from({scheme:i,path:`/${o}`})}n.uri=r;function t(i){return(typeof i=="string"?y.parse(i):i).path.substring(1)}n.id=t;function e(i){return(typeof i=="string"?y.parse(i):i).scheme||void 0}n.provider=e})(H||={});var m4=V("agentService"),h4=V("agentHostService");function gf(r,t){return t&&(r.stack||r.stacktrace)?g(116,null,pv(r),uv(r.stack)||uv(r.stacktrace)):pv(r)}function uv(r){return Array.isArray(r)?r.join(`
`):r}function pv(r){return r.code==="ERR_UNC_HOST_NOT_ALLOWED"?`${r.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`:typeof r.code=="string"&&typeof r.errno=="number"&&typeof r.syscall=="string"?g(115,null,r.message):r.message||g(113,null)}function Ct(r=null,t=!1){if(!r)return g(113,null);if(Array.isArray(r)){let e=Or(r),n=Ct(e[0],t);return e.length>1?g(114,null,n,e.length):n}if(Pe(r))return r;if(r.detail){let e=r.detail;if(e.error)return gf(e.error,t);if(e.exception)return gf(e.exception,t)}return r.stack?gf(r,t):r.message?r.message:g(113,null)}var S4=Object.freeze({text:"text/plain",binary:"application/octet-stream",unknown:"application/unknown",markdown:"text/markdown",latex:"text/latex",uriList:"text/uri-list",html:"text/html"});var mf={".aac":"audio/x-aac",".avi":"video/x-msvideo",".bmp":"image/bmp",".flv":"video/x-flv",".gif":"image/gif",".ico":"image/x-icon",".jpe":["image/jpg","image/jpeg"],".jpeg":["image/jpg","image/jpeg"],".jpg":["image/jpg","image/jpeg"],".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".mid":"audio/midi",".midi":"audio/midi",".mk3d":"video/x-matroska",".mks":"video/x-matroska",".mkv":"video/x-matroska",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4v":"video/mp4",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".oga":"audio/ogg",".ogg":"audio/ogg",".opus":"audio/opus",".ogv":"video/ogg",".png":"image/png",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".spx":"audio/ogg",".svg":"image/svg+xml",".tga":"image/x-tga",".tif":"image/tiff",".tiff":"image/tiff",".wav":"audio/x-wav",".webm":"video/webm",".webp":"image/webp",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".woff":"application/font-woff"};function ic(r){let t=Nl(r),e=mf[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function fv(r){for(let t in mf){let e=mf[t];if(Array.isArray(e)?e.includes(r):e===r)return t}}var ot=class{constructor(t,e,n){this.owner=t;this.debugNameSource=e;this.referenceFn=n}getDebugName(t){return yv(t,this)}},gv=new Map,hf=new WeakMap;function yv(r,t){let e=hf.get(r);if(e)return e;let n=QT(r,t);if(n){let i=gv.get(n)??0;i++,gv.set(n,i);let o=i===1?n:`${n}#${i}`;return hf.set(r,o),o}}function QT(r,t){let e=hf.get(r);if(e)return e;let n=t.owner?XT(t.owner)+".":"",i,o=t.debugNameSource;if(o!==void 0)if(typeof o=="function"){if(i=o(),i!==void 0)return n+i}else return n+o;let s=t.referenceFn;if(s!==void 0&&(i=sa(s),i!==void 0))return n+i;if(t.owner!==void 0){let a=YT(t.owner,r);if(a!==void 0)return n+a}}function YT(r,t){for(let e in r)if(r[e]===t)return e}var mv=new Map,hv=new WeakMap;function XT(r){let t=hv.get(r);if(t)return t;let e=yf(r)??"Object",n=mv.get(e)??0;n++,mv.set(e,n);let i=n===1?e:`${e}#${n}`;return hv.set(r,i),i}function yf(r){let t=r.constructor;if(t)return t.name==="Object"?void 0:t.name}function sa(r){let t=r.toString(),n=/\/\*\*\s*@description\s*([^*]*)\*\//.exec(t);return(n?n[1]:void 0)?.trim()}function At(r,t){return r===t}function ZT(){return(r,t)=>r===t}function ex(r,t,e){return Vt(r,t,e??At)}function tx(r){return(t,e)=>Vt(t,e,r??At)}function rc(r,t){if(r===t)return!0;if(Array.isArray(r)&&Array.isArray(t)){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(!rc(r[e],t[e]))return!1;return!0}if(r&&typeof r=="object"&&t&&typeof t=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let e=r,n=t,i=Object.keys(e),o=Object.keys(n),s=new Set(o);if(i.length!==o.length)return!1;for(let a of i)if(!s.has(a)||!rc(e[a],n[a]))return!1;return!0}return!1}function nx(){return(r,t)=>rc(r,t)}function ix(r,t){return JSON.stringify(r)===JSON.stringify(t)}function rx(){return(r,t)=>JSON.stringify(r)===JSON.stringify(t)}function ox(){return(r,t)=>r.equals(t)}function sx(r,t,e){return r==null||t===void 0||t===null?t===r:e(r,t)}function ax(r){return(t,e)=>t==null||e===void 0||e===null?e===t:r(t,e)}var lx;(d=>(d.strict=At,d.strictC=ZT,d.array=ex,d.arrayC=tx,d.structural=rc,d.structuralC=nx,d.jsonStringify=ix,d.jsonStringifyC=rx,d.thisC=ox,d.ifDefined=sx,d.ifDefinedC=ax))(lx||={});function vf(r){let t=new Error("BugIndicatingErrorRecovery: "+r);Ue(t),console.error("recovered from an error that indicates a bug",t)}var ur;function aa(r){ur?ur instanceof oc?ur.loggers.push(r):ur=new oc([ur,r]):ur=r}function be(){return ur}var bf;function vv(r){bf=r}function bv(r){bf&&bf(r)}var oc=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 i of this.loggers)i.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 i of this.loggers)i.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 pr(r,t){let e=new ki(r,t);try{r(e)}finally{e.finish()}}function Sf(r,t,e){r?t(r):pr(t,e)}var ki=class{constructor(t,e){this._fn=t;this._getDebugName=e;this._updatingObservers=[];be()?.handleBeginTransaction(this)}getDebugName(){return this._getDebugName?this._getDebugName():sa(this._fn)}updateObserver(t,e){if(!this._updatingObservers){vf("Transaction already finished!"),pr(n=>{n.updateObserver(t,e)});return}this._updatingObservers.push({observer:t,observable:e}),t.beginUpdate(e)}finish(){let t=this._updatingObservers;if(!t){vf("transaction.finish() has already been called!");return}for(let e=0;e<t.length;e++){let{observer:n,observable:i}=t[e];n.endUpdate(i)}this._updatingObservers=null,be()?.handleEndTransaction(this)}debugGetUpdatingObservers(){return this._updatingObservers}};var Ke;(n=>{let r=!1;function t(){r=!0}n.enable=t;function e(){if(!r)return;let i=Error,o=i.stackTraceLimit;i.stackTraceLimit=3;let s=new Error().stack;return i.stackTraceLimit=o,If.fromStack(s,2)}n.ofCaller=e})(Ke||={});var If=class r{constructor(t,e,n,i){this.fileName=t;this.line=e;this.column=n;this.id=i}static fromStack(t,e){let n=t.split(`
`),i=cx(n[e+1]);if(i)return new r(i.fileName,i.line,i.column,i.id)}};function cx(r){let t=r.match(/\((.*):(\d+):(\d+)\)/);if(t)return{fileName:t[1],line:parseInt(t[2]),column:parseInt(t[3]),id:r};let e=r.match(/at ([^\(\)]*):(\d+):(\d+)/);if(e)return{fileName:e[1],line:parseInt(e[2]),column:parseInt(e[3]),id:r}}var _f;function Sv(r){_f=r}var Iv;function _v(r){Iv=r}var Cv;function Tv(r){Cv=r}var Cf;function xv(r){Cf=r}var sc=class{get TChange(){return null}reportChanges(){this.get()}read(t){return t?t.readObservable(this):this.get()}map(t,e,n=Ke.ofCaller()){let i=e===void 0?void 0:t,o=e===void 0?t:e;return _f({owner:i,debugName:()=>{let s=sa(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(!i)return`${this.debugName} (mapped)`},debugReferenceFn:o},s=>o(this.read(s),s),n)}flatten(){return _f({owner:void 0,debugName:()=>`${this.debugName} (flattened)`},t=>this.read(t).read(t))}recomputeInitiallyAndOnChange(t,e){return t.add(Iv(this,e)),this}keepObserved(t){return t.add(Cv(this)),this}get debugValue(){return this.get()}get debug(){return new Tf(this)}},Tf=class{constructor(t){this.observable=t}getDependencyGraph(){return Cf(this.observable,{type:"dependencies"})}getObserverGraph(){return Cf(this.observable,{type:"observers"})}},Zt=class extends sc{constructor(e){super();this._observers=new Set;be()?.handleObservableCreated(this,e)}addObserver(e){let n=this._observers.size;this._observers.add(e),n===0&&this.onFirstObserverAdded(),n!==this._observers.size&&be()?.handleOnListenerCountChanged(this,this._observers.size)}removeObserver(e){let n=this._observers.delete(e);n&&this._observers.size===0&&this.onLastObserverRemoved(),n&&be()?.handleOnListenerCountChanged(this,this._observers.size)}onFirstObserverAdded(){}onLastObserverRemoved(){}log(){let e=!!be();return bv(this),e||be()?.handleObservableCreated(this,Ke.ofCaller()),this}debugGetObservers(){return this._observers}};function In(r,t,e=Ke.ofCaller()){let n;return typeof r=="string"?n=new ot(void 0,r,void 0):n=new ot(r,void 0,void 0),new Sn(n,t,At,e)}var Sn=class extends Zt{constructor(e,n,i,o){super(o);this._debugNameData=e;this._equalityComparator=i;this._value=n,be()?.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,i){if(i===void 0&&this._equalityComparator(this._value,e))return;let o;n||(n=o=new ki(()=>{},()=>`Setting ${this.debugName}`));try{let s=this._value;this._setValue(e),be()?.handleObservableUpdated(this,{oldValue:s,newValue:e,change:i,didChange:!0,hadValue:!0});for(let a of this._observers)n.updateObserver(a,this),a.handleChange(this,i)}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}};var ac=class extends Zt{constructor(e,n,i,o){super(o);this._debugNameData=e;this._equalityComparator=i;this._isUpToDate=!0;this._deltas=[];this._updateCounter=0;this._value=n}get debugName(){return this._debugNameData.getDebugName(this)??"LazyObservableValue"}get(){return this._update(),this._value}_update(){if(!this._isUpToDate)if(this._isUpToDate=!0,this._deltas.length>0){for(let e of this._deltas){be()?.handleObservableUpdated(this,{change:e,didChange:!0,oldValue:"(unknown)",newValue:this._value,hadValue:!0});for(let n of this._observers)n.handleChange(this,e)}this._deltas.length=0}else{be()?.handleObservableUpdated(this,{change:void 0,didChange:!0,oldValue:"(unknown)",newValue:this._value,hadValue:!0});for(let e of this._observers)e.handleChange(this,void 0)}}_beginUpdate(){if(this._updateCounter++,this._updateCounter===1)for(let e of this._observers)e.beginUpdate(this)}_endUpdate(){if(this._updateCounter--,this._updateCounter===0){this._update();let e=[...this._observers];for(let n of e)n.endUpdate(this)}}addObserver(e){let n=!this._observers.has(e)&&this._updateCounter>0;super.addObserver(e),n&&e.beginUpdate(this)}removeObserver(e){let n=this._observers.has(e)&&this._updateCounter>0;super.removeObserver(e),n&&e.endUpdate(this)}set(e,n,i){if(i===void 0&&this._equalityComparator(this._value,e))return;let o;n||(n=o=new ki(()=>{},()=>`Setting ${this.debugName}`));try{if(this._isUpToDate=!1,this._setValue(e),i!==void 0&&this._deltas.push(i),n.updateObserver({beginUpdate:()=>this._beginUpdate(),endUpdate:()=>this._endUpdate(),handleChange:(s,a)=>{},handlePossibleChange:s=>{}},this),this._updateCounter>1)for(let s of this._observers)s.handlePossibleChange(this)}finally{o&&o.finish()}}toString(){return`${this.debugName}: ${this._value}`}_setValue(e){this._value=e}};function fr(r,t,e=Ke.ofCaller()){return r.lazy?new ac(new ot(r.owner,r.debugName,void 0),t,r.equalsFn??At,e):new Sn(new ot(r.owner,r.debugName,void 0),t,r.equalsFn??At,e)}function dx(r){switch(r){case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var ti=class{constructor(t,e,n,i){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),be()?.handleAutorunCreated(this,i),this._run(),vi(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(),be()?.handleAutorunDisposed(this),bi(this)}}_run(){let t=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=t,this._state=3;try{if(!this._disposed){be()?.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(i){hi(i)}finally{this._isRunning=!1,n!==void 0&&n.dispose()}}}finally{this._disposed||be()?.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--}Ns(()=>this._updateCount>=0)}handlePossibleChange(t){this._state===3&&this._isDependency(t)&&(this._checkIterations(),this._state=1)}handleChange(t,e){if(this._isDependency(t)){be()?.handleAutorunDependencyChanged(this,t,e);try{(!this._changeTracker||this._changeTracker.handleChange({changedObservable:t,change:e,didChange:i=>i===t},this._changeSummary))&&(this._checkIterations(),this._state=2)}catch(n){hi(n)}}}_isDependency(t){return this._dependencies.has(t)&&!this._dependenciesToBeRemoved.has(t)}_ensureNoRunning(){if(!this._isRunning)throw new we("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 we("Cannot access store after dispose");return this._store===void 0&&(this._store=new z),this._store}get delayedStore(){if(this._ensureNoRunning(),this._disposed)throw new we("Cannot access store after dispose");return this._delayedStore===void 0&&(this._delayedStore=new z),this._delayedStore}debugGetState(){return{isRunning:this._isRunning,updateCount:this._updateCount,dependencies:this._dependencies,state:this._state,stateStr:dx(this._state)}}debugRerun(){this._isRunning?this._state=2:this._run()}_checkIterations(){return this._iteration>100?(hi(new we(`Autorun '${this.debugName}' is stuck in an infinite update loop.`)),!0):!1}};function _n(r,t=Ke.ofCaller()){return new ti(new ot(void 0,void 0,r),r,void 0,t)}function ux(r){switch(r){case 0:return"initial";case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var st=class extends Zt{constructor(e,n,i,o=void 0,s,a){super(a);this._debugNameData=e;this._computeFn=n;this._changeTracker=i;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,be()?.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 i;this._changeTracker&&(i=this._changeTracker.createChangeSummary(void 0),this._changeTracker.beforeUpdate?.(this,i)),n=this._computeFn(this,i)}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 i=this._changeSummary;this._isReaderValid=!0,this._changeTracker&&(this._isInBeforeUpdate=!0,this._changeTracker.beforeUpdate?.(this,i),this._isInBeforeUpdate=!1,this._changeSummary=this._changeTracker?.createChangeSummary(i));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,i)}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),be()?.handleObservableUpdated(this,{oldValue:s,newValue:this._value,change:void 0,didChange:e,hadValue:o})}catch(i){hi(i)}if(this._isComputing=!1,!this._didReportChange&&e)for(let i of this._observers)i.handleChange(this,void 0);else this._didReportChange=!1}toString(){return`LazyDerived<${this.debugName}>`}beginUpdate(e){if(this._isUpdating)throw new we("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 i of this._observers)i.handlePossibleChange(this);if(n)for(let i of this._observers)i.beginUpdate(this)}finally{this._isUpdating=!1}}endUpdate(e){if(this._updateCount--,this._updateCount===0){let n=[...this._observers];for(let i of n)i.endUpdate(this);if(this._removedObserverToCallEndUpdateOn){let i=[...this._removedObserverToCallEndUpdateOn];this._removedObserverToCallEndUpdateOn=null;for(let o of i)o.endUpdate(this)}}Ns(()=>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){be()?.handleDerivedDependencyChanged(this,e,n);let i=!1;try{i=this._changeTracker?this._changeTracker.handleChange({changedObservable:e,change:n,didChange:s=>s===e},this._changeSummary):!0}catch(s){hi(s)}let o=this._state===3;if(i&&(this._state===1||o)&&(this._state=2,o))for(let s of this._observers)s.handlePossibleChange(this)}}_ensureReaderValid(){if(!this._isReaderValid)throw new we("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 z),this._store}get delayedStore(){return this._ensureReaderValid(),this._delayedStore===void 0&&(this._delayedStore=new z),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:ux(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,i){this._value=e;let o=this._observers;n.updateObserver(this,this);for(let s of o)s.handleChange(this,i)}};function la(r,t,e=Ke.ofCaller()){return new st(new ot(r.owner,r.debugName,r.debugReferenceFn),t,void 0,r.onLastObserverRemoved,r.equalsFn??At,e)}Sv(la);function co(...r){let t,e,n,i;return r.length===2?[e,n]=r:[t,e,n,i]=r,new en(new ot(t,void 0,n),e,n,()=>en.globalTransaction,At,i??Ke.ofCaller())}var en=class extends Zt{constructor(e,n,i,o,s,a){super(a);this._debugNameData=e;this.event=n;this._getValue=i;this._getTransaction=o;this._equalityComparator=s;this._hasValue=!1;this.handleEvent=e=>{let n=this._getValue(e),i=this._value,o=!this._hasValue||!this._equalityComparator(i,n),s=!1;o&&(this._value=n,this._hasValue&&(s=!0,Sf(this._getTransaction(),a=>{be()?.handleObservableUpdated(this,{oldValue:i,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||be()?.handleObservableUpdated(this,{oldValue:i,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=en;function t(n,i){let o=!1;en.globalTransaction===void 0&&(en.globalTransaction=n,o=!0);try{i()}finally{o&&(en.globalTransaction=void 0)}}e.batchEventsGlobally=t})(co||={});function Rv(r){let t=new lc(!1,void 0);return r.addObserver(t),A(()=>{r.removeObserver(t)})}Tv(Rv);function Ev(r,t){let e=new lc(!0,t);r.addObserver(e);try{e.beginUpdate(r)}finally{e.endUpdate(r)}return A(()=>{r.removeObserver(e)})}_v(Ev);var lc=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 cc;function Pv(r){cc||(cc=new ca,aa(cc)),cc.addFilteredObj(r)}var ca=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 yx([uo(Sx("|  ",this.indentation)),t])}formatInfo(t){return t.hadValue?t.didChange?[uo(" "),tn(zt(t.oldValue,70),{color:"red",strikeThrough:!0}),uo(" "),tn(zt(t.newValue,60),{color:"green"})]:[uo(" (unchanged)")]:[uo(" "),tn(zt(t.newValue,60),{color:"green"}),uo(" (initial)")]}handleObservableCreated(t){if(t instanceof st){let e=t;if(this.changedObservablesSets.set(e,new Set),!1){let i=[];e.__debugUpdating=i;let o=e.beginUpdate;e.beginUpdate=a=>(i.push(a),o.apply(e,[a]));let s=e.endUpdate;e.endUpdate=a=>{let l=i.indexOf(a);return l===-1&&console.error("endUpdate called without beginUpdate",e.debugName,a.debugName),i.splice(l,1),s.apply(e,[a])}}}}handleOnListenerCountChanged(t,e){}handleObservableUpdated(t,e){if(this._isIncluded(t)){if(t instanceof st){this._handleDerivedRecomputed(t,e);return}console.log(...this.textToConsoleArgs([po("observable value changed"),tn(t.debugName,{color:"BlueViolet"}),...this.formatInfo(e)]))}}formatChanges(t){if(t.size!==0)return tn(" (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([po("derived recomputed"),tn(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([po("derived cleared"),tn(t.debugName,{color:"BlueViolet"})]))}handleFromEventObservableTriggered(t,e){this._isIncluded(t)&&console.log(...this.textToConsoleArgs([po("observable from event triggered"),tn(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([po("autorun"),tn(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([po("transaction"),tn(e,{color:"BlueViolet"}),{data:[{fn:t._fn}]}])),this.indentation++}handleEndTransaction(){this.indentation--}};function yx(r){let t=new Array,e=[],n="";function i(s){if("length"in s)for(let a of s)a&&i(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)}i(r);let o=[n,...t];return o.push(...e),o}function uo(r){return tn(r,{color:"black"})}function po(r){return tn(Ix(`${r}: `,10),{color:"black",bold:!0})}function tn(r,t={color:"black"}){function e(i){return Object.entries(i).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:r,style:e(n)}}function zt(r,t){switch(typeof r){case"number":return""+r;case"string":return r.length+2<=t?`"${r}"`:`"${r.substr(0,t-7)}"+...`;case"boolean":return r?"true":"false";case"undefined":return"undefined";case"object":return r===null?"null":Array.isArray(r)?vx(r,t):bx(r,t);case"symbol":return r.toString();case"function":return`[[Function${r.name?" "+r.name:""}]]`;default:return""+r}}function vx(r,t){let e="[ ",n=!0;for(let i of r){if(n||(e+=", "),e.length-5>t){e+="...";break}n=!1,e+=`${zt(i,t-e.length)}`}return e+=" ]",e}function bx(r,t){if(typeof r.toString=="function"&&r.toString!==Object.prototype.toString){let o=r.toString();return o.length<=t?o:o.substring(0,t-3)+"..."}let e=yf(r),n=e?e+"(":"{ ",i=!0;for(let[o,s]of Object.entries(r)){if(i||(n+=", "),n.length-5>t){n+="...";break}i=!1,n+=`${o}: ${zt(s,t-n.length)}`}return n+=e?")":" }",n}function Sx(r,t){let e="";for(let n=1;n<=t;n++)e+=r;return e}function Ix(r,t){for(;r.length<t;)r+=" ";return r}var dc=class r{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}}),i=new Proxy({},{get:(o,s)=>(...a)=>{this._channel.sendNotification([s,a])}});this.api={notifications:i,requests:n}}static createHost(t,e){return new r(t,e)}static createClient(t,e){return new r(t,e)}};function kv(r,t){let e=globalThis,n=[],i,{channel:o,handler:s}=_x({sendNotification:l=>{i?i.sendNotification(l):n.push(l)}}),a;return(e.$$debugValueEditor_debugChannels??(e.$$debugValueEditor_debugChannels={}))[r]=l=>{a=t(),i=l;for(let c of n)l.sendNotification(c);return n=[],s},dc.createClient(o,()=>{if(!a)throw new Error("Not supported");return a})}function _x(r){let t;return{channel:n=>(t=n,{sendNotification:i=>{r.sendNotification(i)},sendRequest:i=>{throw new Error("not supported")}}),handler:{handleRequest:n=>n.type==="notification"?t?.handleNotification(n.data):t?.handleRequest(n.data)}}}var uc=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 xf(r,t){for(let e in t)r[e]&&typeof r[e]=="object"&&t[e]&&typeof t[e]=="object"?xf(r[e],t[e]):r[e]=t[e]}function wf(r,t){for(let e in t)t[e]===null?delete r[e]:r[e]&&typeof r[e]=="object"&&t[e]&&typeof t[e]=="object"?wf(r[e],t[e]):r[e]=t[e]}var pc=class r{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=kv("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(yi)}),getDerivedInfo:t=>{let e=this._aliveInstances.get(t);return{dependencies:[...e.debugGetState().dependencies].map(n=>this._formatObservable(n)).filter(yi),observers:[...e.debugGetObservers()].map(n=>this._formatObserver(n)).filter(yi)}},getAutorunInfo:t=>({dependencies:[...this._aliveInstances.get(t).debugGetState().dependencies].map(n=>this._formatObservable(n)).filter(yi)}),getTransactionState:()=>this.getTransactionState(),setValue:(t,e)=>{let n=this._aliveInstances.get(t);if(n instanceof st)n.debugSetValue(e);else if(n instanceof Sn)n.debugSetValue(e);else if(n instanceof en)n.debugSetValue(e);else throw new we("Observable is not supported");let i=[...n.debugGetObservers()];for(let o of i)o.beginUpdate(n);for(let o of i)o.handleChange(n,void 0);for(let o of i)o.endUpdate(n)},getValue:t=>{let e=this._aliveInstances.get(t);if(e instanceof st)return zt(e.debugGetState().value,200);if(e instanceof Sn)return zt(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 we("Observable is not supported")},rerun:t=>{let e=this._aliveInstances.get(t);if(e instanceof st)e.debugRecompute();else if(e instanceof ti)e.debugRerun();else throw new we("Observable is not supported")}}}));this._pendingChanges=null;this._changeThrottler=new uc;this._fullState={};this._flushUpdates=()=>{this._pendingChanges!==null&&(this._channel.api.notifications.handleChange(this._pendingChanges,!1),this._pendingChanges=null)};Ke.enable()}static{this._instance=void 0}static getInstance(){return r._instance===void 0&&(r._instance=new r),r._instance}getTransactionState(){let t=[],e=[...this._activeTransactions];if(e.length===0)return;let n=e.flatMap(o=>o.debugGetUpdatingObservers()??[]).map(o=>o.observer),i=new Set;for(;n.length>0;){let o=n.shift();if(i.has(o))continue;i.add(o);let s=this._getInfo(o,a=>{i.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){Ue(new we("No info found"));return}return e}_getAutorunInfo(t){let e=this._instanceInfos.get(t);if(!e){Ue(new we("No info found"));return}return e}_getInfo(t,e){if(t instanceof st){let n=[...t.debugGetObservers()];for(let l of n)e(l);let i=this._getObservableInfo(t);if(!i)return;let o=t.debugGetState(),s={name:t.debugName,instanceId:i.instanceId,updateCount:o.updateCount},a=[...i.changedObservables].map(l=>this._instanceInfos.get(l)?.instanceId).filter(yi);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 ti){let n=this._getAutorunInfo(t);if(!n)return;let i={name:t.debugName,instanceId:n.instanceId,updateCount:n.updateCount},o=[...n.changedObservables].map(s=>this._instanceInfos.get(s).instanceId);if(t.debugGetState().isRunning)return{...i,type:"autorun",state:"updating",changedDependencies:o};switch(t.debugGetState().state){case 3:return{...i,type:"autorun",state:"upToDate"};case 2:return{...i,type:"autorun",state:"stale",changedDependencies:o};case 1:return{...i,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 st)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){wf(this._fullState,t),this._pendingChanges===null?this._pendingChanges=t:xf(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 i={declarationId:this._getDeclarationId("observable/value",e),instanceId:this._instanceId++,listenerCount:0,lastValue:void 0,updateCount:0,changedObservables:new Set};this._instanceInfos.set(t,i)}handleOnListenerCountChanged(t,e){let n=this._getObservableInfo(t);if(n){if(n.listenerCount===0&&e>0){let i=t instanceof st?"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:i,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 st){this._handleDerivedRecomputed(t,e);return}let n=this._getObservableInfo(t);n&&e.didChange&&(n.lastValue=zt(e.newValue,30),n.listenerCount>0&&this._handleChange({instances:{[n.instanceId]:{formattedValue:n.lastValue}}}))}handleAutorunCreated(t,e){let i={declarationId:this._getDeclarationId("autorun",e),instanceId:this._instanceId++,updateCount:0,changedObservables:new Set};this._instanceInfos.set(t,i),this._aliveInstances.set(i.instanceId,t),i&&this._handleChange({instances:{[i.instanceId]:{instanceId:i.instanceId,declarationId:i.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 i=this._getAutorunInfo(t);i&&i.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 i=this._getObservableInfo(t);i&&i.changedObservables.add(e)}_handleDerivedRecomputed(t,e){let n=this._getObservableInfo(t);if(!n)return;let i=zt(e.newValue,30);n.updateCount++,n.changedObservables.clear(),n.lastValue=i,n.listenerCount>0&&this._handleChange({instances:{[n.instanceId]:{formattedValue:i,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 Av(r,t){let e=t?.debugNamePostProcessor??(o=>o),n=gr.from(r,e);if(!n)return"";let i=new Set;return t.type==="observers"?Ov(n,0,i,t).trim():Dv(n,0,i,t).trim()}function Dv(r,t,e,n){let i="		".repeat(t),o=[];if(e.has(r.sourceObj))return o.push(`${i}* ${r.type} ${r.name} (already listed)`),o.join(`
`);if(e.add(r.sourceObj),o.push(`${i}* ${r.type} ${r.name}:`),o.push(`${i}  value: ${zt(r.value,50)}`),o.push(`${i}  state: ${r.state}`),r.dependencies.length>0){o.push(`${i}  dependencies:`);for(let a of r.dependencies){let l=gr.from(a,n.debugNamePostProcessor??(c=>c))??gr.unknown(a);o.push(Dv(l,t+1,e,n))}}return o.join(`
`)}function Ov(r,t,e,n){let i="		".repeat(t),o=[];if(e.has(r.sourceObj))return o.push(`${i}* ${r.type} ${r.name} (already listed)`),o.join(`
`);if(e.add(r.sourceObj),o.push(`${i}* ${r.type} ${r.name}:`),o.push(`${i}  value: ${zt(r.value,50)}`),o.push(`${i}  state: ${r.state}`),r.observers.length>0){o.push(`${i}  observers:`);for(let a of r.observers){let l=gr.from(a,n.debugNamePostProcessor??(c=>c))??gr.unknown(a);o.push(Ov(l,t+1,e,n))}}return o.join(`
`)}var gr=class r{constructor(t,e,n,i,o,s,a){this.sourceObj=t;this.name=e;this.type=n;this.value=i;this.state=o;this.dependencies=s;this.observers=a}static from(t,e){if(t instanceof ti){let n=t.debugGetState();return new r(t,e(t.debugName),"autorun",void 0,n.stateStr,Array.from(n.dependencies),[])}else if(t instanceof st){let n=t.debugGetState();return new r(t,e(t.debugName),"derived",n.value,n.stateStr,Array.from(n.dependencies),Array.from(t.debugGetObservers()))}else if(t instanceof Sn){let n=t.debugGetState();return new r(t,e(t.debugName),"observableValue",n.value,"upToDate",[],Array.from(t.debugGetObservers()))}else if(t instanceof en){let n=t.debugGetState();return new r(t,e(t.debugName),"fromEvent",n.value,n.hasValue?"upToDate":"initial",[],Array.from(t.debugGetObservers()))}}static unknown(t){return new r(t,"(unknown)","unknown",void 0,"unknown",[],[])}};xv(Av);vv(Pv);var Cx=!1;Cx&&aa(new ca);ke&&ke.VSCODE_DEV_DEBUG_OBSERVABLES&&aa(pc.getInstance());var Rf=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]}},Ef=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?Fl(t,this._value,0,t.length,this._from,this._to):sr(t,this._value,0,t.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}},fc=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?Fl(t,this._value,0,t.length,this._from,this._to):sr(t,this._value,0,t.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}};var Pf=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 fc(!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 Vp(t,this._value.scheme);if(this._states[this._stateIdx]===2)return Vp(t,this._value.authority);if(this._states[this._stateIdx]===3)return this._pathIterator.cmp(t);if(this._states[this._stateIdx]===4)return zs(t,this._value.query);if(this._states[this._stateIdx]===5)return zs(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}},ni=class r{static{this.Val=Symbol("undefined_placeholder")}static wrap(t){return t===void 0?r.Val:t}static unwrap(t){return t===r.Val?void 0:t}},fo=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 Cn=class r{static forUris(t=()=>!1,e=()=>!1){return new r(new Pf(t,e))}static forPaths(t=!1){return new r(new fc(void 0,!t))}static forStrings(){return new r(new Rf)}static forConfigKeys(){return new r(new Ef)}constructor(t){this._iter=t}clear(){this._root=void 0}fill(t,e){if(e){let n=e.slice(0);Cp(n);for(let i of n)this.set(i,t)}else{let n=t.slice(0);Cp(n);for(let i of n)this.set(i[0],i[1])}}set(t,e){let n=this._iter.reset(t),i;this._root||(this._root=new fo,this._root.segment=n.value());let o=[];for(i=this._root;;){let a=n.cmp(i.segment);if(a>0)i.left||(i.left=new fo,i.left.segment=n.value()),o.push([-1,i]),i=i.left;else if(a<0)i.right||(i.right=new fo,i.right.segment=n.value()),o.push([1,i]),i=i.right;else if(n.hasNext())n.next(),i.mid||(i.mid=new fo,i.mid.segment=n.value()),o.push([0,i]),i=i.mid;else break}let s=ni.unwrap(i.value);i.value=ni.wrap(e),i.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 u=o[a][0],d=o[a+1][0];if(u===1&&d===1)o[a][1]=l.rotateLeft();else if(u===-1&&d===-1)o[a][1]=l.rotateRight();else if(u===1&&d===-1)l.right=o[a+1][1]=o[a+1][1].rotateRight(),o[a][1]=l.rotateLeft();else if(u===-1&&d===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 ni.unwrap(this._getNode(t)?.value)}_getNode(t){let e=this._iter.reset(t),n=this._root;for(;n;){let i=e.cmp(n.segment);if(i>0)n=n.left;else if(i<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),i=[],o=this._root;for(;o;){let s=n.cmp(o.segment);if(s>0)i.push([-1,o]),o=o.left;else if(s<0)i.push([1,o]),o=o.right;else if(n.hasNext())n.next(),i.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[u,d]=s[s.length-1];switch(u){case-1:d.left=l;break;case 0:Tl(!1);case 1:Tl(!1)}}else o.right=l;let c=this._balanceByStack(s);if(i.length>0){let[u,d]=i[i.length-1];switch(u){case-1:d.left=c;break;case 0:d.mid=c;break;case 1:d.right=c;break}}else this._root=c}}else{let s=o.left??o.right;if(i.length>0){let[a,l]=i[i.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(i)??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 i=n.balanceFactor();if(i>1?(n.right.balanceFactor()>=0||(n.right=n.right.rotateRight()),t[e][1]=n.rotateLeft()):i<-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,i;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(),i=ni.unwrap(n.value)||i,n=n.mid;else break}return n&&ni.unwrap(n.value)||i}findSuperstr(t){return this._findSuperstrOrElement(t,!1)}_findSuperstrOrElement(t,e){let n=this._iter.reset(t),i=this._root;for(;i;){let o=n.cmp(i.segment);if(o>0)i=i.left;else if(o<0)i=i.right;else if(n.hasNext())n.next(),i=i.mid;else return i.mid?this._entries(i.mid):e?ni.unwrap(i.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,ni.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 Se=V("fileService");function ri(r){return r.create===!0}function qt(r){return!!(r.capabilities&2)}function Lv(r){return!!(r.capabilities&524288)}function kf(r){return!!(r.capabilities&8)}function Mv(r){return!!(r.capabilities&131072)}function Nv(r){return!!(r.capabilities&262144)}function oi(r){return!!(r.capabilities&4)}function hc(r){return!!(r.capabilities&16)}function yc(r){return qt(r)?!!(r.capabilities&16384):!1}function Af(r){return qt(r)?!!(r.capabilities&32768):!1}function Uv(r){return!!(r.capabilities&65536)}var go=class r extends Error{constructor(e,n){super(e);this.code=n}static create(e,n){let i=new r(e.toString(),n);return Tx(i,n),i}};function he(r,t){return go.create(r,t)}function si(r){return r||he(g(2371,null),"Unknown")}function Tx(r,t){return r.name=t?`${t} (FileSystemError)`:"FileSystemError",r}function Dt(r){if(!r)return"Unknown";if(r instanceof go)return r.code;let t=/^(.+) \(FileSystemError\)$/.exec(r.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 Df(r){if(r instanceof je)return r.fileOperationResult;switch(Dt(r)){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 ii=class{constructor(t,e,n){this.resource=t;this.operation=e;this.target=n}isOperation(t){return this.operation===t}};var gc=class r{constructor(t,e){this.ignorePathCasing=e;this.correlationId=void 0;this.added=new Ee(()=>{let t=Cn.forUris(()=>this.ignorePathCasing);return t.fill(this.rawAdded.map(e=>[e,!0])),t});this.updated=new Ee(()=>{let t=Cn.forUris(()=>this.ignorePathCasing);return t.fill(this.rawUpdated.map(e=>[e,!0])),t});this.deleted=new Ee(()=>{let t=Cn.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!==r.MIXED_CORRELATION&&(typeof n.cId=="number"?this.correlationId===void 0?this.correlationId=n.cId:this.correlationId!==n.cId&&(this.correlationId=r.MIXED_CORRELATION):this.correlationId!==void 0&&(this.correlationId=r.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 i=n.length>0;return!!((!i||n.includes(1))&&(this.added.value.get(t)||e.includeChildren&&this.added.value.findSuperstr(t))||(!i||n.includes(0))&&(this.updated.value.get(t)||e.includeChildren&&this.updated.value.findSuperstr(t))||(!i||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 Fv(r,t,e){return!r||!t||r===t||t.length>r.length?!1:(t.charAt(t.length-1)!==Ce&&(t+=Ce),e?_i(r,t):r.indexOf(t)===0)}var je=class extends Error{constructor(e,n,i){super(e);this.fileOperationResult=n;this.options=i}},mo=class extends je{constructor(e,n,i,o){super(e,n,o);this.fileOperationResult=n;this.size=i}},ho=class extends je{constructor(e,n,i){super(e,2,i);this.stat=n}};var vc="";function Of(r){if(!(typeof r.size!="number"||typeof r.mtime!="number"))return r.mtime.toString(29)+r.size.toString(31)}var mc=class r{static{this.KB=1024}static{this.MB=r.KB*r.KB}static{this.GB=r.MB*r.KB}static{this.TB=r.GB*r.KB}static formatSize(t){return Us(t)||(t=0),t<r.KB?g(2366,null,t.toFixed(0)):t<r.MB?g(2368,null,(t/r.KB).toFixed(2)):t<r.GB?g(2369,null,(t/r.MB).toFixed(2)):t<r.TB?g(2367,null,(t/r.GB).toFixed(2)):g(2370,null,(t/r.TB).toFixed(2))}};var ai=class{constructor(t,e=[],n=!1){this.ctor=t,this.staticArguments=e,this.supportsDelayedInstantiation=n}};var Lf=class{constructor(t,e){this.key=t;this.data=e;this.incoming=new Map;this.outgoing=new Map}},da=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),i=this.lookupOrInsertNode(e);n.outgoing.set(i.key,i),i.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 Lf(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]),i=this._findCycle(e,n);if(i)return i}}_findCycle(t,e){for(let[n,i]of t.outgoing){if(e.has(n))return[...e,n].join(" -> ");e.add(n);let o=this._findCycle(i,e);if(o)return o;e.delete(n)}}};var Ai=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 xx=!1,bc=class extends Error{constructor(t){super("cyclic dependency between services"),this.message=t.findCycleSlow()??`UNABLE to detect cycle, dumping graph: 
${t.toString()}`}},yo=class r{constructor(t=new Ai,e=!1,n,i=xx){this._services=t;this._strict=e;this._parent=n;this._enableTracing=i;this._isDisposed=!1;this._servicesToMaybeDispose=new Set;this._children=new Set;this._activeInstantiations=new Set;this._services.set(qe,this),this._globalGraph=i?n?._globalGraph??new da(o=>o):void 0}dispose(){if(!this._isDisposed){this._isDisposed=!0,gt(this._children),this._children.clear();for(let t of this._servicesToMaybeDispose)$r(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,i=new class extends r{dispose(){n._children.delete(i),super.dispose()}}(t,this._strict,this,this._enableTracing);return this._children.add(i),e?.add(i),i}invokeFunction(t,...e){this._throwIfDisposed();let n=ua.traceInvocation(this._enableTracing,t),i=!1;try{return t({get:s=>{if(i)throw bl("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{i=!0,n.stop()}}createInstance(t,...e){this._throwIfDisposed();let n,i;return t instanceof ai?(n=ua.traceCreation(this._enableTracing,t.ctor),i=this._createInstance(t.ctor,t.staticArguments.concat(e),n)):(n=ua.traceCreation(this._enableTracing,t),i=this._createInstance(t,e,n)),n.stop(),i}_createInstance(t,e=[],n){let i=dn.getServiceDependencies(t).sort((a,l)=>a.index-l.index),o=[];for(let a of i){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=i.length>0?i[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 ai)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 ai?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 i=new da(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)),i.lookupOrInsertNode(l),o++>1e3)throw new bc(i);for(let c of dn.getServiceDependencies(l.desc.ctor)){let u=this._getServiceInstanceOrDescriptor(c.id);if(u||this._throwIfStrict(`[createInstance] ${t} depends on ${c.id} which is NOT registered.`,!0),this._globalGraph?.insertEdge(String(l.id),String(c.id)),u instanceof ai){let d={id:c.id,desc:u,_trace:l._trace.branch(c.id,!0)};i.insertEdge(l,d),s.push(d)}}}}for(;;){let l=i.roots();if(l.length===0){if(!i.isEmpty())throw new bc(i);break}for(let{data:c}of l){if(this._getServiceInstanceOrDescriptor(c.id)instanceof ai){let d=this._createServiceInstanceWithOwner(c.id,c.desc.ctor,c.desc.staticArguments,c.desc.supportsDelayedInstantiation,c._trace);this._setCreatedServiceInstance(c.id,d)}i.removeNode(c)}}return this._getServiceInstanceOrDescriptor(t)}_createServiceInstanceWithOwner(t,e,n=[],i,o){if(this._services.get(t)instanceof ai)return this._createServiceInstance(t,e,n,i,o,this._servicesToMaybeDispose);if(this._parent)return this._parent._createServiceInstanceWithOwner(t,e,n,i,o);throw new Error(`illegalState - creating UNKNOWN service instance ${e.name}`)}_createServiceInstance(t,e,n=[],i,o,s){if(i){let a=new r(void 0,this._strict,this,this._enableTracing);a._globalGraphImplicitDependency=String(t);let l=new Map,c=new zl(()=>{let u=a._createInstance(e,n,o);for(let[d,f]of l){let m=u[d];if(typeof m=="function")for(let h of f)h.disposable=m.apply(u,h.listener)}return l.clear(),s.add(u),u});return new Proxy(Object.create(null),{get(u,d){if(!c.isInitialized&&typeof d=="string"&&(d.startsWith("onDid")||d.startsWith("onWill"))){let h=l.get(d);return h||(h=new Ws,l.set(d,h)),(S,_,b)=>{if(c.isInitialized)return c.value[d](S,_,b);{let I={listener:[S,_,b],disposable:void 0},R=h.push(I);return A(()=>{R(),I.disposable?.dispose()})}}}if(d in u)return u[d];let f=c.value,m=f[d];return typeof m!="function"||(m=m.bind(f),u[d]=m),m},set(u,d,f){return c.value[d]=f,!0},getPrototypeOf(u){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 ua=class r{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 r{constructor(){super(0,null)}stop(){}branch(){return this}}}static traceInvocation(t,e){return t?new r(2,e.name||new Error().stack.split(`
`).slice(3,4).join(`
`)):r._None}static traceCreation(t,e){return t?new r(1,e.name):r._None}static{this._totals=0}branch(t,e){let n=new r(3,t.toString());return this._dep.push([t,e,n]),n}stop(){let t=Date.now()-this._start;r._totals+=t;let e=!1;function n(o,s){let a=[],l=new Array(o+1).join("	");for(let[c,u,d]of s._dep)if(u&&d){e=!0,a.push(`${l}CREATES -> ${c}`);let f=n(o+1,d);f&&a.push(f)}else a.push(`${l}uses -> ${c}`);return a.join(`
`)}let i=[`${this.type===1?"CREATE":"CALL"} ${this.name}`,`${n(1,this)}`,`DONE, took ${t.toFixed(2)}ms (grand total ${r._totals.toFixed(2)}ms)`];(t>2||e)&&r.all.add(i.join(`
`))}};function ht(r){return Nf(r,0)}function Nf(r,t){switch(typeof r){case"object":return r===null?li(349,t):Array.isArray(r)?Rx(r,t):Ex(r,t);case"string":return $v(r,t);case"boolean":return wx(r,t);case"number":return li(r,t);case"undefined":return li(937,t);default:return li(617,t)}}function li(r,t){return(t<<5)-t+r|0}function wx(r,t){return li(r?433:863,t)}function $v(r,t){t=li(149417,t);for(let e=0,n=r.length;e<n;e++)t=li(r.charCodeAt(e),t);return t}function Rx(r,t){return t=li(104579,t),r.reduce((e,n)=>Nf(n,e),t)}function Ex(r,t){return t=li(181387,t),Object.keys(r).sort().reduce((e,n)=>(e=$v(n,e),Nf(r[n],e)),t)}function Mf(r,t,e=32){let n=e-t,i=~((1<<n)-1);return(r<<t|(i&r)>>>n)>>>0}function pa(r,t=32){return r instanceof ArrayBuffer?cn(k.wrap(new Uint8Array(r))):(r>>>0).toString(16).padStart(t/4,"0")}var Wv=class r{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,i=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(dy(s))if(a+1<e){let c=t.charCodeAt(a+1);Hp(c)?(a++,l=uy(s,c)):l=65533}else{o=s;break}else Hp(s)&&(l=65533);if(i=this._push(n,i,l),a++,a<e)s=t.charCodeAt(a);else break}this._buffLen=i,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()),pa(this._h0)+pa(this._h1)+pa(this._h2)+pa(this._h3)+pa(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=r._bigBlock32,e=this._buffDV;for(let d=0;d<64;d+=4)t.setUint32(d,e.getUint32(d,!1),!1);for(let d=64;d<320;d+=4)t.setUint32(d,Mf(t.getUint32(d-12,!1)^t.getUint32(d-32,!1)^t.getUint32(d-56,!1)^t.getUint32(d-64,!1),1),!1);let n=this._h0,i=this._h1,o=this._h2,s=this._h3,a=this._h4,l,c,u;for(let d=0;d<80;d++)d<20?(l=i&o|~i&s,c=1518500249):d<40?(l=i^o^s,c=1859775393):d<60?(l=i&o|i&s|o&s,c=2400959708):(l=i^o^s,c=3395469782),u=Mf(n,5)+l+a+c+t.getUint32(d*4,!1)&4294967295,a=s,s=o,o=Mf(i,30),i=n,n=u;this._h0=this._h0+n&4294967295,this._h1=this._h1+i&4294967295,this._h2=this._h2+o&4294967295,this._h3=this._h3+s&4294967295,this._h4=this._h4+a&4294967295}};function Uf(...r){switch(r.length){case 1:return g(2169,null,r[0]);case 2:return g(2170,null,r[0],r[1]);case 3:return g(2171,null,r[0],r[1],r[2]);default:return}}var Px=g(2168,null),kx=g(2167,null),Di=class r{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 bl(`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(Uf("==","=~"));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(Uf("&&"));break;case 124:this._match(124)?this._addToken(16):this._error(Uf("||"));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),i={type:19,offset:this._start,lexeme:n};this._errors.push({offset:e,lexeme:n,additionalInfo:t}),this._tokens.push(i)}_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=r._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(Px);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(kx);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&&r._regexFlags.has(this._input.charCodeAt(t));)t++;this._current=t;let i=this._input.substring(this._start,this._current);this._tokens.push({type:10,lexeme:i,offset:this._start})}_isAtEnd(){return this._current>=this._input.length}};var et=new Map;et.set("false",!1);et.set("true",!0);et.set("isMac",Ye);et.set("isLinux",ve);et.set("isWindows",K);et.set("isWeb",It);et.set("isMacNative",Ye&&!It);et.set("isEdge",qh);et.set("isFirefox",Hh);et.set("isChrome",Ap);et.set("isSafari",zh);var Ax=Object.prototype.hasOwnProperty;var Dx={regexParsingWithErrorRecovery:!0},Ox=g(2148,null),Lx=g(2149,null),Mx=g(2151,null),Vv=g(2147,null),Nx=g(2154,null),Ux=g(2155,null),Fx=g(2152,null),Wx=g(2153,null),Ff=class r{constructor(t=Dx){this._config=t;this._scanner=new Di;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:Ox,offset:0,lexeme:"",additionalInfo:Lx});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(),i=n.type===17?Ux:void 0;throw this._parsingErrors.push({message:Nx,offset:n.offset,lexeme:Di.getLexeme(n),additionalInfo:i}),r._parseError}return e}catch(e){if(e!==r._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]:at.or(...t)}_and(){let t=[this._term()];for(;this._matchOne(15);){let e=this._term();t.push(e)}return t.length===1?t[0]:at.and(...t)}_term(){if(this._matchOne(2)){let t=this._peek();switch(t.type){case 11:return this._advance(),ut.INSTANCE;case 12:return this._advance(),yt.INSTANCE;case 0:{this._advance();let e=this._expr();return this._consume(1,Vv),e?.negate()}case 17:return this._advance(),hr.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(),at.true();case 12:return this._advance(),at.false();case 0:{this._advance();let e=this._expr();return this._consume(1,Vv),e}case 17:{let e=t.lexeme;if(this._advance(),this._matchOne(9)){let i=this._peek();if(!this._config.regexParsingWithErrorRecovery){if(this._advance(),i.type!==10)throw this._errExpectedButGot("REGEX",i);let o=i.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",i)}return ba.create(e,l)}switch(i.type){case 10:case 19:{let o=[i.lexeme];this._advance();let s=this._peek(),a=0;for(let f=0;f<i.lexeme.length;f++)i.lexeme.charCodeAt(f)===40?a++:i.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++:i.lexeme.charCodeAt(f)===41&&a--}if(a<0)break;o.push(Di.getLexeme(s)),this._advance(),s=this._peek()}let l=o.join(""),c=l.lastIndexOf("/"),u=c===l.length-1?void 0:this._removeFlagsGY(l.substring(c+1)),d;try{d=new RegExp(l.substring(1,c),u)}catch{throw this._errExpectedButGot("REGEX",i)}return at.regex(e,d)}case 18:{let o=i.lexeme;this._advance();let s=null;if(!sy(o)){let a=o.indexOf("/"),l=o.lastIndexOf("/");if(a!==l&&a>=0){let c=o.slice(a+1,l),u=o[l+1]==="i"?"i":"";try{s=new RegExp(c,u)}catch{throw this._errExpectedButGot("REGEX",i)}}}if(s===null)throw this._errExpectedButGot("REGEX",i);return ba.create(e,s)}default:throw this._errExpectedButGot("REGEX",this._peek())}}if(this._matchOne(14)){this._consume(13,Mx);let i=this._value();return at.notIn(e,i)}switch(this._peek().type){case 3:{this._advance();let i=this._value();if(this._previous().type===18)return at.equals(e,i);switch(i){case"true":return at.has(e);case"false":return at.not(e);default:return at.equals(e,i)}}case 4:{this._advance();let i=this._value();if(this._previous().type===18)return at.notEquals(e,i);switch(i){case"true":return at.not(e);case"false":return at.has(e);default:return at.notEquals(e,i)}}case 5:return this._advance(),ya.create(e,this._value());case 6:return this._advance(),va.create(e,this._value());case 7:return this._advance(),vo.create(e,this._value());case 8:return this._advance(),ha.create(e,this._value());case 13:return this._advance(),at.in(e,this._value());default:return at.has(e)}}case 20:throw this._parsingErrors.push({message:Fx,offset:t.offset,lexeme:"",additionalInfo:Wx}),r._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 i=g(2150,null,t,Di.getLexeme(e)),o=e.offset,s=Di.getLexeme(e);return this._parsingErrors.push({message:i,offset:o,lexeme:s,additionalInfo:n}),r._parseError}_check(t){return this._peek().type===t}_peek(){return this._tokens[this._current]}_isAtEnd(){return this._peek().type===20}},at=class{static false(){return ut.INSTANCE}static true(){return yt.INSTANCE}static has(t){return mr.create(t)}static equals(t,e){return ga.create(t,e)}static notEquals(t,e){return ma.create(t,e)}static regex(t,e){return ba.create(t,e)}static in(t,e){return Sc.create(t,e)}static notIn(t,e){return Ic.create(t,e)}static not(t){return hr.create(t)}static and(...t){return _c.create(t,null,!0)}static or(...t){return Sa.create(t,null,!0)}static greater(t,e){return vo.create(t,e)}static greaterEquals(t,e){return ha.create(t,e)}static smaller(t,e){return ya.create(t,e)}static smallerEquals(t,e){return va.create(t,e)}static{this._parser=new Ff({regexParsingWithErrorRecovery:!1})}static deserialize(t){return t==null?void 0:this._parser.parse(t)}};function fa(r,t){return r.cmp(t)}var ut=class r{constructor(){this.type=0}static{this.INSTANCE=new r}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 yt.INSTANCE}},yt=class r{constructor(){this.type=1}static{this.INSTANCE=new r}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 ut.INSTANCE}},mr=class r{constructor(t,e){this.key=t;this.negated=e;this.type=2}static create(t,e=null){let n=et.get(t);return typeof n=="boolean"?n?yt.INSTANCE:ut.INSTANCE:new r(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:zv(this.key,t.key)}equals(t){return t.type===this.type?this.key===t.key:!1}substituteConstants(){let t=et.get(this.key);return typeof t=="boolean"?t?yt.INSTANCE:ut.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=hr.create(this.key,this)),this.negated}},ga=class r{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?mr.create(t,n):hr.create(t,n);let i=et.get(t);return typeof i=="boolean"?e===(i?"true":"false")?yt.INSTANCE:ut.INSTANCE:new r(t,e,n)}cmp(t){return t.type!==this.type?this.type-t.type:yr(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=et.get(this.key);if(typeof t=="boolean"){let e=t?"true":"false";return this.value===e?yt.INSTANCE:ut.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=ma.create(this.key,this.value,this)),this.negated}},Sc=class r{constructor(t,e){this.key=t;this.valueKey=e;this.type=10;this.negated=null}static create(t,e){return new r(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:yr(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(K&&typeof n=="string"&&n.startsWith("file:///")){let i=n.toLowerCase();return e.some(o=>typeof o=="string"&&o.toLowerCase()===i)}return!1}if(typeof n=="string"&&typeof e=="object"&&e!==null){if(Ax.call(e,n))return!0;if(K&&n.startsWith("file:///")){let i=n.toLowerCase();return Object.keys(e).some(o=>o.toLowerCase()===i)}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=Ic.create(this.key,this.valueKey)),this.negated}},Ic=class r{constructor(t,e){this.key=t;this.valueKey=e;this.type=11;this._negated=Sc.create(t,e)}static create(t,e){return new r(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}},ma=class r{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?hr.create(t,n):mr.create(t,n);let i=et.get(t);return typeof i=="boolean"?e===(i?"true":"false")?ut.INSTANCE:yt.INSTANCE:new r(t,e,n)}cmp(t){return t.type!==this.type?this.type-t.type:yr(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=et.get(this.key);if(typeof t=="boolean"){let e=t?"true":"false";return this.value===e?ut.INSTANCE:yt.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=ga.create(this.key,this.value,this)),this.negated}},hr=class r{constructor(t,e){this.key=t;this.negated=e;this.type=3}static create(t,e=null){let n=et.get(t);return typeof n=="boolean"?n?ut.INSTANCE:yt.INSTANCE:new r(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:zv(this.key,t.key)}equals(t){return t.type===this.type?this.key===t.key:!1}substituteConstants(){let t=et.get(this.key);return typeof t=="boolean"?t?ut.INSTANCE:yt.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=mr.create(this.key,this)),this.negated}};function Tc(r,t){if(typeof r=="string"){let e=parseFloat(r);isNaN(e)||(r=e)}return typeof r=="string"||typeof r=="number"?t(r):ut.INSTANCE}var vo=class r{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=12}static create(t,e,n=null){return Tc(e,i=>new r(t,i,n))}cmp(t){return t.type!==this.type?this.type-t.type:yr(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=va.create(this.key,this.value,this)),this.negated}},ha=class r{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=13}static create(t,e,n=null){return Tc(e,i=>new r(t,i,n))}cmp(t){return t.type!==this.type?this.type-t.type:yr(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=ya.create(this.key,this.value,this)),this.negated}},ya=class r{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=14}static create(t,e,n=null){return Tc(e,i=>new r(t,i,n))}cmp(t){return t.type!==this.type?this.type-t.type:yr(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=ha.create(this.key,this.value,this)),this.negated}},va=class r{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=15}static create(t,e,n=null){return Tc(e,i=>new r(t,i,n))}cmp(t){return t.type!==this.type?this.type-t.type:yr(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=vo.create(this.key,this.value,this)),this.negated}},ba=class r{constructor(t,e){this.key=t;this.regexp=e;this.type=7;this.negated=null}static create(t,e){return new r(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=Wf.create(this)),this.negated}},Wf=class r{constructor(t){this._actual=t;this.type=8}static create(t){return new r(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 r(this._actual.map(t))}negate(){return this._actual}};function Hv(r){let t=null;for(let e=0,n=r.length;e<n;e++){let i=r[e].substituteConstants();if(r[e]!==i&&t===null){t=[];for(let o=0;o<e;o++)t[o]=r[o]}t!==null&&(t[e]=i)}return t===null?r:t}var _c=class r{constructor(t,e){this.expr=t;this.negated=e;this.type=6}static create(t,e,n){return r._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 i=fa(this.expr[e],t.expr[e]);if(i!==0)return i}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=Hv(this.expr);return t===this.expr?this:r.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 i=[],o=!1;for(let s of t)if(s){if(s.type===1){o=!0;continue}if(s.type===0)return ut.INSTANCE;if(s.type===6){i.push(...s.expr);continue}i.push(s)}if(i.length===0&&o)return yt.INSTANCE;if(i.length!==0){if(i.length===1)return i[0];i.sort(fa);for(let s=1;s<i.length;s++)i[s-1].equals(i[s])&&(i.splice(s,1),s--);if(i.length===1)return i[0];for(;i.length>1;){let s=i[i.length-1];if(s.type!==9)break;i.pop();let a=i.pop(),l=i.length===0,c=Sa.create(s.expr.map(u=>r.create([u,a],null,n)),null,l);c&&(i.push(c),i.sort(fa))}if(i.length===1)return i[0];if(n){for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++)if(i[s].negate().equals(i[a]))return ut.INSTANCE;if(i.length===1)return i[0]}return new r(i,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 r(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=Sa.create(t,this,!0)}return this.negated}},Sa=class r{constructor(t,e){this.expr=t;this.negated=e;this.type=9}static create(t,e,n){return r._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 i=fa(this.expr[e],t.expr[e]);if(i!==0)return i}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=Hv(this.expr);return t===this.expr?this:r.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 i=[],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 yt.INSTANCE;if(l.type===9){i=i.concat(l.expr);continue}i.push(l)}}if(i.length===0&&o)return ut.INSTANCE;i.sort(fa)}if(i.length!==0){if(i.length===1)return i[0];for(let s=1;s<i.length;s++)i[s-1].equals(i[s])&&(i.splice(s,1),s--);if(i.length===1)return i[0];if(n){for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++)if(i[s].negate().equals(i[a]))return yt.INSTANCE;if(i.length===1)return i[0]}return new r(i,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 r(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(),i=[];for(let o of Bv(e))for(let s of Bv(n))i.push(_c.create([o,s],null,!1));t.unshift(r.create(i,null,!1))}this.negated=r.create(t,this,!0)}return this.negated}},Cc=class r extends mr{static{this._info=[]}static all(){return r._info.values()}constructor(t,e,n){super(t,null),this._defaultValue=e,typeof n=="object"?r._info.push({...n,key:t}):n!==!0&&r._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 ga.create(this.key,t)}notEqualsTo(t){return ma.create(this.key,t)}greater(t){return vo.create(this.key,t)}},cF=V("contextKeyService");function zv(r,t){return r<t?-1:r>t?1:0}function yr(r,t,e,n){return r<e?-1:r>e?1:t<n?-1:t>n?1:0}function Bv(r){return r.type===9?r.expr:[r]}var L=V("logService"),Kv=V("loggerService");function Vf(r){return Us(r)}var jv=3;function $x(r,t){return r!==0&&r<=t}function Vx(r,t,e){switch(t){case 1:r.trace(e);break;case 2:r.debug(e);break;case 3:r.info(e);break;case 4:r.warn(e);break;case 5:r.error(e);break;case 0:break;default:throw new Error(`Invalid log level ${t}`)}}var Gv=!1,qv=!1,Bx=!1;function Ia(r,t){switch(r){case"debug":console.debug=t;break;case"error":console.error=t;break;case"info":console.info=t;break;case"log":console.log=t;break;case"warn":console.warn=t;break}}function Jv(r){let t={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn},e=(i,o,s)=>{if(!Bx){qv=!0;try{Vx(r,o,vr(s))}catch{}finally{qv=!1}}t[i].apply(console,s)},n={debug:(...i)=>e("debug",2,i),error:(...i)=>e("error",5,i),info:(...i)=>e("info",3,i),log:(...i)=>e("log",3,i),warn:(...i)=>e("warn",4,i)};return Ia("debug",n.debug),Ia("error",n.error),Ia("info",n.info),Ia("log",n.log),Ia("warn",n.warn),A(()=>{console.debug===n.debug&&(console.debug=t.debug),console.error===n.error&&(console.error=t.error),console.info===n.info&&(console.info=t.info),console.log===n.log&&(console.log=t.log),console.warn===n.warn&&(console.warn=t.warn)})}function vr(r,t=!1){let e="";for(let n=0;n<r.length;n++){let i=r[n];if(i instanceof Error&&(i=Ct(i,t)),typeof i=="object")try{i=JSON.stringify(i)}catch{}e+=(n>0?" ":"")+i}return e}var xc=class extends T{constructor(){super(...arguments);this.level=jv;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 $x(this.level,e)}canLog(e){return this._store.isDisposed?!1:this.checkLogLevel(e)}},br=class extends xc{constructor(e){super();this.logAlways=e}checkLogLevel(e){return this.logAlways||super.checkLogLevel(e)}trace(e,...n){this.canLog(1)&&this.log(1,vr([e,...n],!0))}debug(e,...n){this.canLog(2)&&this.log(2,vr([e,...n]))}info(e,...n){this.canLog(3)&&this.log(3,vr([e,...n]))}warn(e,...n){this.canLog(4)&&this.log(4,vr([e,...n]))}error(e,...n){if(this.canLog(5))if(e instanceof Error){let i=Array.prototype.slice.call(arguments);i[0]=e.stack,this.log(5,vr(i))}else this.log(5,vr([e,...n]))}flush(){}};var wc=class extends xc{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 i of this.loggers)i.trace(e,...n)}debug(e,...n){for(let i of this.loggers)i.debug(e,...n)}info(e,...n){for(let i of this.loggers)i.info(e,...n)}warn(e,...n){for(let i of this.loggers)i.warn(e,...n)}error(e,...n){for(let i of this.loggers)i.error(e,...n)}flush(){for(let e of this.loggers)e.flush()}dispose(){for(let e of this.loggers)e.dispose();super.dispose()}},_a=class extends T{constructor(e,n,i){super();this.logLevel=e;this.logsHome=n;this._loggers=new Fe;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(i)for(let o of i)this._loggers.set(o.resource,{logger:void 0,info:o})}getLoggerEntry(e){return Pe(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 i=this.toResource(e),o=Pe(e)?e:n?.id??ht(i.toString()).toString(16),s=this._loggers.get(i)?.logger,a=n?.logLevel==="always"?1:n?.logLevel;s||(s=this.doCreateLogger(i,a??this.getLogLevel(i)??this.logLevel,{...n,id:o}));let l={logger:s,info:{resource:i,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(i,l),s}toResource(e){return Pe(e)?ee(this.logsHome,`${e.replace(/[\\/:\*\?"<>\|]/g,"")}.log`):e}setLogLevel(e,n){if(y.isUri(e)){let i=e,o=n,s=this._loggers.get(i);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([i,o]))}else{this.logLevel=e;for(let[i,o]of this._loggers.entries())this._loggers.get(i)?.info.logLevel===void 0&&o.logger?.setLevel(this.logLevel);this._onDidChangeLogLevel.fire(this.logLevel)}}setVisibility(e,n){let i=this.getLoggerEntry(e);i&&n!==!i.info.hidden&&(i.info.hidden=!n,this._loggers.set(i.info.resource,i),this._onDidChangeVisibility.fire([i.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),i=this._loggers.get(n);i&&(i.logger&&i.logger.dispose(),this._loggers.delete(n),this._onDidChangeLoggers.fire({added:[],removed:[i.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()}},$f=class{constructor(){this.onDidChangeLogLevel=new x().event}setLevel(t){}getLevel(){return 3}trace(t,...e){}debug(t,...e){}info(t,...e){}warn(t,...e){}error(t,...e){}critical(t,...e){}dispose(){}flush(){}},Rc=class extends $f{};function Qv(r){if(r.verbose)return 1;if(typeof r.logLevel=="string"){let t=zx(r.logLevel.toLowerCase());if(t!==void 0)return t}return jv}function Hx(r){switch(r){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 zx(r){switch(r){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 xF=new Cc("logLevel",Hx(3));var vt=V("sessionDataService"),Ca="session.db",Ec="attachments";var Yv="session",Xv="uncommitted",Bf="turn/",qx="{turnId}",Hf="compare/",Kx="{originalTurnId}",jx="{modifiedTurnId}",zf=()=>g(1876,null),qf=()=>g(1878,null),Kf=()=>g(1877,null);function Zv(r,t){return!r||!t||r===t?r:`${r} \u2192 ${t}`}var bo="/changeset/";function Ot(r){return`${r}${bo}${Yv}`}function Kt(r){return`${r}${bo}${Xv}`}function eb(r,t){if(!t||t.includes("/"))throw new Error(`buildTurnChangesetUri: turnId must be non-empty and not contain '/' (got ${JSON.stringify(t)})`);return`${r}${bo}${Bf}${t}`}function tb(r,t,e){if(!t||t.includes("/"))throw new Error(`buildCompareTurnsChangesetUri: originalTurnId must be non-empty and not contain '/' (got ${JSON.stringify(t)})`);if(!e||e.includes("/"))throw new Error(`buildCompareTurnsChangesetUri: modifiedTurnId must be non-empty and not contain '/' (got ${JSON.stringify(e)})`);return`${r}${bo}${Hf}${t}/${e}`}function Tn(r){let t=r.lastIndexOf(bo);if(t<0)return;let e=r.slice(t+bo.length);if(!e)return;let n=r.slice(0,t);if(e===Yv)return{sessionUri:n,changesetId:e,kind:"session"};if(e===Xv)return{sessionUri:n,changesetId:e,kind:"uncommitted"};if(e.startsWith(Bf)){let i=e.slice(Bf.length);return!i||i.includes("/")||i===qx?void 0:{sessionUri:n,changesetId:e,kind:"turn",turnId:i}}if(e.startsWith(Hf)){let o=e.slice(Hf.length).split("/");if(o.length!==2)return;let[s,a]=o;return!s||!a||s===Kx||a===jx?void 0:{sessionUri:n,changesetId:e,kind:"compare",originalTurnId:s,modifiedTurnId:a}}if(!e.includes("/"))return{sessionUri:n,changesetId:e,kind:"unknown"}}function jf(r){return[{label:zf(),uriTemplate:Ot(r)},{label:qf(),uriTemplate:Kt(r),description:Kf()}]}function nb(r){return r.type.startsWith("root/")}function Pc(r){return r.type.startsWith("session/")}function kc(r){return r.type.startsWith("terminal/")}function ib(r){return r.type.startsWith("changeset/")}var nn={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603},ge={SessionNotFound:-32001,ProviderNotFound:-32002,SessionAlreadyExists:-32003,TurnInProgress:-32004,UnsupportedProtocolVersion:-32005,ContentNotFound:-32006,AuthRequired:-32007,NotFound:-32008,PermissionDenied:-32009,AlreadyExists:-32010,Conflict:-32011};var ob=-32700,So=-32603,xn=-32001,sb=-32002;var ab=-32005;var Io=-32007;function lb(r){return"method"in r&&"id"in r}function cb(r){return"method"in r&&!("id"in r)}var N=class extends Error{constructor(e,n,i){super(n);this.code=e;this.data=i}};var Ne="ahp-root://",Xx="ahp-root",Zf="ahp-resource-watch";function mb(r){let t={root:r.root};r.recursive&&(t.recursive=!0),r.excludes&&r.excludes.items.length>0&&(t.excludes=[...r.excludes.items]),r.includes&&r.includes.items.length>0&&(t.includes=[...r.includes.items]);let e=Xr(k.fromString(JSON.stringify(t)),!1,!0);return`${Zf}://r/${e}`}function hb(r){let t;try{t=y.parse(r)}catch{return}if(t.scheme!==Zf)return;let e=t.path.replace(/^\//,"");if(e)try{let n=JSON.parse(bn(e).toString());return typeof n.root!="string"?void 0:{root:n.root,recursive:n.recursive===!0,...Array.isArray(n.excludes)?{excludes:{items:n.excludes.filter(i=>typeof i=="string")}}:{},...Array.isArray(n.includes)?{includes:{items:n.includes.filter(i=>typeof i=="string")}}:{}}}catch{return}}function yb(r){try{return y.parse(r).scheme===Zf}catch{return!1}}function xa(r){if(r===Ne)return!0;try{return y.parse(r).scheme===Xx}catch{return!1}}function Gt(r,t){return t?`${r.replace(/#/g,"%23")}#range=${t.start.line}:${t.start.character}-${t.end.line}:${t.end.character}`:r}function vb(r){if(!r.content||r.content.length===0)return[];let t=[];for(let e of r.content)Le(e,{type:!0})&&e.type==="fileEdit"&&t.push(e);return t}var Zx="subagent",ew=`/${Zx}/`,tw=/^(?<parentPath>.+)\/subagent\/(?<toolCallId>.+)$/;function bb(r){return typeof r=="string"?y.parse(r):r}function Sb(r){let t=bb(r),e=t.path.endsWith("/")?t.path.slice(0,-1):t.path;return{parent:t,path:`${e}${ew}`}}function Co(r,t){let{parent:e,path:n}=Sb(r);return e.with({path:`${n}${t}`}).toString()}function Ge(r){let t=bb(r),e=tw.exec(t.path);if(e?.groups)return{parentSession:t.with({path:e.groups.parentPath}),toolCallId:e.groups.toolCallId}}function Lc(r){return Ge(r)!==void 0}function Ib(r){let{parent:t,path:e}=Sb(r);return t.with({path:e}).toString()}function _b(){return{agents:[],activeSessions:0}}function eg(r){return{summary:r,lifecycle:"creating",turns:[],activeTurn:void 0}}var Jf="git";function tg(r){let t=r?.[Jf];if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n={};return typeof e.hasGitHubRemote=="boolean"&&(n.hasGitHubRemote=e.hasGitHubRemote),typeof e.branchName=="string"&&(n.branchName=e.branchName),typeof e.baseBranchName=="string"&&(n.baseBranchName=e.baseBranchName),typeof e.upstreamBranchName=="string"&&(n.upstreamBranchName=e.upstreamBranchName),typeof e.incomingChanges=="number"&&(n.incomingChanges=e.incomingChanges),typeof e.outgoingChanges=="number"&&(n.outgoingChanges=e.outgoingChanges),typeof e.uncommittedChanges=="number"&&(n.uncommittedChanges=e.uncommittedChanges),typeof e.githubOwner=="string"&&(n.githubOwner=e.githubOwner),typeof e.githubRepo=="string"&&(n.githubRepo=e.githubRepo),n}function Cb(r,t){let e={...r};return t!==void 0?e[Jf]=t:delete e[Jf],Object.keys(e).length>0?e:void 0}var Lt=V("productService");import*as Aa from"fs";var Li=V("telemetryService");var F9=V("customEndpointTelemetryService");var Tb="telemetry",To="telemetry.telemetryLevel",Mc="telemetry.enableCrashReporter",wa="telemetry.enableTelemetry";function bt(r){let t=ng(r);return{protocol:r,validate:i=>{try{return t(i,""),!0}catch{return!1}},assertValid:(i,o="")=>t(i,o)}}function wn(r){return{definition:r,toProtocol(){let t={};for(let e of Object.keys(r))t[e]=r[e].protocol;return{type:"object",properties:t}},values(t){let e=t;for(let n of Object.keys(r)){let i=e[n];if(i===void 0)continue;r[n].assertValid(i,n)}return{...e}},validate(t,e){let n=r[t];return n?n.validate(e):!1},assertValid(t,e){let n=r[t];if(!n)throw new N(nn.InvalidParams,`Unknown schema key '${t}'`);n.assertValid(e,t)},validateOrDefault(t,e){let n={},i=t??{};for(let o of Object.keys(r)){let s=r[o],a=i[o];a!==void 0&&s.validate(a)?n[o]=a:Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o])}return n}}}function ng(r){if(r.type==="object"&&r.properties){let t={};for(let n of Object.keys(r.properties))t[n]=ng(r.properties[n]);let e=new Set(r.required??[]);return(n,i)=>{if(typeof n!="object"||n===null||Array.isArray(n))throw Ir(i,"object",n);let o=n;for(let s of Object.keys(t)){let a=iw(i,s);if(o[s]===void 0){if(e.has(s))throw new N(nn.InvalidParams,`Missing required property at '${a}'`);continue}t[s](o[s],a)}}}if(r.type==="array"&&r.items){let t=ng(r.items);return(e,n)=>{if(!Array.isArray(e))throw Ir(n,"array",e);for(let i=0;i<e.length;i++)t(e[i],`${n}[${i}]`)}}return nw(r)}function nw(r){let t=r.enumDynamic===!0;return(e,n)=>{switch(r.type){case"string":if(typeof e!="string")throw Ir(n,"string",e);break;case"number":if(typeof e!="number")throw Ir(n,"number",e);break;case"boolean":if(typeof e!="boolean")throw Ir(n,"boolean",e);break;case"array":if(!Array.isArray(e))throw Ir(n,"array",e);break;case"object":if(typeof e!="object"||e===null||Array.isArray(e))throw Ir(n,"object",e);break}if(r.enum&&!t&&!r.enum.includes(e))throw new N(nn.InvalidParams,`Invalid value at '${n||"<root>"}': ${wb(e)} is not one of [${r.enum.map(i=>JSON.stringify(i)).join(", ")}]`)}}function Ir(r,t,e){return new N(nn.InvalidParams,`Invalid value at '${r||"<root>"}': expected ${t}, got ${wb(e)}`)}function iw(r,t){return r?`${r}.${t}`:t}function wb(r){try{return JSON.stringify(r)}catch{return String(r)}}var Rb=bt({type:"object",title:g(1862,null),description:g(1866,null),properties:{allow:{type:"array",title:g(1863,null),items:{type:"string",title:g(1865,null)}},deny:{type:"array",title:g(1864,null),items:{type:"string",title:g(1865,null)}}},default:{allow:[],deny:[]},sessionMutable:!0}),Mt=wn({autoApprove:bt({type:"string",title:g(1848,null),description:g(1855,null),enum:["default","autoApprove","autopilot"],enumLabels:[g(1853,null),g(1851,null),g(1849,null)],enumDescriptions:[g(1854,null),g(1852,null),g(1850,null)],default:"default",sessionMutable:!0}),permissions:Rb,mode:bt({type:"string",title:g(1856,null),description:g(1861,null),enum:["interactive","plan"],enumLabels:[g(1857,null),g(1859,null)],enumDescriptions:[g(1858,null),g(1860,null)],default:"interactive",sessionMutable:!0})}),Ea="telemetryLevel",ig="sessionSyncEnabled";function Eb(r){switch(r){case 0:return"off";case 1:return"crash";case 2:return"error";case 3:return"all"}}function Pb(r){switch(r){case"off":return 0;case"crash":return 1;case"error":return 2;case"all":return 3;default:return}}var Pa=wn({permissions:Rb,[Ea]:bt({type:"string",title:g(1847,null),description:g(1846,null),enum:["all","error","crash","off"],default:"all"}),[ig]:bt({type:"boolean",title:g(1845,null),description:g(1844,null),default:!1})});var Rn=wn({customizations:bt({type:"array",title:g(1838,null),description:g(1834,null),default:[],items:{type:"object",title:g(1837,null),properties:{uri:{type:"string",title:g(1839,null)},displayName:{type:"string",title:g(1836,null)},description:{type:"string",title:g(1835,null)}},required:["uri","displayName"]}}),defaultShell:bt({type:"string",title:g(1841,null),description:g(1840,null)}),disableCustomTerminalTool:bt({type:"boolean",title:g(1843,null),description:g(1842,null),default:!1})}),kb={customizations:[]};function Ab(r){return{type:"plugin",id:Gt(r.uri),uri:r.uri,name:r.displayName,enabled:!0}}var ka=wn({sandbox:bt({type:"object",title:g(1896,null),properties:{enabled:{type:"string",title:g(1893,null),enum:["off","on","allowNetwork"]},"enabled.windows":{type:"string",title:g(1897,null),enum:["off","on","allowNetwork"]},allowUnsandboxedCommands:{type:"boolean",title:g(1889,null)},autoApproveUnsandboxedCommands:{type:"boolean",title:g(1890,null)},"fileSystem.linux":{type:"object",title:g(1894,null)},"fileSystem.mac":{type:"object",title:g(1895,null)},"fileSystem.windows":{type:"object",title:g(1898,null)},"advanced.runtime":{type:"object",title:g(1886,null)},allowedNetworkDomains:{type:"array",title:g(1888,null),items:{type:"string",title:g(1887,null)}},deniedNetworkDomains:{type:"array",title:g(1892,null),items:{type:"string",title:g(1891,null)}}}})}),Db={"chat.agent.sandbox.enabled":"enabled","chat.agent.sandbox.enabledWindows":"enabled.windows","chat.agent.sandbox.allowUnsandboxedCommands":"allowUnsandboxedCommands","chat.agent.sandbox.autoApproveUnsandboxedCommands":"autoApproveUnsandboxedCommands","chat.agent.sandbox.fileSystem.linux":"fileSystem.linux","chat.agent.sandbox.fileSystem.mac":"fileSystem.mac","chat.agent.sandbox.fileSystem.windows":"fileSystem.windows","chat.agent.sandbox.advanced.runtime":"advanced.runtime","chat.agent.allowedNetworkDomains":"allowedNetworkDomains","chat.agent.deniedNetworkDomains":"deniedNetworkDomains"};var Je=V("agentConfigurationService"),xo=class extends T{constructor(e,n,i){super();this._stateManager=e;this._logService=n;this._rootConfigResource=i;this._rootConfigWrite=Promise.resolve();this._onDidRootConfigChange=this._register(new x);this.onDidRootConfigChange=this._onDidRootConfigChange.event;let o=this._stateManager.rootState.config,s=Rn.toProtocol(),a=ka.toProtocol();this._stateManager.rootState.config={schema:{type:"object",properties:{...o?.schema.properties,...s.properties,...a.properties}},values:{...o?.values,...this._loadPersistedRootConfig()}},this._register(this._stateManager.onDidEmitEnvelope(l=>{l.action.type==="root/configChanged"&&this._onDidRootConfigChange.fire()}))}getEffectiveValue(e,n,i){for(let o of this._effectiveChain(e)){let s=o[i];if(s!==void 0)try{return n.assertValid(i,s),s}catch(a){let l=a instanceof N?a.message:String(a);this._logService.warn(`[AgentConfigurationService] Value for '${i}' on ${e} failed schema validation, falling back: ${l}`)}}}getEffectiveWorkingDirectory(e){let n=this._stateManager.getSessionState(e)?.summary.workingDirectory;if(n!==void 0)return n;let i=Ge(e);if(i)return this._stateManager.getSessionState(i.parentSession.toString())?.summary.workingDirectory}updateSessionConfig(e,n){this._stateManager.dispatchServerAction(e,{type:"session/configChanged",config:n})}getSessionConfigValues(e){return this._stateManager.getSessionState(e)?.config?.values}getRootValue(e,n){let o=this._stateManager.rootState.config?.values?.[n];if(o!==void 0)try{return e.assertValid(n,o),o}catch(s){let a=s instanceof N?s.message:String(s);this._logService.warn(`[AgentConfigurationService] Host value for '${n}' failed schema validation, ignoring: ${a}`);return}}updateRootConfig(e,n=!1){this._stateManager.dispatchServerAction(Ne,{type:"root/configChanged",config:e,replace:n}),this.persistRootConfig()}persistRootConfig(){if(!this._rootConfigResource)return;let e=this._stateManager.rootState.config?.values??{customizations:[]},n=JSON.stringify(e,void 0,"	"),i=this._rootConfigResource;this._rootConfigWrite=this._rootConfigWrite.catch(o=>{this._logService.warn("[AgentConfigurationService] Previous host config write failed",o)}).then(async()=>{await Aa.promises.mkdir(de(i.fsPath),{recursive:!0}),await Aa.promises.writeFile(i.fsPath,`${n}
`,"utf8")}).catch(o=>{this._logService.error(`[AgentConfigurationService] Failed to persist host config to ${i.fsPath}`,o)})}*_effectiveChain(e){let n=this._stateManager.getSessionState(e)?.config?.values;n&&(yield n);let i=Ge(e);if(i){let s=this._stateManager.getSessionState(i.parentSession.toString())?.config?.values;s&&(yield s)}let o=this._stateManager.rootState.config?.values;o&&(yield o)}_loadPersistedRootConfig(){let e=kb;if(!this._rootConfigResource)return{...e};try{let n=Aa.readFileSync(this._rootConfigResource.fsPath,"utf8"),i=JSON.parse(n);return{...Rn.validateOrDefault(i,e),...ka.validateOrDefault(i,{})}}catch(n){return(n&&typeof n=="object"&&Le(n,{code:!0})?String(n.code):void 0)!=="ENOENT"&&this._logService.warn(`[AgentConfigurationService] Failed to read host config from ${this._rootConfigResource.fsPath}: ${n instanceof Error?n.message:String(n)}`),{...e}}}};xo=w([C(1,L)],xo);import*as Tr from"fs";import{userInfo as mw}from"os";import*as og from"os";var Ob=/^\d+$/,aw=/^Microsoft.PowerShell_.*/,lw=/^Microsoft.PowerShellPreview_.*/;var Da;switch(process.arch){case"ia32":Da=1;break;case"arm":case"arm64":Da=2;break;default:Da=0;break}var wo;process.env.PROCESSOR_ARCHITEW6432?wo=process.env.PROCESSOR_ARCHITEW6432==="ARM64"?2:0:process.env.PROCESSOR_ARCHITECTURE==="ARM64"?wo=2:process.env.PROCESSOR_ARCHITECTURE==="X86"?wo=1:wo=0;var _r=class{constructor(t,e,n){this.exePath=t;this.displayName=e;this.knownToExist=n}async exists(){return this.knownToExist===void 0&&(this.knownToExist=await _t.existsFile(this.exePath)),this.knownToExist}};function cw({useAlternateBitness:r=!1}={}){return r?Da===0?process.env["ProgramFiles(x86)"]||null:wo===0&&process.env.ProgramW6432||null:process.env.ProgramFiles||null}async function Uc({useAlternateBitness:r=!1,findPreview:t=!1}={}){let e=cw({useAlternateBitness:r});if(!e)return null;let n=B(e,"PowerShell");if(!await _t.existsDirectory(n))return null;let i=-1,o=null;for(let l of await xe.readdir(n)){let c=-1;if(t){let d=l.indexOf("-");if(d<0)continue;let f=l.substring(0,d);if(!Ob.test(f)||l.substring(d+1)!=="preview")continue;c=parseInt(f,10)}else{if(!Ob.test(l))continue;c=parseInt(l,10)}if(c<=i)continue;let u=B(n,l,"pwsh.exe");await _t.existsFile(u)&&(o=u,i=c)}if(!o)return null;let s=e.includes("x86")?" (x86)":"",a=t?" Preview":"";return new _r(o,`PowerShell${a}${s}`,!0)}async function Lb({findPreview:r}={}){if(!process.env.LOCALAPPDATA)return null;let t=B(process.env.LOCALAPPDATA,"Microsoft","WindowsApps");if(!await _t.existsDirectory(t))return null;let{pwshMsixDirRegex:e,pwshMsixName:n}=r?{pwshMsixDirRegex:lw,pwshMsixName:"PowerShell Preview (Store)"}:{pwshMsixDirRegex:aw,pwshMsixName:"PowerShell (Store)"};for(let i of await xe.readdir(t))if(e.test(i)){let o=B(t,i,"pwsh.exe");return new _r(o,n)}return null}function dw(){let r=B(og.homedir(),".dotnet","tools","pwsh.exe");return new _r(r,".NET Core PowerShell Global Tool")}function uw(){let r=B(og.homedir(),"scoop","apps"),t=B(r,"pwsh","current","pwsh.exe");return new _r(t,"PowerShell (Scoop)")}function pw(){let r=B(process.env.windir,Da===1&&wo!==1?"SysNative":"System32","WindowsPowerShell","v1.0","powershell.exe");return new _r(r,"Windows PowerShell",!0)}async function*fw(){let r=await Uc();r&&(yield r),r=await Uc({useAlternateBitness:!0}),r&&(yield r),r=await Lb(),r&&(yield r),r=dw(),r&&(yield r),r=await Uc({findPreview:!0}),r&&(yield r),r=await Lb({findPreview:!0}),r&&(yield r),r=await Uc({useAlternateBitness:!0,findPreview:!0}),r&&(yield r),r=await uw(),r&&(yield r),r=pw(),r&&(yield r)}async function*gw(){for await(let r of fw())await r.exists()&&(yield r)}async function Mb(){for await(let r of gw())return r;return null}async function Nb(r,t){return r===1?K?yw():lv(t):hw(r,t)}var sg=null;function hw(r,t){if(ve&&r===2||Ye&&r===3)return"/bin/bash";if(!sg){let e;if(K)e="/bin/bash";else{if(e=t.SHELL,!e)try{e=mw().shell}catch{}e||(e="sh"),e==="/bin/false"&&(e="/bin/bash")}sg=e}return sg}var ag=null;async function yw(){return ag||(ag=(await Mb()).exePath),ag}import*as Ro from"os";var lg=class{constructor(){this.data=new Map}add(t,e){Cl(Pe(t)),Cl(Oe(e)),Cl(!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=>{Fs(t.dispose)&&t.dispose()}),this.data.clear()}},lt=new lg;var T8=V("ptyService");var bw={Backend:"workbench.contributions.terminal.processBackend"},cg=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()??""}};lt.add(bw.Backend,new cg);var x8=V("localPtyService"),w8=V("terminalLogService");function Sw(r){return new Map(r)}function Iw(r){return new Map(r??[])}function Ub(r){return new Map(r.map(t=>[t[0],{map:Sw(t[1]),descriptionMap:Iw(t[2])}]))}var Cw=new Map([[2,"APPEND"],[3,"PREPEND"],[1,"REPLACE"]]),Tw=/^VSCODE_PYTHON_(PWSH|ZSH|BASH|FISH)_ACTIVATE/,xw="ms-python.vscode-python-envs",Fc=class{constructor(t){this.collections=t;this.map=new Map;this.descriptionMap=new Map;t.forEach((e,n)=>{this.populateDescriptionMap(e,n);let i=e.map.entries(),o=i.next();for(;!o.done;){let s=o.value[1],a=o.value[0];if(this.blockPythonActivationVar(a,n)){o=i.next();continue}let l=this.map.get(a);if(l||(l=[],this.map.set(a,l)),l.length>0&&l[0].type===1){o=i.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=i.next()}})}async applyToProcessEnvironment(t,e,n){let i;K&&(i={},Object.keys(t).forEach(o=>i[o.toLowerCase()]=o));for(let[o,s]of this.getVariableMap(e)){let a=K&&i[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 u=`VSCODE_ENV_${Cw.get(l.type)}`;t[u]=(t[u]?t[u]+":":"")+o+"="+this._encodeColons(c)}}}}}_encodeColons(t){return t.replaceAll(":","\\x3a")}blockPythonActivationVar(t,e){return!!(Tw.test(t)&&xw!==e)}diff(t,e){let n=new Map,i=new Map,o=new Map;if(t.getVariableMap(e).forEach((s,a)=>{let l=this.getVariableMap(e).get(a),c=Wb(s,l);c&&n.set(a,c)}),this.getVariableMap(e).forEach((s,a)=>{let l=t.getVariableMap(e).get(a),c=Wb(s,l);c&&o.set(a,c)}),this.getVariableMap(e).forEach((s,a)=>{let l=t.getVariableMap(e).get(a),c=ww(s,l);c&&i.set(a,c)}),!(n.size===0&&i.size===0&&o.size===0))return{added:n,changed:i,removed:o}}getVariableMap(t){let e=new Map;for(let n of this.map.values()){let i=n.filter(o=>Fb(o,t));i.length>0&&e.set(i[0].variable,i)}return e}getDescriptionMap(t){let e=new Map;for(let n of this.descriptionMap.values()){let i=n.filter(o=>Fb(o,t,!0));for(let o of i)e.set(o.extensionIdentifier,o.description)}return e}populateDescriptionMap(t,e){if(!t.descriptionMap)return;let n=t.descriptionMap.entries(),i=n.next();for(;!i.done;){let o=i.value[1],s=i.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),i=n.next()}}};function Fb(r,t,e=!1){return r.scope?!!(r.scope.workspaceFolder&&t?.workspaceFolder&&r.scope.workspaceFolder.index===t.workspaceFolder.index):e?t===r.scope:!0}function Wb(r,t){if(!t)return r;let e=new Set;t.forEach(i=>e.add(i.extensionIdentifier));let n=[];return r.forEach(i=>{e.has(i.extensionIdentifier)||n.push(i)}),n.length===0?void 0:n}function ww(r,t){if(!t)return;let e=new Map;t.forEach(i=>e.set(i.extensionIdentifier,i));let n=[];return r.forEach(i=>{let o=e.get(i.extensionIdentifier);o&&(i.type!==o.type||i.value!==o.value||i.scope?.workspaceFolder?.index!==o.scope?.workspaceFolder?.index)&&n.push(o)}),n.length===0?void 0:n}import{chmod as Vb,realpathSync as Pw,mkdirSync as kw}from"fs";import{promisify as Bb}from"util";import*as Wc from"os";var Oa;async function Rw(){if(Oa)return;if(!K){Oa={release:Wc.release(),buildNumber:0};return}let r,t;try{let e=await import("@vscode/windows-registry"),n="SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",i=e.GetStringRegKey("HKEY_LOCAL_MACHINE",n,"CurrentBuild");i!==void 0&&(r=parseInt(i,10),isNaN(r)&&(r=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&&i!==void 0&&(t=`${o}.${s}.${i}`)}catch{}finally{Oa={release:t||Wc.release(),buildNumber:r||Ew()}}}async function $b(){return Oa||await Rw(),Oa.buildNumber}function Ew(){let r=/(\d+)\.(\d+)\.(\d+)/g.exec(Wc.release());return r&&r.length===4?parseInt(r[3],10):0}async function Kb(r,t,e,n,i,o=!1){if(!t.shellIntegration.enabled)return{type:"failure",reason:"injectionSettingDisabled"};if(!r.executable)return{type:"failure",reason:"noExecutable"};if(r.isFeatureTerminal&&!r.forceShellIntegration)return{type:"failure",reason:"featureTerminal"};if(r.ignoreShellIntegration)return{type:"failure",reason:"ignoreShellIntegrationFlag"};let s=K?await $b():0;if(K&&s<18309)return{type:"failure",reason:"unsupportedWindowsBuild"};let a=r.args,l=Vr==="win32"?_e(r.executable).toLowerCase():_e(r.executable),c=de(rt.asFileUri("").fsPath),u="injection",d,f={VSCODE_INJECTION:"1"};t.shellIntegration.nonce&&(f.VSCODE_NONCE=t.shellIntegration.nonce);let m=["PATH","VIRTUAL_ENV","HOME","SHELL","PWD"];if(r.shellIntegrationEnvironmentReporting&&(K?(t.windowsUseConptyDll||s>=22631&&l!=="bash.exe")&&(f.VSCODE_SHELL_ENV_REPORTING=m.join(",")):f.VSCODE_SHELL_ENV_REPORTING=m.join(",")),K)return l==="pwsh.exe"||l==="powershell.exe"?(f.VSCODE_A11Y_MODE=t.isScreenReaderOptimized?"1":"0",!a||qb(a)?d=Ae.get("windows-pwsh"):zb(a)&&(d=Ae.get("windows-pwsh-login")),d?(d=[...d],d[d.length-1]=or(d[d.length-1],c,""),f.VSCODE_STABLE=i.quality==="stable"?"1":"0",{type:u,newArgs:d,envMixin:f}):{type:"failure",reason:"unsupportedArgs"}):l==="bash.exe"?(!a||a.length===0?d=Ae.get("bash"):Bc(a)&&(f.VSCODE_SHELL_LOGIN="1",$c(t,f,l),d=Ae.get("bash")),d?(d=[...d],d[d.length-1]=or(d[d.length-1],c),f.VSCODE_STABLE=i.quality==="stable"?"1":"0",{type:u,newArgs:d,envMixin:f}):{type:"failure",reason:"unsupportedArgs"}):(n.warn(`Shell integration cannot be enabled for executable "${r.executable}" and args`,r.args),{type:"failure",reason:"unsupportedShell"});switch(l){case"bash":return!a||a.length===0?d=Ae.get("bash"):Bc(a)&&(f.VSCODE_SHELL_LOGIN="1",$c(t,f,l),d=Ae.get("bash")),d?(d=[...d],d[d.length-1]=or(d[d.length-1],c),f.VSCODE_STABLE=i.quality==="stable"?"1":"0",{type:u,newArgs:d,envMixin:f}):{type:"failure",reason:"unsupportedArgs"};case"fish":return!a||a.length===0?d=Ae.get("fish"):Bc(a)?d=Ae.get("fish-login"):(a===Ae.get("fish")||a===Ae.get("fish-login"))&&(d=a),d?($c(t,f,l),d=[...d],d[d.length-1]=or(d[d.length-1],c),{type:u,newArgs:d,envMixin:f}):{type:"failure",reason:"unsupportedArgs"};case"pwsh":return!a||qb(a)?d=Ae.get("pwsh"):zb(a)&&(d=Ae.get("pwsh-login")),d?(d=[...d],d[d.length-1]=or(d[d.length-1],c,""),f.VSCODE_STABLE=i.quality==="stable"?"1":"0",{type:u,newArgs:d,envMixin:f}):{type:"failure",reason:"unsupportedArgs"};case"zsh":{if(!a||a.length===0?d=Ae.get("zsh"):Bc(a)?(d=Ae.get("zsh-login"),$c(t,f,l)):(a===Ae.get("zsh")||a===Ae.get("zsh-login"))&&(d=a),!d)return{type:"failure",reason:"unsupportedArgs"};d=[...d],d[d.length-1]=or(d[d.length-1],c);let h;try{h=Ro.userInfo().username}catch{h="unknown"}let v=Pw(Ro.tmpdir()),S=B(v,`${h}-${i.applicationName}-zsh`);if(!o)try{await Bb(Vb)(S,960)}catch(I){if(I.message.includes("ENOENT")){try{kw(S)}catch(R){return n.error(`Failed to create zdotdir at ${S}: ${R}`),{type:"failure",reason:"failedToCreateTmpDir"}}try{await Bb(Vb)(S,960)}catch{return n.error(`Failed to set sticky bit on ${S}: ${I}`),{type:"failure",reason:"failedToSetStickyBit"}}}return n.error(`Failed to set sticky bit on ${S}: ${I}`),{type:"failure",reason:"failedToSetStickyBit"}}f.ZDOTDIR=S;let _=e?.ZDOTDIR??Ro.homedir()??"~";f.USER_ZDOTDIR=_;let b=[];return b.push({source:B(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-rc.zsh"),dest:B(S,".zshrc")}),b.push({source:B(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-profile.zsh"),dest:B(S,".zprofile")}),b.push({source:B(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-env.zsh"),dest:B(S,".zshenv")}),b.push({source:B(c,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-login.zsh"),dest:B(S,".zlogin")}),{type:u,newArgs:d,envMixin:f,filesToCopy:b}}}return n.warn(`Shell integration cannot be enabled for executable "${r.executable}" and args`,r.args),{type:"failure",reason:"unsupportedShell"}}function $c(r,t,e){if((Ye||e==="fish")&&r.environmentVariableCollections){let n=Ub(r.environmentVariableCollections),o=new Fc(n).getVariableMap({workspaceFolder:r.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 Ae=new Map;Ae.set("windows-pwsh",["-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);Ae.set("windows-pwsh-login",["-l","-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);Ae.set("pwsh",["-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"{1}']);Ae.set("pwsh-login",["-l","-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"']);Ae.set("zsh",["-i"]);Ae.set("zsh-login",["-il"]);Ae.set("bash",["--init-file","{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh"]);Ae.set("fish",["--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);Ae.set("fish-login",["-l","--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);var Vc=["-login","-l"],Hb=["--login","-l"],Aw=["-i","--interactive"],Hc=["-nol","-nologo"];function zb(r){return Pe(r)?Vc.includes(r.toLowerCase()):r.length===1&&Vc.includes(r[0].toLowerCase())||r.length===2&&(Vc.includes(r[0].toLowerCase())||Vc.includes(r[1].toLowerCase()))&&(Hc.includes(r[0].toLowerCase())||Hc.includes(r[1].toLowerCase()))}function qb(r){return Pe(r)?Hc.includes(r.toLowerCase()):r.length===0||r?.length===1&&Hc.includes(r[0].toLowerCase())}function Bc(r){return Pe(r)||(r=r.filter(t=>!Aw.includes(t.toLowerCase()))),Pe(r)&&Hb.includes(r.toLowerCase())||!Pe(r)&&r.length===1&&Hb.includes(r[0].toLowerCase())}import Dw from"@xterm/headless";var{Terminal:Ow}=Dw,zc=class extends T{constructor(e){super();this._onResponseData=this._register(new x);this.onResponseData=this._onResponseData.event;this._writeBarrier=Promise.resolve();this._isDisposed=!1;this._logService=e.logService;let n={cols:e.cols,rows:e.rows,scrollback:e.scrollback,allowProposedApi:!0};this._terminal=e.terminalFactory?.(n)??new Ow(n),this._register(this._terminal.onData(i=>{this._isCursorPositionReportResponse(i)?(this._logService.debug(`[AgentHostHeadlessTerminal] Forwarding terminal response ${JSON.stringify(i)}`),this._onResponseData.fire(i)):this._logService.debug(`[AgentHostHeadlessTerminal] Dropping terminal response ${JSON.stringify(i)}`)})),this._register({dispose:()=>{this._isDisposed=!0,this._terminal.dispose()}})}writePtyData(e){return this._writeBarrier=this._writeBarrier.catch(()=>{}).then(()=>{if(!this._isDisposed)return new Promise(n=>{try{this._terminal.write(e,n)}catch{n()}})}),this._writeBarrier}whenPtyDataFlushed(){return this._writeBarrier.catch(()=>{})}resize(e,n){this._terminal.resize(e,n)}isBracketedPasteMode(){return this._terminal.modes.bracketedPasteMode}isInAltBuffer(){return this._terminal.buffer.active===this._terminal.buffer.alternate}createAltBufferPromise(e){let n=new fe,i=()=>{n.isSettled||(this._logService.debug("[AgentHostHeadlessTerminal] Detected alternate buffer entry"),n.complete())};return this.isInAltBuffer()?i():e.add(this._terminal.buffer.onBufferChange(()=>{this.isInAltBuffer()&&i()})),n.p}clear(){this.writePtyData("\x1B[2J\x1B[3J\x1B[H")}dispose(){this._isDisposed=!0,super.dispose()}_isCursorPositionReportResponse(e){return/^(?:\x1b\[\??\d+;\d+R)+$/.test(e)}};function qc(r){return mt===1?/^zsh(?:\.exe)?$/i.test(ae.basename(r)):/^zsh$/.test(Z.basename(r))}function jb(r){return r.indexOf("\\")===-1?r:r.replaceAll(/\\(\\|x([0-9a-f]{2}))/gi,(t,e,n)=>n?String.fromCharCode(parseInt(n,16)):e)}function Lw(r){let t=r.indexOf(";");if((t===-1?r.length:t)!==1)return;let e=r[0],n=t===-1?"":r.substring(t+1);switch(e){case"A":return{type:0};case"B":return{type:1};case"C":return{type:2};case"D":{let i=n.length>0?parseInt(n,10):void 0;return{type:3,exitCode:i!==void 0&&!isNaN(i)?i:void 0}}case"E":{let i=n.indexOf(";"),o=jb(i===-1?n:n.substring(0,i)),s=i===-1?void 0:n.substring(i+1);return{type:4,commandLine:o,nonce:s}}case"P":{let i=jb(n),o=i.indexOf("=");return o===-1?void 0:{type:5,key:i.substring(0,o),value:i.substring(o+1)}}default:return}}var pg="\x1B",dg=pg+"]",ug="\x07",Gb=pg+"\\",Kc=class{constructor(){this._pendingOsc="";this._inOsc=!1;this._pendingEscInOsc=!1}parse(t){let e=[];if(!this._inOsc&&t.indexOf(dg)===-1)return{cleanedData:t,events:e};let n="",i=0;for(;i<t.length;){if(this._inOsc){if(this._pendingEscInOsc){if(this._pendingEscInOsc=!1,t[i]==="\\"){i++,this._inOsc=!1;let c=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(c,e,{value:n,append(u){n=u}},Gb);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,i);if(i=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(dg,i);if(o===-1){n+=t.substring(i),i=t.length;continue}n+=t.substring(i,o),i=o+2,this._pendingOsc="",this._inOsc=!0;let s=this._consumeOscBody(t,i);if(i=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(ug,e),i=t.indexOf(pg,e);return n!==-1&&(i===-1||n<i)?(this._pendingOsc+=t.substring(e,n),{nextIndex:n+1,complete:!0,terminator:ug}):i!==-1?i+1>=t.length?(this._pendingOsc+=t.substring(e,i),{nextIndex:t.length,complete:!1,pendingEsc:!0}):(this._pendingOsc+=t.substring(e,i),t[i+1]==="\\"?{nextIndex:i+2,complete:!0,terminator:Gb}:{nextIndex:i,complete:!0}):(this._pendingOsc+=t.substring(e),{nextIndex:t.length,complete:!1})}_handleOscPayload(t,e,n,i=ug){if(t.startsWith("633;")){let o=t.substring(4),s=Lw(o);s&&e.push(s)}else n&&n.append(n.value+dg+t+i)}};var Nw=1e4,Uw=0,fg="\x1B[6n",gg="\x1B[?6n",Fw=["\x1B[?6","\x1B[?","\x1B[6","\x1B[","\x1B"],Po=V("agentHostTerminalManager");function Ww(r,t){if(!t.pendingData&&!r.includes(fg)&&!r.includes(gg)&&!Jb(r))return r;let e=t.pendingData+r,n=Jb(e),i=n?e.substring(0,e.length-n.length):e;return t.pendingData=n,!i.includes(fg)&&!i.includes(gg)?i:i.replaceAll(gg,"").replaceAll(fg,"")}function Jb(r){for(let t of Fw)if(r.endsWith(t))return t;return""}function $w(r,t){return t.forceBracketedPasteMode&&(r=`\x1B[200~${r}\x1B[201~`),r=r.replace(/\r?\n/g,"\r"),t.shouldExecute&&!r.endsWith("\r")&&(r+="\r"),r}var mg;async function Vw(){return mg||(mg=await import("node-pty")),mg}var Eo=class extends T{constructor(e,n,i,o){super();this._stateManager=e;this._logService=n;this._productService=i;this._configurationService=o;this._terminals=new Map;this._register(this._stateManager.onDidEmitEnvelope(s=>{let a=s.action;if(!kc(a))return;let l=s.channel;switch(a.type){case"terminal/input":this._writeInput(l,a.data);break;case"terminal/resized":this._resize(l,a.cols,a.rows);break;case"terminal/claimed":this._setClaim(l,a.claim);break;case"terminal/titleChanged":this._setTitle(l,a.title);break;case"terminal/cleared":this._clearContent(l);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 i=e.channel;if(this._terminals.has(i))throw new Error(`Terminal already exists: ${i}`);let o=await this._resolveCwd(e.cwd,i),s=e.cols??80,a=e.rows??24,l=n?.shell??await this.getDefaultShell(),c=K?"cmd":"xterm-256color";this._logService.info(`[TerminalManager] Creating terminal ${i}: shell=${l}, cwd=${o}, cols=${s}, rows=${a}`);let u=q(),d={...process.env};n?.preventShellHistory&&(d.VSCODE_PREVENT_SHELL_HISTORY="1"),e.claim?.kind==="session"&&qc(l)&&(d.VSCODE_AGENT_ZSH_FIXUPS="1"),n?.nonInteractive&&(d.LC_ALL="C.UTF-8",d.PAGER="",d.GIT_PAGER="",d.GH_PAGER="",d.GIT_TERMINAL_PROMPT="0",d.DEBIAN_FRONTEND="noninteractive");let f=[];Ye&&ty(l).name.match(/(zsh|bash)/)&&(f=["--login"]);let m=await Kb({executable:l,args:f,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(m.type==="injection"){if(this._logService.info(`[TerminalManager] Shell integration injected for ${i}`),m.envMixin)for(let[te,ye]of Object.entries(m.envMixin))ye!==void 0&&(d[te]=ye);if(m.newArgs&&(f=m.newArgs),m.filesToCopy)for(let te of m.filesToCopy)try{await Tr.promises.mkdir(de(te.dest),{recursive:!0}),await Tr.promises.copyFile(te.source,te.dest)}catch{}h={parser:new Kc,nonce:u,commandCounter:0,detectionAvailableEmitted:!1}}else this._logService.info(`[TerminalManager] Shell integration not available for ${i}: ${m.reason}`);let v=await this._spawnPty(l,f,{name:c,cwd:o,env:d,cols:s,rows:a}),S=new z,_=e.claim??{kind:"client",clientId:""},b=S.add(new x),I=S.add(new x),R=S.add(new x),P=S.add(new x),j=S.add(new zc({cols:s,rows:a,scrollback:Uw,logService:this._logService})),E={uri:i,store:S,pty:v,onDataEmitter:b,onExitEmitter:I,onClaimChangedEmitter:R,onCommandFinishedEmitter:P,title:e.name??l,cwd:o,cols:s,rows:a,content:[],contentSize:0,claim:_,commandTracker:h,headlessTerminal:j,terminalQueryFilterState:{pendingData:""}};this._terminals.set(i,E),S.add(j.onResponseData(te=>{this._logService.debug(`[TerminalManager] Writing headless terminal response for ${i}: ${JSON.stringify(te)}`);try{v.write(te)}catch(ye){this._logService.debug(`[TerminalManager] Failed to write headless terminal response for ${i}: ${ye instanceof Error?ye.message:String(ye)}`)}})),S.add(A(()=>{try{v.kill()}catch{}}));let M=new fe,O=v.onData(te=>{E.headlessTerminal?.writePtyData(te),this._handlePtyData(E,te),M.complete()});S.add(A(()=>O.dispose()));let G=v.onExit(te=>{E.exitCode=te.exitCode,E.onExitEmitter.fire(te.exitCode),M.complete(),this._stateManager.dispatchServerAction(i,{type:"terminal/exited",exitCode:te.exitCode}),this._broadcastTerminalList()});if(S.add(A(()=>G.dispose())),!K){let te=setInterval(()=>{let ye=v.process;ye&&ye!==E.title&&(E.title=ye,this._stateManager.dispatchServerAction(i,{type:"terminal/titleChanged",title:ye}),this._broadcastTerminalList())},200);S.add(A(()=>clearInterval(te)))}await Oy([M.p,Xn(Nw)]),this._broadcastTerminalList()}async _spawnPty(e,n,i){return(await Vw()).spawn(e,n,i)}_writeInput(e,n){this.writeInput(e,n)}writeInput(e,n){let i=this._terminals.get(e);i&&i.exitCode===void 0&&i.pty.write(n)}async sendText(e,n,i){let o=this._terminals.get(e),s=!1;i.bracketedPasteMode&&(await o?.headlessTerminal?.whenPtyDataFlushed(),s=!!o?.headlessTerminal?.isBracketedPasteMode()),this.writeInput(e,$w(n,{shouldExecute:i.shouldExecute,forceBracketedPasteMode:s}))}onData(e,n){let i=this._terminals.get(e);return i?i.onDataEmitter.event(n):A(()=>{})}onExit(e,n){let i=this._terminals.get(e);return i?i.onExitEmitter.event(n):A(()=>{})}onClaimChanged(e,n){let i=this._terminals.get(e);return i?i.onClaimChangedEmitter.event(n):A(()=>{})}onCommandFinished(e,n){let i=this._terminals.get(e);return i?i.onCommandFinishedEmitter.event(n):A(()=>{})}createAltBufferPromise(e,n){let i=this._terminals.get(e);return i?.headlessTerminal?i.headlessTerminal.createAltBufferPromise(n):new Promise(()=>{})}getContent(e){let n=this._terminals.get(e);if(n)return n.content.map(i=>i.type==="command"?i.output:i.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,i){let o=this._terminals.get(e);o&&o.exitCode===void 0&&(o.cols=n,o.rows=i,o.pty.resize(n,i),o.headlessTerminal?.resize(n,i))}_setClaim(e,n){let i=this._terminals.get(e);i&&(i.claim=n,i.onClaimChangedEmitter.fire(n),this._broadcastTerminalList())}_setTitle(e,n){let i=this._terminals.get(e);i&&(i.title=n,this._broadcastTerminalList())}_clearContent(e){let n=this._terminals.get(e);n&&(n.content=[],n.contentSize=0,n.headlessTerminal?.clear())}_handlePtyData(e,n){let i=e.commandTracker,o;if(i){let s=i.parser.parse(n);o=s.cleanedData;for(let a of s.events)this._handleOsc633Event(e,i,a)}else o=n;o=Ww(o,e.terminalQueryFilterState),o.length>0&&this._appendToContent(e,o),this._trimContent(e),o.length>0&&(e.onDataEmitter.fire(o),this._stateManager.dispatchServerAction(e.uri,{type:"terminal/data",data:o}))}_handleOsc633Event(e,n,i){switch(n.detectionAvailableEmitted||(n.detectionAvailableEmitted=!0,this._stateManager.dispatchServerAction(e.uri,{type:"terminal/commandDetectionAvailable"})),i.type){case 4:{i.nonce===n.nonce&&(n.pendingCommandLine=i.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(e.uri,{type:"terminal/commandExecuted",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=i.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:i.exitCode,command:a,output:l}),this._stateManager.dispatchServerAction(e.uri,{type:"terminal/commandFinished",commandId:o,exitCode:i.exitCode,durationMs:s});break}case 5:{i.key==="Cwd"&&(e.cwd=i.value,this._stateManager.dispatchServerAction(e.uri,{type:"terminal/cwdChanged",cwd:i.value}));break}}}_appendToContent(e,n){let i=e.content.length>0?e.content[e.content.length-1]:void 0;i?.type==="command"&&!i.isComplete?(i.output+=n,e.contentSize+=n.length):i?.type==="unclassified"?(i.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())}async getDefaultShell(){let e=this._configurationService.getRootValue(Rn,"defaultShell");if(e)try{return await Tr.promises.access(e,Tr.constants.X_OK),e}catch(n){this._logService.warn(`[TerminalManager] Configured defaultShell '${e}' is not accessible, falling back to system shell: ${n instanceof Error?n.message:String(n)}`)}return Nb(mt,process.env)}async _resolveCwd(e,n){let i=e;if(e){let s=y.parse(e);s.scheme==="file"&&s.fsPath&&s.fsPath!=="/"?i=s.fsPath:this._logService.warn(`[TerminalManager] Ignoring non-file cwd for ${n}: ${e}`)}try{if(i&&(await Tr.promises.stat(i)).isDirectory())return i}catch{}let o=process.env.HOME||process.env.USERPROFILE||process.cwd();return this._logService.warn(`[TerminalManager] cwd '${i}' is not accessible, falling back to ${o}`),o}_broadcastTerminalList(){this._stateManager.dispatchServerAction(Ne,{type:"root/terminalsChanged",terminals:this.getTerminalInfos()})}dispose(){for(let e of this._terminals.values())e.store.dispose();this._terminals.clear(),super.dispose()}};Eo=w([C(1,L),C(2,Lt),C(3,Je)],Eo);var jc=V("diffComputeService"),Qb=5e3;var Xb="session-db";function Ni(r,t,e,n){return y.from({scheme:Xb,authority:cn(k.fromString(r)).toString(),path:`/${encodeURIComponent(t)}/${cn(k.fromString(e))}/${n}/${_e(e)}`}).toString()}function Zb(r){let t=y.parse(r);if(t.scheme!==Xb)return;let[,e,n,i]=t.path.split("/");if(!(!e||!n||i!=="before"&&i!=="after"))try{return{sessionUri:Zr(t.authority).toString(),toolCallId:decodeURIComponent(e),filePath:Zr(n).toString(),part:i}}catch{return}}var Mi=class{constructor(t,e,n,i,o){this._sessionUri=t;this._db=e;this._fileService=n;this._logService=i;this._diffComputeService=o;this._pendingEdits=new Map;this._completedEdits=new Map}async trackEditStart(t){let e=this._readFileWithExistence(t),n={beforeContent:k.fromString(""),beforeExisted:!1,snapshotDone:e.then(({content:i,existed:o})=>{n.beforeContent=i,n.beforeExisted=o})};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,beforeExisted:e.beforeExisted,afterContent:n})}async takeCompletedEdit(t,e,n){let i=this._completedEdits.get(n);if(!i)return;this._completedEdits.delete(n);let o=i.beforeContent.buffer,s=i.afterContent.buffer,a=i.beforeContent.toString(),l=i.afterContent.toString(),c=!i.beforeExisted&&s.length>0,u,d;try{let f=await this._diffComputeService.computeDiffCounts(a,l);u=f.added,d=c?0:f.removed}catch(f){this._logService.warn(`[FileEditTracker] Failed to compute diff counts: ${n}`,f)}try{await this._db.storeFileEdit({turnId:t,toolCallId:e,filePath:n,kind:c?"create":"edit",beforeContent:o,afterContent:s,addedLines:u,removedLines:d})}catch(f){this._logService.warn(`[FileEditTracker] Failed to persist file edit to database: ${n}`,f)}return{type:"fileEdit",before:{uri:y.file(n).toString(),content:{uri:Ni(this._sessionUri,e,n,"before")}},after:{uri:y.file(n).toString(),content:{uri:Ni(this._sessionUri,e,n,"after")}},diff:u!==void 0?{added:u,removed:d}:void 0}}async _readFile(t){try{return(await this._fileService.readFile(y.file(t))).value}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${t}`,e),k.fromString("")}}async _readFileWithExistence(t){try{return{content:(await this._fileService.readFile(y.file(t))).value,existed:!0}}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${t}`,e),{content:k.fromString(""),existed:!1}}}};Mi=w([C(2,Se),C(3,L),C(4,jc)],Mi);var eS="git-blob";function Gc(r,t,e){return y.from({scheme:eS,authority:cn(k.fromString(r)).toString(),path:`/${encodeURIComponent(t)}/${cn(k.fromString(e))}/${_e(e)}`}).toString()}function tS(r){let t;try{t=y.parse(r)}catch{return}if(t.scheme!==eS)return;let[,e,n]=t.path.split("/");if(!(!e||!n))try{return{sessionUri:Zr(t.authority).toString(),sha:decodeURIComponent(e),repoRelativePath:Zr(n).toString()}}catch{return}}var Bw={"root/agentsChanged":!1,"root/activeSessionsChanged":!1,"root/terminalsChanged":!1,"root/configChanged":!0,"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/agentChanged":!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/customizationUpdated":!1,"session/customizationRemoved":!1,"session/truncated":!0,"session/isReadChanged":!0,"session/isArchivedChanged":!0,"session/activityChanged":!1,"session/changesetsChanged":!1,"session/configChanged":!0,"session/metaChanged":!1,"changeset/statusChanged":!1,"changeset/fileSet":!1,"changeset/fileRemoved":!1,"changeset/operationsChanged":!1,"changeset/cleared":!1,"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,"resourceWatch/changed":!1};function ci(r,t){let e=`Unhandled action type: ${JSON.stringify(r)}`;(t??console.warn)(e)}function Jc(r,t,e){switch(t.type){case"root/agentsChanged":return{...r,agents:t.agents};case"root/activeSessionsChanged":return{...r,activeSessions:t.activeSessions};case"root/terminalsChanged":return{...r,terminals:t.terminals};case"root/configChanged":return r.config?{...r,config:{...r.config,values:t.replace?{...t.config}:{...r.config.values,...t.config}}}:r;default:return ci(t,e),r}}function La(r){return{toolCallId:r.toolCallId,toolName:r.toolName,displayName:r.displayName,toolClientId:r.toolClientId,_meta:r._meta}}function Hw(r,t){if(!(!t||!r))return r.find(e=>e.id===t)}function zw(r){return r.activeTurn?r.activeTurn.responseParts.some(t=>t.kind==="toolCall"&&(t.toolCall.status==="pending-confirmation"||t.toolCall.status==="pending-result-confirmation")):!1}var qw=31;function Yc(r,t,e){return e?r|t:r&~t}function Ao(r,t){let e;return t?e=t:(r.inputRequests?.length??0)>0||zw(r)?e=24:r.activeTurn?e=8:e=1,r.summary.status&~qw|e}function Qc(r){let t=Ao(r);return t===r.summary.status?r:{...r,summary:{...r.summary,status:t}}}function hg(r,t,e,n,i){if(!r.activeTurn||r.activeTurn.id!==t)return r;let o=r.activeTurn,s=o.responseParts.map(c=>{if(c.kind!=="toolCall")return c;let u=c.toolCall;return u.status==="completed"||u.status==="cancelled"?c:{kind:"toolCall",toolCall:{status:"cancelled",...La(u),invocationMessage:u.status==="streaming"?u.invocationMessage??"":u.invocationMessage,toolInput:u.status==="streaming"?void 0:u.toolInput,reason:"skipped"}}}),a={id:o.id,message:o.message,responseParts:s,usage:o.usage,state:e,error:i},l={...r,turns:[...r.turns,a],activeTurn:void 0,summary:{...r.summary,modifiedAt:Date.now()}};return delete l.inputRequests,{...l,summary:{...l.summary,status:Ao(l,n)}}}function Kw(r,t){let e=r.inputRequests??[],n=e.findIndex(s=>s.id===t.id),i=[...e];if(n>=0){let s=t.answers??i[n].answers;i[n]={...t,answers:s}}else i.push(t);let o={...r,inputRequests:i};return{...o,summary:{...o.summary,status:Yc(Ao(o),32,!1),modifiedAt:Date.now()}}}function ko(r,t,e,n){let i=r.activeTurn;if(!i||i.id!==t)return r;let o=!1,s=i.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?{...r,activeTurn:{...i,responseParts:s}}:r}function nS(r,t,e,n){let i=r.activeTurn;if(!i||i.id!==t)return r;let o=!1,s=i.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?{...r,activeTurn:{...i,responseParts:s}}:r}function Xc(r,t,e){switch(t.type){case"session/ready":return{...r,lifecycle:"ready"};case"session/creationFailed":return{...r,lifecycle:"creationFailed",creationError:t.error};case"session/turnStarted":{let n={...r,activeTurn:{id:t.turnId,message:t.message,responseParts:[],usage:void 0}};if(n={...n,summary:{...n.summary,status:Yc(Ao(n),32,!1),modifiedAt:Date.now()}},t.queuedMessageId&&(n.steeringMessage?.id===t.queuedMessageId&&(n={...n,steeringMessage:void 0}),n.queuedMessages)){let i=n.queuedMessages.filter(o=>o.id!==t.queuedMessageId);n={...n,queuedMessages:i.length>0?i:void 0}}return n}case"session/delta":return nS(r,t.turnId,t.partId,n=>n.kind==="markdown"?{...n,content:n.content+t.content}:n);case"session/responsePart":return!r.activeTurn||r.activeTurn.id!==t.turnId?r:{...r,activeTurn:{...r.activeTurn,responseParts:[...r.activeTurn.responseParts,t.part]}};case"session/turnComplete":return hg(r,t.turnId,"complete");case"session/turnCancelled":return hg(r,t.turnId,"cancelled");case"session/error":return hg(r,t.turnId,"error",2,t.error);case"session/toolCallStart":return!r.activeTurn||r.activeTurn.id!==t.turnId?r:{...r,activeTurn:{...r.activeTurn,responseParts:[...r.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 ko(r,t.turnId,t.toolCallId,n=>n.status!=="streaming"?n:{...n,partialInput:(n.partialInput??"")+t.content,invocationMessage:t.invocationMessage??n.invocationMessage});case"session/toolCallReady":return Qc(ko(r,t.turnId,t.toolCallId,n=>{if(n.status!=="streaming"&&n.status!=="running")return n;let i=La(n);return t.confirmed?{status:"running",...i,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:t.confirmed}:{status:"pending-confirmation",...i,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmationTitle:t.confirmationTitle,edits:t.edits,editable:t.editable,...t.options?{options:t.options}:{}}}));case"session/toolCallConfirmed":return Qc(ko(r,t.turnId,t.toolCallId,n=>{if(n.status!=="pending-confirmation")return n;let i=La(n),o=Hw(n.options,t.selectedOptionId);return t.approved?{status:"running",...i,invocationMessage:n.invocationMessage,toolInput:t.editedToolInput??n.toolInput,confirmed:t.confirmed,...o?{selectedOption:o}:{}}:{status:"cancelled",...i,invocationMessage:n.invocationMessage,toolInput:n.toolInput,reason:t.reason,reasonMessage:t.reasonMessage,userSuggestion:t.userSuggestion,...o?{selectedOption:o}:{}}}));case"session/toolCallComplete":return Qc(ko(r,t.turnId,t.toolCallId,n=>{if(n.status!=="running"&&n.status!=="pending-confirmation")return n;let i=La(n),o=n.status==="running"?n.confirmed:"not-needed",s=n.status==="running"?n.selectedOption:void 0;return t.requiresResultConfirmation?{status:"pending-result-confirmation",...i,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:o,...s?{selectedOption:s}:{},...t.result}:{status:"completed",...i,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:o,...s?{selectedOption:s}:{},...t.result}}));case"session/toolCallResultConfirmed":return Qc(ko(r,t.turnId,t.toolCallId,n=>{if(n.status!=="pending-result-confirmation")return n;let i=La(n);return t.approved?{status:"completed",...i,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:n.confirmed,...n.selectedOption?{selectedOption:n.selectedOption}:{},success:n.success,pastTenseMessage:n.pastTenseMessage,content:n.content,structuredContent:n.structuredContent,error:n.error}:{status:"cancelled",...i,invocationMessage:n.invocationMessage,toolInput:n.toolInput,reason:"result-denied",...n.selectedOption?{selectedOption:n.selectedOption}:{}}}));case"session/toolCallContentChanged":return ko(r,t.turnId,t.toolCallId,n=>n.status!=="running"?n:{...n,content:t.content});case"session/titleChanged":return{...r,summary:{...r.summary,title:t.title,modifiedAt:Date.now()}};case"session/usage":return!r.activeTurn||r.activeTurn.id!==t.turnId?r:{...r,activeTurn:{...r.activeTurn,usage:t.usage}};case"session/reasoning":return nS(r,t.turnId,t.partId,n=>n.kind==="reasoning"?{...n,content:n.content+t.content}:n);case"session/modelChanged":return{...r,summary:{...r.summary,model:t.model,modifiedAt:Date.now()}};case"session/agentChanged":return{...r,summary:{...r.summary,agent:t.agent,modifiedAt:Date.now()}};case"session/isReadChanged":return{...r,summary:{...r.summary,status:Yc(r.summary.status,32,t.isRead)}};case"session/isArchivedChanged":return{...r,summary:{...r.summary,status:Yc(r.summary.status,64,t.isArchived)}};case"session/activityChanged":return{...r,summary:{...r.summary,activity:t.activity}};case"session/changesetsChanged":{let{changesets:n,...i}=r.summary,o=t.changesets?{...i,changesets:t.changesets}:i;return{...r,summary:o}}case"session/configChanged":return r.config?{...r,config:{...r.config,values:t.replace?{...t.config}:{...r.config.values,...t.config}},summary:{...r.summary,modifiedAt:Date.now()}}:r;case"session/metaChanged":return{...r,_meta:t._meta};case"session/serverToolsChanged":return{...r,serverTools:t.tools};case"session/activeClientChanged":return{...r,activeClient:t.activeClient??void 0};case"session/activeClientToolsChanged":return r.activeClient?{...r,activeClient:{...r.activeClient,tools:t.tools}}:r;case"session/customizationsChanged":return{...r,customizations:t.customizations};case"session/customizationToggled":{let n=r.customizations;if(!n)return r;let i=n.findIndex(s=>s.id===t.id);if(i<0)return r;let o=[...n];return o[i]={...n[i],enabled:t.enabled},{...r,customizations:o}}case"session/customizationUpdated":{let n=r.customizations??[],i=n.findIndex(s=>s.id===t.customization.id);if(i<0)return{...r,customizations:[...n,t.customization]};let o=[...n];return o[i]=t.customization,{...r,customizations:o}}case"session/customizationRemoved":{let n=r.customizations;if(!n)return r;let i=n.findIndex(a=>a.id===t.id);if(i>=0){let a=n.slice();return a.splice(i,1),{...r,customizations:a}}let o=!1,s=n.map(a=>{let l=a.children;if(!l)return a;let c=l.findIndex(d=>d.id===t.id);if(c<0)return a;o=!0;let u=l.slice();return u.splice(c,1),{...a,children:u}});return o?{...r,customizations:s}:r}case"session/truncated":{let n;if(t.turnId===void 0)n=[];else{let o=r.turns.findIndex(s=>s.id===t.turnId);if(o<0)return r;n=r.turns.slice(0,o+1)}let i={...r,turns:n,activeTurn:void 0,summary:{...r.summary,modifiedAt:Date.now()}};return delete i.inputRequests,{...i,summary:{...i.summary,status:Ao(i)}}}case"session/inputRequested":return Kw(r,t.request);case"session/inputAnswerChanged":{let n=r.inputRequests,i=n?.findIndex(l=>l.id===t.requestId)??-1;if(!n||i<0)return r;let o=n[i],s={...o.answers??{}};t.answer===void 0?delete s[t.questionId]:s[t.questionId]=t.answer;let a=[...n];return a[i]={...o,answers:Object.keys(s).length>0?s:void 0},{...r,inputRequests:a,summary:{...r.summary,modifiedAt:Date.now()}}}case"session/inputCompleted":{let n=r.inputRequests;if(!n?.some(s=>s.id===t.requestId))return r;let i=n.filter(s=>s.id!==t.requestId),o={...r};return i.length>0?o.inputRequests=i:delete o.inputRequests,{...o,summary:{...o.summary,status:Ao(o),modifiedAt:Date.now()}}}case"session/pendingMessageSet":{let n={id:t.id,message:t.message};if(t.kind==="steering")return{...r,steeringMessage:n};let i=r.queuedMessages??[],o=i.findIndex(s=>s.id===t.id);if(o>=0){let s=[...i];return s[o]=n,{...r,queuedMessages:s}}return{...r,queuedMessages:[...i,n]}}case"session/pendingMessageRemoved":{if(t.kind==="steering")return!r.steeringMessage||r.steeringMessage.id!==t.id?r:{...r,steeringMessage:void 0};let n=r.queuedMessages;if(!n)return r;let i=n.filter(o=>o.id!==t.id);return i.length===n.length?r:{...r,queuedMessages:i.length>0?i:void 0}}case"session/queuedMessagesReordered":{let n=r.queuedMessages;if(!n)return r;let i=new Map(n.map(a=>[a.id,a])),o=new Set,s=t.order.filter(a=>i.has(a)&&!o.has(a)?(o.add(a),!0):!1).map(a=>i.get(a));for(let a of n)o.has(a.id)||s.push(a);return{...r,queuedMessages:s}}default:return ci(t,e),r}}function Zc(r,t,e){switch(t.type){case"changeset/statusChanged":{if(t.status==="error")return{...r,status:t.status,error:t.error};let{error:n,...i}=r;return{...i,status:t.status}}case"changeset/fileSet":{let n=r.files.findIndex(o=>o.id===t.file.id);if(n<0)return{...r,files:[...r.files,t.file]};let i=[...r.files];return i[n]=t.file,{...r,files:i}}case"changeset/fileRemoved":{let n=r.files.findIndex(o=>o.id===t.fileId);if(n<0)return r;let i=[...r.files];return i.splice(n,1),{...r,files:i}}case"changeset/operationsChanged":{if(t.operations===void 0){let{operations:n,...i}=r;return i}return{...r,operations:t.operations}}case"changeset/cleared":return r.files.length===0?r:{...r,files:[]};default:return ci(t,e),r}}var Gw=500,ed=class{constructor(t={}){this._states=new Map;this._lru=new Ms;this._softLimit=Math.max(0,t.softLimit??Gw),this._canEvict=t.canEvict??(()=>!0)}keys(){return this._states.keys()}has(t){return this._states.has(t)}get(t){return this._touch(t),this._states.get(t)}set(t,e){this._states.set(t,e),this._touch(t),this._evictIfOverLimit()}delete(t){this._states.delete(t),this._lru.delete(t)}register(t,e="computing"){if(this._states.has(t)){this._touch(t);return}this.set(t,{status:e,files:[]})}trimEvictableEntries(){this._evictIfOverLimit()}_touch(t){this._states.has(t)&&this._lru.set(t,!0,2)}_evictIfOverLimit(){if(this._softLimit===0){for(let t of[...this._lru.keys()])this._canEvict(t)&&this.delete(t);return}for(let t of[...this._lru.keys()]){if(this._states.size<=this._softLimit)return;if(!this._states.has(t)){this._lru.delete(t);continue}this._canEvict(t)&&this.delete(t)}}};function Jw(r,t){if(r===t)return!0;if(!r||!t||r.length!==t.length)return!1;for(let e=0;e<r.length;e++){let n=r[e],i=t[e];if(n.label!==i.label||n.uriTemplate!==i.uriTemplate||n.description!==i.description||n.additions!==i.additions||n.deletions!==i.deletions||n.files!==i.files)return!1}return!0}var Do=class extends T{constructor(e,n={}){super();this._logService=e;this._serverSeq=0;this._sessionStates=new Map;this._sessionsWithActiveTurn=new Set;this._lastNotifiedSummaries=new Map;this._dirtySummaries=new Set;this._summaryNotifyScheduler=this._register(new wi(()=>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._onDidChangeSessionActiveTurn=this._register(new x);this.onDidChangeSessionActiveTurn=this._onDidChangeSessionActiveTurn.event;this._log=e=>this._logService.warn(`[AgentHostStateManager] ${e}`);this._changesets=new ed(n.changesetStateRetention),this._rootState=_b(),this._rootState={...this._rootState,config:{schema:Pa.toProtocol(),values:Pa.validateOrDefault({},{permissions:{allow:[],deny:[]},[Ea]:Eb(3)})}}}get hasActiveSessions(){return this._sessionsWithActiveTurn.size>0}get rootState(){return this._rootState}getSessionState(e){return this._sessionStates.get(e)}get serverSeq(){return this._serverSeq}getSessionUris(){return[...this._sessionStates.keys()]}getSessionUrisWithPrefix(e){let n=[];for(let i of this._sessionStates.keys())i.startsWith(e)&&n.push(i);return n}getSnapshot(e){if(xa(e))return{resource:Ne,state:this._rootState,fromSeq:this._serverSeq};let n=this._changesets.get(e);if(n)return{resource:e,state:n,fromSeq:this._serverSeq};let i=this._sessionStates.get(e);if(i)return{resource:e,state:i,fromSeq:this._serverSeq}}getChangesetState(e){return this._changesets.get(e)}onChangesetLivenessChanged(){this._changesets.trimEvictableEntries()}createSession(e,n){let i=e.resource;if(this._sessionStates.has(i))return this._logService.warn(`[AgentHostStateManager] Session already exists: ${i}`),this._sessionStates.get(i);let o=eg(e);return this._sessionStates.set(i,o),this._logService.trace(`[AgentHostStateManager] Created session: ${i}`),n?.emitNotification!==!1&&(this._lastNotifiedSummaries.set(i,e),this._onDidEmitNotification.fire({type:"root/sessionAdded",channel:Ne,summary:e})),o}markSessionPersisted(e,n){let i=e.toString(),o=this._sessionStates.get(i);if(!o){this._logService.warn(`[AgentHostStateManager] markSessionPersisted: unknown session ${i}`);return}this._lastNotifiedSummaries.has(i)||(o.summary=n,this._lastNotifiedSummaries.set(i,n),this._onDidEmitNotification.fire({type:"root/sessionAdded",channel:Ne,summary:n}))}restoreSession(e,n){let i=e.resource;if(this._sessionStates.has(i))return this._logService.warn(`[AgentHostStateManager] Session already exists (restore): ${i}`),this._sessionStates.get(i);let o={...eg(e),lifecycle:"ready",turns:n};return this._sessionStates.set(i,o),this._lastNotifiedSummaries.set(i,e),this._logService.trace(`[AgentHostStateManager] Restored session: ${i} (${n.length} turns)`),o}removeSession(e){this._sessionStates.get(e)&&(this._dirtySummaries.has(e)&&this._flushSummaryNotificationFor(e),this._sessionsWithActiveTurn.delete(e)&&(this._onDidChangeSessionActiveTurn.fire({session:e,active:!1}),this.dispatchServerAction(Ne,{type:"root/activeSessionsChanged",activeSessions:this._sessionsWithActiveTurn.size})),this._sessionStates.delete(e),this._lastNotifiedSummaries.delete(e),this._dirtySummaries.delete(e),this._logService.trace(`[AgentHostStateManager] Removed session: ${e}`))}deleteSession(e){let n=this._lastNotifiedSummaries.has(e);this._dirtySummaries.delete(e),this.disposeSessionChangesets(e),this.removeSession(e),n&&this._onDidEmitNotification.fire({type:"root/sessionRemoved",channel:Ne,session:e})}setSessionMeta(e,n){this.dispatchServerAction(e,{type:"session/metaChanged",_meta:n})}registerChangeset(e,n="computing"){return this._changesets.register(e,n),e}setSessionChangesets(e,n){let i=this._sessionStates.get(e);if(!i){this._logService.warn(`[AgentHostStateManager] setSessionChangesets: unknown session ${e}`);return}if(Jw(i.summary.changesets,n))return;let o=n?[...n]:void 0;this.dispatchServerAction(e,{type:"session/changesetsChanged",changesets:o})}disposeChangeset(e){this._changesets.has(e)&&(this.dispatchServerAction(e,{type:"changeset/cleared"}),this._changesets.delete(e))}disposeSessionChangesets(e){let n=[];for(let i of this._changesets.keys()){let o=Tn(i);o&&o.sessionUri===e&&n.push(i)}for(let i of n)this.disposeChangeset(i)}getActiveTurnId(e){return this._sessionStates.get(e)?.activeTurn?.id}dispatchServerAction(e,n){this._applyAndEmit(e,n,void 0)}dispatchClientAction(e,n,i){return this._applyAndEmit(e,n,i)}_applyAndEmit(e,n,i){let o;if(nb(n)){if(n.type==="root/configChanged"&&this._rootState.config){let a=this._rootState.config.values,l=n.config;if(n.replace?Me(a,l):Me({...a,...l},a))return this._rootState}this._rootState=Jc(this._rootState,n,this._log),o=this._rootState}if(Pc(n)){let a=n,l=e,c=this._sessionStates.get(l);if(c){let u=Xc(c,a,this._log);this._sessionStates.set(l,u),c.summary!==u.summary&&(this._dirtySummaries.add(l),this._summaryNotifyScheduler.schedule());let d=!!c.activeTurn,f=!!u.activeTurn;d!==f&&(f?this._sessionsWithActiveTurn.add(l):this._sessionsWithActiveTurn.delete(l),this._onDidChangeSessionActiveTurn.fire({session:l,active:f}),this.dispatchServerAction(Ne,{type:"root/activeSessionsChanged",activeSessions:this._sessionsWithActiveTurn.size})),o=u}else this._logService.warn(`[AgentHostStateManager] Action for unknown session: ${l}, type=${n.type}`)}if(ib(n)){let a=n,l=e,c=this._changesets.get(l);if(!c){this._logService.warn(`[AgentHostStateManager] Action for unknown changeset: ${l}, type=${n.type}`);return}let u=Zc(c,a,this._log);u!==c&&this._changesets.set(l,u),o=u}let s={channel:e,action:n,serverSeq:++this._serverSeq,origin:i};return this._logService.trace(`[AgentHostStateManager] Emitting envelope: seq=${s.serverSeq}, type=${n.type}${i?`, origin=${i.clientId}:${i.clientSeq}`:""}`),this._onDidEmitEnvelope.fire(s),o}_flushSummaryNotifications(){for(let e of this._dirtySummaries)this._flushSummaryNotificationFor(e);this._dirtySummaries.clear()}_flushSummaryNotificationFor(e){let n=this._sessionStates.get(e),i=this._lastNotifiedSummaries.get(e);if(!n||!i||n.summary===i)return;let o=n.summary,s={};o.title!==i.title&&(s.title=o.title),o.status!==i.status&&(s.status=o.status),o.activity!==i.activity&&(s.activity=o.activity),o.modifiedAt!==i.modifiedAt&&(s.modifiedAt=o.modifiedAt),o.project!==i.project&&(s.project=o.project),o.model!==i.model&&(s.model=o.model),o.workingDirectory!==i.workingDirectory&&(s.workingDirectory=o.workingDirectory),o.changesets!==i.changesets&&(s.changesets=o.changesets),this._lastNotifiedSummaries.set(e,o),Object.keys(s).length>0&&this._onDidEmitNotification.fire({type:"root/sessionSummaryChanged",channel:Ne,session:e,changes:s})}};Do=w([C(0,L)],Do);import*as td from"child_process";var Ma=V("environmentService"),Ui=Ma;var Nt=V("agentHostGitService"),nd="agentHost.diffBaseBranch";function iS(r){return r==="main"?0:r==="master"?1:2}function Qw(r,t){let e=t?.query?.toLowerCase(),n=e?r.filter(i=>i.toLowerCase().includes(e)):[...r];return n.sort((i,o)=>iS(i)-iS(o)),t?.limit?n.slice(0,t.limit):n}var Oo=class{constructor(t,e,n){this._fileService=t;this._environmentService=e;this._logService=n}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/remotes/origin/${n}`])!==void 0?`origin/${n}`:await this._runGit(t,["show-ref","--verify","--quiet",`refs/heads/${n}`])!==void 0?n:void 0}}async getBranches(t,e){let n=["for-each-ref","--format=%(refname:short)","--sort=-committerdate"];n.push("refs/heads");let i=await this._runGit(t,n);if(!i)return[];let o=i.split(/\r?\n/g).map(s=>s.trim()).filter(s=>s.length>0);return Qw(o,e)}async getRepositoryRoot(t){let e=(await this._runGit(t,["rev-parse","--show-toplevel"]))?.trim();return e?y.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=>y.file(n.substring(9))):[]}async addWorktree(t,e,n,i){let o=await this._resolveRemoteTrackingBranch(t,i)??i;await this._runGit(t,["worktree","add","--no-track","-b",n,e.fsPath,o],{timeout:6e4,throwOnError:!0})}async addExistingWorktree(t,e,n){await this._runGit(t,["worktree","add",e.fsPath,n],{timeout:6e4,throwOnError:!0})}async removeWorktree(t,e){await this._runGit(t,["worktree","remove","--force",e.fsPath],{timeout:6e4,throwOnError:!0})}async branchExists(t,e){return await this._runGit(t,["show-ref","--verify","--quiet",`refs/heads/${e}`])!==void 0}async hasUncommittedChanges(t){let e=await this._runGit(t,["status","--porcelain"]);return!!e&&e.trim().length>0}async computeSessionFileDiffs(t,e){if((await this._runGit(t,["rev-parse","--is-inside-work-tree"]))?.trim()!=="true")return;let i=(await this._runGit(t,["rev-parse","--show-toplevel"]))?.trim();if(!i)return;let o=y.file(i),s;if(e.baseBranch){let u=await this._resolveRemoteTrackingBranch(o,e.baseBranch)??e.baseBranch;s=(await this._runGit(o,["merge-base","HEAD",u]))?.trim()}s||(s=(await this._runGit(o,["rev-parse","HEAD"]))?.trim()),s||(s=yg);let a=await this._runGit(o,["status","--porcelain=v1","-z","--untracked-files=all"]),l=Zw(a),c;if(l.length===0?c=await this._runGit(o,["diff","--raw","--numstat","--diff-filter=ADMR","-z",s,"--"]):c=await this._runWithTempIndex(o,s),c!==void 0)return rS(c,o,e.sessionUri,s)}async _runWithTempIndex(t,e){let n=y.joinPath(this._environmentService.tmpDir,`agent-host-git-diff-${q()}`);await this._fileService.createFolder(n);let o={GIT_INDEX_FILE:y.joinPath(n,"index").fsPath};o.COMMAND_HOOK_LOCK="1";try{return await this._runGit(t,["read-tree","HEAD"],{env:o})===void 0&&await this._runGit(t,["read-tree",yg],{env:o}),await this._runGit(t,["add","-A","--",":/"],{env:o}),await this._runGit(t,["diff","--cached","--raw","--numstat","--diff-filter=ADMR","-z",e,"--"],{env:o})}finally{try{await this._fileService.del(n,{recursive:!0,useTrash:!1})}catch{}}}async _resolveRemoteTrackingBranch(t,e){let n=`origin/${e}`;return await this._runGit(t,["show-ref","--verify","--quiet",`refs/remotes/${n}`])!==void 0?n:void 0}async showBlob(t,e,n){if(!(!/^[0-9a-f]{4,64}$/.test(e)||(await this._runGit(t,["rev-parse","--is-inside-work-tree"]))?.trim()!=="true"))return new Promise(o=>{td.execFile("git",["show",`${e}:${n}`],{cwd:t.fsPath,timeout:5e3,encoding:"buffer",maxBuffer:32*1024*1024},(s,a)=>{if(s){o(void 0);return}o(k.wrap(a))})})}async getSessionGitState(t){return this._computeSessionGitState(t)}async captureWorkingTreeAsTree(t){if((await this._runGit(t,["rev-parse","--is-inside-work-tree"]))?.trim()!=="true")return;let n=(await this._runGit(t,["rev-parse","--show-toplevel"]))?.trim();if(!n)return;let i=y.file(n),o=y.joinPath(this._environmentService.tmpDir,`agent-host-checkpoint-${q()}`);await this._fileService.createFolder(o);let a={GIT_INDEX_FILE:y.joinPath(o,"index").fsPath,COMMAND_HOOK_LOCK:"1"};try{return await this._runGit(i,["read-tree","HEAD"],{env:a})===void 0&&await this._runGit(i,["read-tree",yg],{env:a}),await this._runGit(i,["add","-A","--",":/"],{env:a}),(await this._runGit(i,["write-tree"],{env:a}))?.trim()||void 0}finally{try{await this._fileService.del(o,{recursive:!0,useTrash:!1})}catch{}}}async commitTree(t,e,n,i){let o=["commit-tree",e];return n&&o.push("-p",n),o.push("-m",i),(await this._runGit(t,o,{throwOnError:!0}))?.trim()||void 0}async updateRef(t,e,n){await this._runGit(t,["update-ref",e,n],{throwOnError:!0})}async deleteRefs(t,e){if(e.length===0)return;let n=e.map(i=>`delete ${i}\0\0`).join("");await new Promise(i=>{td.execFile("git",["update-ref","--stdin","-z"],{cwd:t.fsPath,timeout:1e4},()=>{i()}).stdin?.end(n)})}async revParse(t,e){return(await this._runGit(t,["rev-parse","--verify","--quiet",e]))?.trim()||void 0}async computeFileDiffsBetweenRefs(t,e){let n=(await this._runGit(t,["rev-parse","--show-toplevel"]))?.trim();if(!n)return;let i=y.file(n),o=(await this._runGit(i,["rev-parse","--verify","--quiet",e.fromRef]))?.trim(),s=(await this._runGit(i,["rev-parse","--verify","--quiet",e.toRef]))?.trim();if(!o||!s)return;let a=await this._runGit(i,["diff","--raw","--numstat","--diff-filter=ADMR","-z",o,s,"--"]);if(a!==void 0)return rS(a,i,e.sessionUri,o,s)}async _computeSessionGitState(t){if((await this._runGit(t,["rev-parse","--is-inside-work-tree"]))?.trim()!=="true")return;let[n,i,o]=await Promise.all([this._runGit(t,["status","-b","--porcelain=v2"]),this._runGit(t,["remote","-v"]),this._runGit(t,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])]),s=e0(n),a=t0(i),l=r0(o),c=n0(i),u=s.outgoingChanges;if(u===void 0&&l&&s.branchName&&s.branchName!==l){let f=await this._runGit(t,["rev-list","--count",`${l}..HEAD`]),m=f===void 0?NaN:Number(f.trim());Number.isFinite(m)&&(u=m)}let d={hasGitHubRemote:a,branchName:s.branchName,baseBranchName:l,upstreamBranchName:s.upstreamBranchName,incomingChanges:s.incomingChanges,outgoingChanges:u,uncommittedChanges:s.uncommittedChanges,githubOwner:c?.owner,githubRepo:c?.repo};return o0(d)}_runGit(t,e,n){return new Promise((i,o)=>{let s=n?.env?{...process.env,...n.env}:void 0,a=n?.timeout??5e3,l=!1,c=td.execFile("git",[...e],{cwd:t.fsPath,env:s,maxBuffer:n?.maxBuffer??32*1024*1024},(d,f,m)=>{if(d){if(m&&this._logService.warn(`[agentHostGitService] git ${e.join(" ")} failed; full stderr:
${m}`),n?.throwOnError){o(new Error(Yw(e,a,l,d,m),{cause:d}));return}i(void 0);return}i(f)}),u=setTimeout(()=>{l=!0,c.kill()},a);c.on("exit",()=>clearTimeout(u))})}};Oo=w([C(0,Se),C(1,Ui),C(2,L)],Oo);function Yw(r,t,e,n,i){let o=r[0]??"(unknown)",s;e?s=`git ${o} timed out after ${t}ms`:n.killed&&n.signal?s=`git ${o} killed by ${n.signal}`:typeof n.code=="number"?s=`git ${o} exited with code ${n.code}`:s=n.message;let a=Xw(i);return a?`${s}: ${a}`:s}function Xw(r){if(!r)return"";let t=r.split(/[\r\n]+/g).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return"";let e=t[t.length-1],n=200;return e.length>n?`${e.slice(0,n-1)}\u2026`:e}var yg="4b825dc642cb6eb9a060e54bf8d69288fbee4904";function Zw(r){if(!r)return[];let t=[],e=r.split("\0");for(let n=0;n<e.length;n++){let i=e[n];if(!i)continue;let o=i.substring(0,2),s=i.substring(3);o==="??"?t.push(s):(o[0]==="R"||o[0]==="C")&&n++}return t}function rS(r,t,e,n,i){let o=r.split("\0"),s=[],a=new Map,l=0;for(;l<o.length;){let c=o[l++];if(c)if(c.startsWith(":")){let d=c.split(" ")[4]??"",f=o[l++];if(!f)continue;switch(d[0]){case"A":s.push({kind:"create",newPath:f});break;case"M":s.push({kind:"edit",oldPath:f,newPath:f});break;case"D":s.push({kind:"delete",oldPath:f});break;case"R":{let m=o[l++];if(!m)continue;s.push({kind:"rename",oldPath:f,newPath:m});break}default:break}}else{let[u,d,f]=c.split("	"),m;if(f===""||f===void 0){let h=o[l++];m=o[l++]??h??""}else m=f;if(!m)continue;a.set(m,{added:u==="-"?0:Number(u)||0,removed:d==="-"?0:Number(d)||0})}}return s.map(c=>{let u=a.get(c.newPath??c.oldPath??""),d=c.kind!=="create",f=c.kind!=="delete";return{...d&&c.oldPath?{before:{uri:y.joinPath(t,c.oldPath).toString(),content:{uri:Gc(e,n,c.oldPath)}}}:{},...f&&c.newPath?{after:i!==void 0?{uri:Gc(e,i,c.newPath),content:{uri:Gc(e,i,c.newPath)}}:{uri:y.joinPath(t,c.newPath).toString(),content:{uri:y.joinPath(t,c.newPath).toString()}}}:{},diff:{added:u?.added??0,removed:u?.removed??0}}})}function e0(r){if(!r)return{};let t,e,n,i,o=0;for(let s of r.split(/\r?\n/g)){let a=s.trimEnd();if(a)if(a.startsWith("# branch.head ")){let l=a.substring(14).trim();t=l==="(detached)"?void 0:l}else if(a.startsWith("# branch.upstream "))e=a.substring(18).trim();else if(a.startsWith("# branch.ab ")){let l=/^# branch\.ab \+(\d+) -(\d+)$/.exec(a);l&&(n=Number(l[1]),i=Number(l[2]))}else a.startsWith("#")||o++}return{branchName:t,upstreamBranchName:e,outgoingChanges:n,incomingChanges:i,uncommittedChanges:o}}function t0(r){if(r!==void 0)return r.trim()?/github\.com[:\/]/i.test(r):!1}function n0(r){if(!r)return;let t=[];for(let n of r.split(/\r?\n/)){let i=n.trim();if(!i)continue;let o=/^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(i);o&&t.push({name:o[1],url:o[2]})}if(t.length===0)return;let e=[...t.filter(n=>n.name==="origin"),...t.filter(n=>n.name!=="origin")];for(let{url:n}of e){let i=i0(n);if(i)return i}}function i0(r){let t=/^[^@\s]+@github\.com:([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(r);if(t)return{owner:t[1],repo:t[2]};if(t=/^[a-z+]+:\/\/(?:[^@\/\s]+@)?github\.com(?::\d+)?\/([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(r),t)return{owner:t[1],repo:t[2]}}function r0(r){let t=r?.trim();if(!t)return;let e="refs/remotes/origin/";return t.startsWith(e)?t.substring(e.length):t}function o0(r){let t={};for(let[e,n]of Object.entries(r))n!==void 0&&(t[e]=n);return t}var En=V("agentHostCheckpointService"),Lo="checkpoint.baseRef";function vg(r,t){return`refs/agents/${r}/checkpoints/turn/${t}`}var oS={_serviceBrand:void 0,captureBaseline:async()=>{},captureTurnCheckpoint:async()=>{},getTurnCheckpointPair:async()=>{},disposeSessionData:async()=>{}};import{Worker as s0}from"worker_threads";var Fi=class extends T{constructor(e){super();this._logService=e;this._workerFailures=0;this._nextId=1;this._pending=new Map}async computeDiffCounts(e,n,i=Qb){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,i]})}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=rt.asFileUri("vs/platform/agentHost/node/diffWorkerMain.js").fsPath,n=new s0(e,{name:"Diff compute worker"});n.on("message",i=>{let o=this._pending.get(i.id);if(o)if(this._pending.delete(i.id),i.err){let s=new Error(i.err.message);i.err.stack&&(s.stack=i.err.stack),o.reject(s)}else o.resolve(i.res)}),n.on("error",i=>{this._logService.error("[DiffComputeService] Worker error",i);for(let[,o]of this._pending)o.reject(i);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()}};Fi=w([C(0,L)],Fi);function sS(r){return r.after?.uri??r.before?.uri}function aS(r,t,e,n){let i=t.firstKind!=="create",o=t.lastKind!=="delete";return{...i?{before:{uri:y.file(t.firstFilePath).toString(),content:{uri:Ni(r,t.firstToolCallId,t.firstFilePath,"before")}}}:{},...o?{after:{uri:y.file(t.terminalPath).toString(),content:{uri:Ni(r,t.lastToolCallId,t.lastFilePath,"after")}}}:{},diff:{added:e,removed:n}}}async function lS(r,t,e,n){let i,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(sS));f.some(v=>v.kind==="rename"||m.has(y.file(v.filePath).toString()))?i=await t.getAllFileEdits():(i=f,o=!0)}else i=await t.getAllFileEdits();if(i.length===0)return[];let s=new Map,a=new Map,l=n&&!o?new Set:void 0;for(let f of i){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 h=a.get(m);h?(h.terminalPath=f.filePath,h.lastToolCallId=f.toolCallId,h.lastFilePath=f.filePath,h.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=>[sS(f),f])):void 0,u=[],d=[];for(let[f,m]of a){if(l&&!l.has(f)){let h=y.file(m.terminalPath).toString(),v=c.get(h);v&&u.push(v);continue}d.push((async()=>{let h;if(m.firstKind==="create")h="";else{let _=await t.readFileEditContent(m.firstToolCallId,m.firstFilePath);h=_?.beforeContent?new TextDecoder().decode(_.beforeContent):""}let v;if(m.lastKind==="delete")v="";else{let _=await t.readFileEditContent(m.lastToolCallId,m.lastFilePath);v=_?.afterContent?new TextDecoder().decode(_.afterContent):""}if(h===v)return;let S=await e.computeDiffCounts(h,v);u.push(aS(r,m,S.added,S.removed))})())}return await Promise.allSettled(d),o&&u.push(...n.previousDiffs),u}async function cS(r,t,e,n){let i=await t.getFileEditsByTurn(n);if(i.length===0)return[];let o=new Map,s=new Map;for(let c of i){let u;c.kind==="rename"&&c.originalPath?(u=o.get(c.originalPath)??c.originalPath,o.set(c.filePath,u),o.delete(c.originalPath)):(u=o.get(c.filePath)??c.filePath,o.set(c.filePath,u));let d=s.get(u);d?(d.terminalPath=c.filePath,d.lastToolCallId=c.toolCallId,d.lastFilePath=c.filePath,d.lastKind=c.kind):s.set(u,{terminalPath:c.filePath,firstToolCallId:c.toolCallId,firstFilePath:c.kind==="rename"&&c.originalPath?c.originalPath:c.filePath,firstKind:c.kind,lastToolCallId:c.toolCallId,lastFilePath:c.filePath,lastKind:c.kind})}let a=[],l=[];for(let c of s.values())l.push((async()=>{let u;if(c.firstKind==="create")u="";else{let m=await t.readFileEditContent(c.firstToolCallId,c.firstFilePath);u=m?.beforeContent?new TextDecoder().decode(m.beforeContent):""}let d;if(c.lastKind==="delete")d="";else{let m=await t.readFileEditContent(c.lastToolCallId,c.lastFilePath);d=m?.afterContent?new TextDecoder().decode(m.afterContent):""}if(u===d)return;let f=await e.computeDiffCounts(u,d);a.push(aS(r,c,f.added,f.removed))})());return await Promise.allSettled(l),a}var Na="checkpoint.workingDir",Mo=class extends T{constructor(e,n,i){super();this._sessionDataService=e;this._gitService=n;this._logService=i;this._sequencer=new Ze;this._register(this._sessionDataService.onWillDeleteSessionData(o=>{o.waitUntil(this.disposeSessionData(o.session))}))}captureBaseline(e,n){return this._sequencer.queue(e.toString(),()=>this._captureBaseline(e,n))}async _captureBaseline(e,n){if(!n)return;let i=this._sessionDataService.openDatabase(e);try{let o=await i.object.getMetadata(Lo);if(o)return o;let s=this._sanitizedSessionId(e),a=vg(s,0),l=await this._writeCheckpointCommit(n,void 0,`Agent host session ${s} - baseline checkpoint`);if(!l)return;let c=await this._gitService.getRepositoryRoot(n);return c?(await this._gitService.updateRef(c,a,l.commitOid),await i.object.setMetadata(Lo,a),await i.object.setMetadata(Na,n.toString()),this._logService.trace(`[AgentHostCheckpoint] Captured baseline for ${e.toString()} at ${a}`),a):void 0}catch(o){this._logService.warn(`[AgentHostCheckpoint] Failed to capture baseline for ${e.toString()}`,o);return}finally{i.dispose()}}captureTurnCheckpoint(e,n){return this._sequencer.queue(e.toString(),()=>this._captureTurnCheckpoint(e,n))}async _captureTurnCheckpoint(e,n){let i=this._sessionDataService.openDatabase(e);try{let[o,s,a,l]=await Promise.all([i.object.getMetadata(Lo),i.object.getMetadata(Na),i.object.getTurnCheckpointRef(n),i.object.getPreviousCheckpointRef(n)]);if(a)return a;if(!o||!s)return;let c=y.parse(s),u=await this._gitService.getRepositoryRoot(c);if(!u)return;let d=l??o,f=await this._gitService.revParse(u,d);if(!f){this._logService.warn(`[AgentHostCheckpoint] Parent ref ${d} missing for session ${e.toString()}`);return}let m=await this._gitService.captureWorkingTreeAsTree(c);if(!m)return;let h=await this._gitService.revParse(u,`${f}^{tree}`);if(h&&h===m)return await i.object.setTurnCheckpointRef(n,d),this._logService.trace(`[AgentHostCheckpoint] No-op turn ${n} for ${e.toString()}; reusing ${d}`),d;let v=this._sanitizedSessionId(e),S=await this._nextTurnNumber(i.object),_=vg(v,S),b=await this._gitService.commitTree(u,m,f,`Agent host session ${v} - turn ${S}`);return b?(await this._gitService.updateRef(u,_,b),await i.object.setTurnCheckpointRef(n,_),this._logService.trace(`[AgentHostCheckpoint] Captured turn ${S} for ${e.toString()} at ${_}`),_):void 0}catch(o){this._logService.warn(`[AgentHostCheckpoint] Failed to capture turn checkpoint for ${e.toString()}/${n}`,o);return}finally{i.dispose()}}async getTurnCheckpointPair(e,n){let i=this._sessionDataService.openDatabase(e);try{let[o,s,a]=await Promise.all([i.object.getTurnCheckpointRef(n),i.object.getPreviousCheckpointRef(n),i.object.getMetadata(Lo)]);if(!o)return;let l=s??a;return l?{parent:l,current:o}:void 0}finally{i.dispose()}}async disposeSessionData(e){await this._sequencer.queue(e.toString(),()=>this._disposeSessionData(e))}async _disposeSessionData(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(n)try{let[i,o,s]=await Promise.all([n.object.getMetadata(Na),n.object.getMetadata(Lo),n.object.getAllCheckpointRefs()]);if(!i)return;let a=y.parse(i),l=await this._gitService.getRepositoryRoot(a);if(!l)return;let c=new Set;o&&c.add(o);for(let u of s)c.add(u);if(c.size===0)return;await this._gitService.deleteRefs(l,[...c]),this._logService.trace(`[AgentHostCheckpoint] Deleted ${c.size} checkpoint refs for ${e.toString()}`)}catch(i){this._logService.warn(`[AgentHostCheckpoint] Failed to dispose checkpoint refs for ${e.toString()}`,i)}finally{n.dispose()}}async _writeCheckpointCommit(e,n,i){let o=await this._gitService.captureWorkingTreeAsTree(e);if(!o)return;let s=await this._gitService.getRepositoryRoot(e);if(!s)return;let a=await this._gitService.commitTree(s,o,n,i);if(a)return{commitOid:a}}async _nextTurnNumber(e){let n=await e.getAllCheckpointRefs(),i=0;for(let o of n){let s=o.lastIndexOf("/"),a=s>=0?o.substring(s+1):o,l=parseInt(a,10);Number.isFinite(l)&&l>i&&(i=l)}return i+1}_sanitizedSessionId(e){return H.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};Mo=w([C(0,vt),C(1,Nt),C(2,L)],Mo);var Ua="agentHost.changeset.uncommitted",Fa="agentHost.changeset.session",Wa="diffs";function bg(r,t){return t==="uncommitted"?Kt(r):Ot(r)}function a0(r){return r==="uncommitted"?Ua:Fa}function dS(r,t,e,n){let i=n?{label:r,uriTemplate:t,description:n}:{label:r,uriTemplate:t};if(!e)return i;let o=0,s=0;for(let a of e)o+=a.diff?.added??0,s+=a.diff?.removed??0;return{...i,additions:o,deletions:s,files:e.length}}function uS(r,t,e){return[dS(zf(),Ot(r),e),dS(qf(),Kt(r),t,Kf())]}function pS(r,t,e){let n=t?.status==="ready"?t.files.map(o=>o.edit):void 0,i=e?.status==="ready"?e.files.map(o=>o.edit):void 0;if(!(!n&&!i))return uS(r,n,i)}function fS(r,t,e){if(!(!t&&!e))return uS(r,t,e)}function Sg(r,t,e,n){if(r)try{return JSON.parse(r)}catch(i){n.warn(`[AgentHostChangesetService] Failed to parse persisted ${e} diffs for ${t}: ${Ct(i)}`);return}}var No=V("agentHostChangesetService"),di=class extends T{constructor(e,n,i,o,s){super();this._stateManager=e;this._logService=n;this._sessionDataService=i;this._gitService=o;this._checkpointService=s;this._diffComputationSequencer=new Ze;this._debouncedDiffTimers=this._register(new We);this._perTurnDebouncedDiffTimers=this._register(new We);this._activeStaticComputes=new Set;this._hasTurnSubscribers=()=>!1;this._diffComputeService=this._register(new Fi(this._logService))}static{this._DIFF_DEBOUNCE_MS=5e3}setTurnSubscriberProbe(e){this._hasTurnSubscribers=e}registerStaticChangesets(e){this._stateManager.registerChangeset(Kt(e)),this._stateManager.registerChangeset(Ot(e))}restoreStaticChangeset(e,n,i){let o=this._stateManager.registerChangeset(bg(e,n));this._publishChangesetDiffs(e,o,i)}parsePersistedStaticChangesets(e,n){let i=Sg(n.uncommittedRaw,e,"uncommitted",this._logService),o=Sg(n.sessionRaw,e,"session",this._logService)??Sg(n.legacyRaw,e,"session (legacy)",this._logService);return{uncommitted:i,session:o}}applyPersistedStaticChangesets(e,n){this._seedIfEmpty(e,"uncommitted",n.uncommitted),this._seedIfEmpty(e,"session",n.session)}restorePersistedStaticChangesets(e,n){let i=this.parsePersistedStaticChangesets(e,n);return this.applyPersistedStaticChangesets(e,i),i}isStaticChangesetComputeActive(e){return this._activeStaticComputes.has(e)}_seedIfEmpty(e,n,i){if(!i)return;let o=this._stateManager.getChangesetState(bg(e,n));o&&o.files.length>0||this.restoreStaticChangeset(e,n,i)}refreshUncommittedChangeset(e){this._scheduleStaticRecompute(e,"uncommitted")}refreshSessionChangeset(e){this._scheduleStaticRecompute(e,"session")}async computeTurnChangeset(e,n){let i=this._stateManager.registerChangeset(eb(e,n)),o;try{o=this._sessionDataService.openDatabase(y.parse(e))}catch(s){return this._logService.warn(`[AgentHostChangesetService] Failed to open session database for turn diff: ${e}`,s),this._stateManager.dispatchServerAction(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:s instanceof Error?s.message:String(s)}}),i}try{let s=await this._computeTurnDiffsPreferCheckpoint(e,o.object,n);this._publishChangesetDiffs(e,i,s)}catch(s){this._logService.warn(`[AgentHostChangesetService] Failed to compute turn diffs for ${e}/${n}`,s),this._stateManager.dispatchServerAction(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:s instanceof Error?s.message:String(s)}})}finally{o.dispose()}return i}async computeCompareTurnsChangeset(e,n,i){let o=this._stateManager.registerChangeset(tb(e,n,i)),s;try{s=this._sessionDataService.openDatabase(y.parse(e))}catch(a){return this._logService.warn(`[AgentHostChangesetService] Failed to open session database for compare-turns diff: ${e}`,a),this._stateManager.dispatchServerAction(o,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:a instanceof Error?a.message:String(a)}}),o}try{let a=y.parse(e),[l,c]=await Promise.all([this._checkpointService.getTurnCheckpointPair(a,n),this._checkpointService.getTurnCheckpointPair(a,i)]);if(!l||!c){let f=!l&&!c?"both turns":l?"modified turn":"original turn";return this._stateManager.dispatchServerAction(o,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:`No checkpoint available for ${f}; compare requires git-backed sessions.`}}),o}if(l.current===c.current)return this._publishChangesetDiffs(e,o,[]),o;let u=await this._resolveWorkingDirectory(s.object);if(!u)return this._stateManager.dispatchServerAction(o,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:"No working directory recorded for session; compare requires git-backed sessions."}}),o;let d=await this._gitService.computeFileDiffsBetweenRefs(u,{sessionUri:e,fromRef:l.current,toRef:c.current});if(d===void 0)return this._stateManager.dispatchServerAction(o,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:`Failed to compute compare-turns diff from git (${l.current}..${c.current}).`}}),o;this._publishChangesetDiffs(e,o,d)}catch(a){this._logService.warn(`[AgentHostChangesetService] Failed to compute compare-turns diffs for ${e}/${n}/${i}`,a),this._stateManager.dispatchServerAction(o,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:a instanceof Error?a.message:String(a)}})}finally{s.dispose()}return o}async _computeTurnDiffsPreferCheckpoint(e,n,i){let o=await this._checkpointService.getTurnCheckpointPair(y.parse(e),i);if(o&&o.parent!==o.current){let s=await this._resolveWorkingDirectory(n);if(s){let a=await this._gitService.computeFileDiffsBetweenRefs(s,{sessionUri:e,fromRef:o.parent,toRef:o.current});if(a)return a}}else if(o&&o.parent===o.current)return[];return cS(e,n,this._diffComputeService,i)}async _resolveWorkingDirectory(e){let n=await e.getMetadata(Na);return n?y.parse(n):void 0}onToolCallEditsApplied(e,n){this._scheduleDebouncedDiffComputation(e,n),this._hasTurnSubscribers(e,n)&&this._scheduleDebouncedTurnDiffComputation(e,n)}onTurnComplete(e,n){this._cancelDebouncedDiffComputation(e),n!==void 0&&(this._cancelDebouncedTurnDiffComputation(e,n),this._hasTurnSubscribers(e,n)&&this._scheduleTurnRecompute(e,n)),this._scheduleStaticRecompute(e,"session",n),this._scheduleStaticRecompute(e,"uncommitted")}onSessionTruncated(e){this._scheduleStaticRecompute(e,"session")}_scheduleDebouncedDiffComputation(e,n){this._debouncedDiffTimers.set(e,Ri(()=>{this._debouncedDiffTimers.deleteAndDispose(e),this._scheduleStaticRecompute(e,"session",n)},di._DIFF_DEBOUNCE_MS))}_cancelDebouncedDiffComputation(e){this._debouncedDiffTimers.deleteAndDispose(e)}_scheduleDebouncedTurnDiffComputation(e,n){let i=`${e}\0${n}`;this._perTurnDebouncedDiffTimers.set(i,Ri(()=>{this._perTurnDebouncedDiffTimers.deleteAndDispose(i),this._scheduleTurnRecompute(e,n)},di._DIFF_DEBOUNCE_MS))}_cancelDebouncedTurnDiffComputation(e,n){this._perTurnDebouncedDiffTimers.deleteAndDispose(`${e}\0${n}`)}_scheduleTurnRecompute(e,n){this._diffComputationSequencer.queue(`${e}\0turn\0${n}`,()=>this.computeTurnChangeset(e,n).then(()=>{}))}_scheduleStaticRecompute(e,n,i){this._diffComputationSequencer.queue(`${e}\0${n}`,()=>this._doComputeStaticChangeset(e,n,i))}async _doComputeStaticChangeset(e,n,i){let o=bg(e,n);this._activeStaticComputes.add(o);let s;try{s=this._sessionDataService.openDatabase(y.parse(e))}catch(a){this._logService.warn(`[AgentHostChangesetService] Failed to open session database for ${n} diff computation: ${e}`,a),this._activeStaticComputes.delete(o),this._stateManager.onChangesetLivenessChanged();return}this._stateManager.registerChangeset(o);try{let a=await this._tryComputeGitDiffs(e,s.object,n);if(!a){if(n==="uncommitted")return;let l;if(i){let c=this._readPreviousChangesetDiffs(o);c&&(l={changedTurnId:i,previousDiffs:[...c]})}a=await lS(e,s.object,this._diffComputeService,l)}this._publishChangesetDiffs(e,o,a),this._persistSessionFlag(e,a0(n),JSON.stringify(a)),n==="session"&&this._persistSessionFlag(e,Wa,JSON.stringify(a))}catch(a){this._logService.warn(`[AgentHostChangesetService] Failed to compute ${n} diffs`,a),this._stateManager.dispatchServerAction(o,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:a instanceof Error?a.message:String(a)}})}finally{this._activeStaticComputes.delete(o),this._stateManager.onChangesetLivenessChanged(),s.dispose()}}_readPreviousChangesetDiffs(e){let n=this._stateManager.getChangesetState(e);if(!(!n||n.files.length===0))return n.files.map(i=>i.edit)}_publishChangesetDiffs(e,n,i){let o=this._stateManager.getChangesetState(n),s=new Set(o?.files.map(m=>m.id)??[]),a=new Map;for(let m of i){let h=m.after?.uri??m.before?.uri;if(!h)continue;a.set(h,m);let v={id:h,edit:m};this._stateManager.dispatchServerAction(n,{type:"changeset/fileSet",file:v})}for(let m of s)a.has(m)||this._stateManager.dispatchServerAction(n,{type:"changeset/fileRemoved",fileId:m});this._stateManager.getChangesetState(n)?.status!=="ready"&&this._stateManager.dispatchServerAction(n,{type:"changeset/statusChanged",status:"ready"});let c=this._stateManager.getSessionState(e);if(!c)return;let u=Array.from(a.values()).reduce((m,h)=>(m.additions+=h.diff?.added??0,m.deletions+=h.diff?.removed??0,m),{additions:0,deletions:0}),f=(c.summary.changesets??[]).map(m=>m.uriTemplate===n?{...m,additions:u.additions,deletions:u.deletions,files:a.size}:m);this._stateManager.setSessionChangesets(e,f)}async _tryComputeGitDiffs(e,n,i){let o=this._stateManager.getSessionState(e)?.summary.workingDirectory;if(!o)return;let s;try{s=y.parse(o)}catch{return}let a=i==="session"?await n.getMetadata(nd)??void 0:void 0;try{return await this._gitService.computeSessionFileDiffs(s,{sessionUri:e,baseBranch:a})}catch(l){this._logService.warn(`[AgentHostChangesetService] git-driven ${i} diff computation failed; falling back to edit-tracker`,l);return}}_persistSessionFlag(e,n,i){let o=this._sessionDataService.openDatabase(y.parse(e));o.object.setMetadata(n,i).catch(s=>{this._logService.warn(`[AgentHostChangesetService] Failed to persist ${n}`,s)}).finally(()=>{o.dispose()})}};di=w([C(1,L),C(2,vt),C(3,Nt),C(4,En)],di);import{homedir as P0}from"os";var Uo="**",gS="/",id="[/\\\\]",rd="[^/\\\\]",l0=/\//g;function mS(r,t){switch(r){case 0:return"";case 1:return`${rd}*?`;default:return`(?:${id}|${rd}+${id}${t?`|${id}${rd}+`:""})*?`}}function hS(r,t){if(!r)return[];let e=[],n=!1,i=!1,o="";for(let s of r){switch(s){case t:if(!n&&!i){e.push(o),o="";continue}break;case"{":n=!0;break;case"}":n=!1;break;case"[":i=!0;break;case"]":i=!1;break}o+=s}return o&&e.push(o),e}function IS(r){if(!r)return"";let t="",e=hS(r,gS);if(e.every(n=>n===Uo))t=".*";else{let n=!1;e.forEach((i,o)=>{if(i===Uo){if(n)return;t+=mS(2,o===e.length-1)}else{let s=!1,a="",l=!1,c="";for(let u of i){if(u!=="}"&&s){a+=u;continue}if(l&&(u!=="]"||!c)){let d;u==="-"?d=u:(u==="^"||u==="!")&&!c?d="^":u===gS?d="":d=Bt(u),c+=d;continue}switch(u){case"{":s=!0;continue;case"[":l=!0;continue;case"}":{let f=`(?:${hS(a,",").map(m=>IS(m)).join("|")})`;t+=f,s=!1,a="";break}case"]":{t+="["+c+"]",l=!1,c="";break}case"?":t+=rd;continue;case"*":t+=mS(1);continue;default:t+=Bt(u)}}o<e.length-1&&(e[o+1]!==Uo||o+2<e.length)&&(t+=id)}n=i===Uo})}return t}var c0=/^\*\*\/\*\.[\w\.-]+$/,d0=/^\*\*\/([\w\.-]+)\/?$/,u0=/^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/,p0=/^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/,f0=/^\*\*((\/[\w\.-]+)+)\/?$/,g0=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,yS=new hn(1e4),vS=function(){return!1},Pn=function(){return null};function _g(r,t){if(!r)return Pn;let e;typeof r!="string"?e=r.pattern:e=r,e=e.trim();let n=t.ignoreCase??!1,i={...t,equals:n?Jn:(l,c)=>l===c,endsWith:n?cy:(l,c)=>l.endsWith(c),isEqualOrParent:(l,c)=>Qn(l,c,t.ignoreCase??!ve)},o=`${n?e.toLowerCase():e}_${!!t.trimForExclusions}_${n}`,s=yS.get(o);if(s)return bS(s,r,i);let a;return c0.test(e)?s=m0(e.substring(4),e,i):(a=d0.exec(Ig(e,i)))?s=h0(a[1],e,i):(t.trimForExclusions?p0:u0).test(e)?s=y0(e,i):(a=f0.exec(Ig(e,i)))?s=SS(a[1].substring(1),e,!0,i):(a=g0.exec(Ig(e,i)))?s=SS(a[1],e,!1,i):s=v0(e,i),yS.set(o,s),bS(s,r,i)}function bS(r,t,e){if(typeof t=="string")return r;let n=function(i,o){return e.isEqualOrParent(i,t.base)?r($p(i.substring(t.base.length),Ce),o):null};return n.allBasenames=r.allBasenames,n.allPaths=r.allPaths,n.basenames=r.basenames,n.patterns=r.patterns,n}function Ig(r,t){return t.trimForExclusions&&r.endsWith("/**")?r.substring(0,r.length-2):r}function m0(r,t,e){return function(n,i){return typeof n=="string"&&e.endsWith(n,r)?t:null}}function h0(r,t,e){let n=`/${r}`,i=`\\${r}`,o=function(a,l){return typeof a!="string"?null:l?e.equals(l,r)?t:null:e.equals(a,r)||e.endsWith(a,n)||e.endsWith(a,i)?t:null},s=[r];return o.basenames=s,o.patterns=[t],o.allBasenames=s,o}function y0(r,t){let e=CS(r.slice(1,-1).split(",").map(a=>_g(a,t)).filter(a=>a!==Pn),r),n=e.length;if(!n)return Pn;if(n===1)return e[0];let i=function(a,l){for(let c=0,u=e.length;c<u;c++)if(e[c](a,l))return r;return null},o=e.find(a=>!!a.allBasenames);o&&(i.allBasenames=o.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(i.allPaths=s),i}function SS(r,t,e,n){let i=Ce===Z.sep,o=i?r:r.replace(l0,Ce),s=Ce+o,a=Z.sep+r,l;return e?l=function(c,u){return typeof c=="string"&&(n.equals(c,o)||n.endsWith(c,s)||!i&&(n.equals(c,r)||n.endsWith(c,a)))?t:null}:l=function(c,u){return typeof c=="string"&&(n.equals(c,o)||!i&&n.equals(c,r))?t:null},l.allPaths=[(e?"*/":"./")+r],l}function v0(r,t){try{let e=new RegExp(`^${IS(r)}$`,t.ignoreCase?"i":void 0);return function(n){return e.lastIndex=0,typeof n=="string"&&e.test(n)?r:null}}catch{return Pn}}function _S(r,t,e){return!r||typeof t!="string"?!1:$a(r,e)(t)}function $a(r,t={}){if(!r)return vS;if(typeof r=="string"||b0(r)){let e=_g(r,t);if(e===Pn)return vS;let n=function(i,o){return!!e(i,o)};return e.allBasenames&&(n.allBasenames=e.allBasenames),e.allPaths&&(n.allPaths=e.allPaths),n}return S0(r,t)}function b0(r){let t=r;return t?typeof t.base=="string"&&typeof t.pattern=="string":!1}function S0(r,t){let e=CS(Object.getOwnPropertyNames(r).map(a=>I0(a,r[a],t)).filter(a=>a!==Pn)),n=e.length;if(!n)return Pn;if(!e.some(a=>!!a.requiresSiblings)){if(n===1)return e[0];let a=function(u,d){let f;for(let m=0,h=e.length;m<h;m++){let v=e[m](u,d);if(typeof v=="string")return v;ql(v)&&(f||(f=[]),f.push(v))}return f?(async()=>{for(let m of f){let h=await m;if(typeof h=="string")return h}return null})():null},l=e.find(u=>!!u.allBasenames);l&&(a.allBasenames=l.allBasenames);let c=e.reduce((u,d)=>d.allPaths?u.concat(d.allPaths):u,[]);return c.length&&(a.allPaths=c),a}let i=function(a,l,c){let u,d;for(let f=0,m=e.length;f<m;f++){let h=e[f];h.requiresSiblings&&c&&(l||(l=_e(a)),u||(u=l.substring(0,l.length-Nl(a).length)));let v=h(a,l,u,c);if(typeof v=="string")return v;ql(v)&&(d||(d=[]),d.push(v))}return d?(async()=>{for(let f of d){let m=await f;if(typeof m=="string")return m}return null})():null},o=e.find(a=>!!a.allBasenames);o&&(i.allBasenames=o.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(i.allPaths=s),i}function I0(r,t,e){if(t===!1)return Pn;let n=_g(r,e);if(n===Pn)return Pn;if(typeof t=="boolean")return n;if(t){let i=t.when;if(typeof i=="string"){let o=(s,a,l,c)=>{if(!c||!n(s,a))return null;let u=i.replace("$(basename)",()=>l),d=c(u);return ql(d)?d.then(f=>f?r:null):d?r:null};return o.requiresSiblings=!0,o}}return n}function CS(r,t){let e=r.filter(a=>!!a.basenames);if(e.length<2)return r;let n=e.reduce((a,l)=>{let c=l.basenames;return c?a.concat(c):a},[]),i;if(t){i=[];for(let a=0,l=n.length;a<l;a++)i.push(t)}else i=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 u;for(u=a.length;u>0;u--){let d=a.charCodeAt(u-1);if(d===47||d===92)break}l=a.substring(u)}let c=n.indexOf(l);return c!==-1?i[c]:null};o.basenames=n,o.patterns=i,o.allBasenames=n;let s=r.filter(a=>!a.basenames);return s.push(o),s}function Cg(r,t){return Vt(r,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)}function od(r,t){return r.replace(/^~($|\/|\\)/,`${t}$1`)}import*as TS from"fs";var _0=new Set(["/dev/null","/dev/stdout","/dev/stderr","/dev/tty"]);function C0(r){let t=r.trim();return t.length===0?!1:((t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),/^&[0-9]+-?$/.test(t)?!0:_0.has(t))}function T0(r){if(!r.includes(">"))return{kind:"read"};let t=r.match(/(?:[0-9]+|&)?>>?\|?\s*(.+)$/);if(!t)return{kind:"unsafeWrite",dest:void 0};let e=t[1].trim();if(C0(e))return{kind:"safeWrite"};let n=e;return(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))&&(n=n.slice(1,-1)),{kind:"unsafeWrite",dest:n}}var Tg=/(?!.*)/,x0=/^[A-Z_][A-Z0-9_]*=/i,sd=class extends T{constructor(e){super();this._logService=e;this._initPromise=this._initTreeSitter()}initialize(){return this._initPromise}shouldAutoApprove(e,n){let i=e.trimStart();if(i.length===0)return"approved";this._ensureRules();let o=this._extractSubCommands(i);if(!o)return this._logService.trace("[CommandAutoApprover] Tree-sitter unavailable, requiring confirmation"),"noMatch";let s=this._matchSubCommands(o.subCommands);if(s==="approved"&&o.unsafeWriteDests.length>0){for(let a of o.unsafeWriteDests)if(a===void 0||!n?.isWriteDestApproved?.(a))return this._logService.trace("[CommandAutoApprover] Write redirection to non-approved destination, requiring confirmation"),"noMatch"}return s}_matchSubCommands(e){let n=!0;for(let i of e){if(x0.test(i))return"denied";let o=this._matchSingleCommand(i);if(o==="denied")return"denied";o!=="approved"&&(n=!1)}return n?"approved":"noMatch"}_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 i=new this._queryClass(this._bashLanguage,"(command) @command (file_redirect) @file_redirect (heredoc_redirect) @heredoc_redirect (herestring_redirect) @herestring_redirect"),o=i.captures(n.rootNode),s=[],a=[];for(let l of o)if(l.name==="command")s.push(l.node.text);else if(l.name==="file_redirect"){let c=T0(l.node.text);c.kind==="unsafeWrite"&&a.push(c.dest)}else l.name==="heredoc_redirect"||l.name;return i.delete(),s.length>0||a.length>0?{subCommands:s,unsafeWriteDests:a}: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=y.joinPath(rt.asFileUri(""),"..","node_modules","@vscode","tree-sitter-wasm","wasm"),i=y.joinPath(n,"tree-sitter.wasm").fsPath;if(await e.Parser.init({locateFile(){return i}}),this._store.isDisposed)return;let o=new e.Parser;this._register(A(()=>{try{o.delete()}catch{}}));let s=y.joinPath(n,"tree-sitter-bash.wasm").fsPath,a=await TS.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[i,o]of Object.entries(R0)){let s=w0(i);o===!0?e.push({regex:s}):o===!1&&n.push({regex:s})}this._allowRules=e,this._denyRules=n}};function w0(r){let t=r.match(/^\/(?<pattern>.+)\/(?<flags>[dgimsuvy]*)$/),e=t?.groups?.pattern;if(e){let i=t.groups?.flags;if(i&&(i=i.replaceAll("g","")),e===".*")return new RegExp(e);try{let o=new RegExp(e,i||void 0);return ay(o)?Tg:o}catch{return Tg}}if(r==="")return Tg;let n;if(r.includes("/")||r.includes("\\")){let i=r.replace(/[/\\]/g,"%%PATH_SEP%%");i=Bt(i),i=i.replace(/%%PATH_SEP%%*/g,"[/\\\\]"),n=`^(?:\\.[/\\\\])?${i}`}else n=Bt(r);return new RegExp(`^${n}\\b`)}var R0={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};var xS="allow-session",k0=[{id:xS,label:g(2134,null),kind:"approve",group:1},{id:"allow-once",label:g(2133,null),kind:"approve"},{id:"skip",label:g(2135,null),kind:"deny",group:2}],A0={"**/*":!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},Fo=class extends T{constructor(e,n,i){super();this._stateManager=e;this._configService=n;this._logService=i;this._commandAutoApprover=this._register(new sd(this._logService))}initialize(){return this._commandAutoApprover.initialize()}getAutoApproval(e,n){let i=this._configService.getEffectiveValue(n,Mt,"autoApprove"),o=this._configService.getEffectiveWorkingDirectory(n);if(i==="autoApprove"||i==="autopilot")return this._logService.trace(`[SessionPermissionManager] Auto-approving tool call (session autoApprove=${i})`),"setting";if(this._isToolAllowedByPermissions(n,e.toolCallId))return"setting";if(e.permissionKind==="read"&&e.permissionPath)return this._isPathInWorkingDirectory(e.permissionPath,o)?(this._logService.trace(`[SessionPermissionManager] Auto-approving read of ${e.permissionPath}`),"not-needed"):void 0;if(e.permissionKind==="write"&&e.permissionPath)return this._isPathInWorkingDirectory(e.permissionPath,o)&&this._isEditAutoApproved(e.permissionPath)?(this._logService.trace(`[SessionPermissionManager] Auto-approving write to ${e.permissionPath}`),"not-needed"):void 0;if(e.permissionKind==="shell"&&e.toolInput){let s=this._commandAutoApprover.shouldAutoApprove(e.toolInput,{isWriteDestApproved:a=>this._isShellWriteDestApproved(a,o)});if(s==="approved")return this._logService.trace("[SessionPermissionManager] Auto-approving shell command"),"not-needed";s==="denied"&&this._logService.trace("[SessionPermissionManager] Shell command denied by rule");return}}createToolReadyAction(e,n,i){let o=e.state;return o.confirmationTitle?{type:"session/toolCallReady",turnId:i,toolCallId:o.toolCallId,invocationMessage:o.invocationMessage,toolInput:o.toolInput,confirmationTitle:o.confirmationTitle,edits:o.edits,editable:o.editable,options:o.options?o.options.slice():k0.slice()}:{type:"session/toolCallReady",turnId:i,toolCallId:o.toolCallId,invocationMessage:o.invocationMessage,toolInput:o.toolInput,confirmed:"not-needed"}}handleToolCallConfirmed(e,n,i){if(i===xS){let o=this._getToolNameForToolCall(e,n);o&&this._addToolToSessionPermissions(e,o)}}_isPathInWorkingDirectory(e,n){if(!n)return!1;let i=y.parse(n);return Ve.isEqualOrParent(Ht(y.file(e)),i)}_isShellWriteDestApproved(e,n){let i=this._resolveShellRedirectPath(e,n);return i?this._isPathInWorkingDirectory(i,n)&&this._isEditAutoApproved(i):!1}_resolveShellRedirectPath(e,n){let i=od(e.trim(),P0());if(i){if(Yt(i))return i;if(n)return an(y.parse(n).fsPath,i)}}_isEditAutoApproved(e){let n=!0;for(let[i,o]of Object.entries(A0))o!==n&&_S(i,e)&&(n=o);return n}_isToolAllowedByPermissions(e,n){let i=this._getToolNameForToolCall(e,n);if(!i)return!1;let s=this._configService.getEffectiveValue(e,Mt,"permissions")?.allow.includes(i)??!1;return s&&this._logService.trace(`[SessionPermissionManager] Auto-approving "${i}" via permissions`),s}_getToolNameForToolCall(e,n){let o=this._stateManager.getSessionState(e)?.activeTurn?.responseParts;if(o){for(let s of o)if(s.kind==="toolCall"&&s.toolCall.toolCallId===n)return s.toolCall.toolName}}_addToolToSessionPermissions(e,n){let i=this._configService.getEffectiveValue(e,Mt,"permissions")??{allow:[],deny:[]};i.allow.includes(n)||(this._configService.updateSessionConfig(e,{permissions:{allow:[...i.allow,n],deny:[...i.deny]}}),this._logService.info(`[SessionPermissionManager] Added "${n}" to session permissions for ${e}`))}};Fo=w([C(1,Je),C(2,L)],Fo);import{hostname as aR,release as lR}from"os";import{networkInterfaces as M0}from"os";import{networkInterfaces as D0}from"os";var O0=new Set(["00:00:00:00:00:00","ff:ff:ff:ff:ff:ff","ac:de:48:00:11:22"]);function L0(r){let t=r.replace(/\-/g,":").toLowerCase();return!O0.has(t)}function wS(){let r=D0();for(let t in r){let e=r[t];if(e){for(let{mac:n}of e)if(L0(n))return n}}throw new Error("Unable to retrieve mac address (unexpected format)")}var aV=new class{_isVirtualMachineMacAddress(r){return this._virtualMachineOUIs||(this._virtualMachineOUIs=Cn.forStrings(),this._virtualMachineOUIs.set("00-50-56",!0),this._virtualMachineOUIs.set("00-0C-29",!0),this._virtualMachineOUIs.set("00-05-69",!0),this._virtualMachineOUIs.set("00-03-FF",!0),this._virtualMachineOUIs.set("00-1C-42",!0),this._virtualMachineOUIs.set("00-16-3E",!0),this._virtualMachineOUIs.set("08-00-27",!0),this._virtualMachineOUIs.set("00:50:56",!0),this._virtualMachineOUIs.set("00:0C:29",!0),this._virtualMachineOUIs.set("00:05:69",!0),this._virtualMachineOUIs.set("00:03:FF",!0),this._virtualMachineOUIs.set("00:1C:42",!0),this._virtualMachineOUIs.set("00:16:3E",!0),this._virtualMachineOUIs.set("08:00:27",!0)),!!this._virtualMachineOUIs.findSubstr(r)}value(){if(this._value===void 0){let r=0,t=0,e=M0();for(let n in e){let i=e[n];if(i)for(let{mac:o,internal:s}of i)s||(t+=1,this._isVirtualMachineMacAddress(o.toUpperCase())&&(r+=1))}this._value=t>0?r/t:0}return this._value}},xg;async function ad(r){return xg||(xg=(async()=>await N0(r)||q())()),xg}async function N0(r){try{let t=await import("crypto"),e=wS();return t.createHash("sha256").update(e,"utf8").digest("hex")}catch(t){r(t);return}}var U0="Software\\Microsoft\\SQMClient";async function RS(r){if(K){let t=await import("@vscode/windows-registry");try{return t.GetStringRegKey("HKEY_LOCAL_MACHINE",U0,"MachineId")||""}catch(e){return r(e),""}}return""}async function ld(r){try{let e=await(await import("@vscode/deviceid")).getDeviceId();return fy(e)}catch(t){return r(t),q()}}var dd;(t=>t.DEFAULT={allowTrailingComma:!0})(dd||={});function Rg(r,t=!1){let e=0,n=r.length,i="",o=0,s=16,a=0;function l(v){let S=0,_=0;for(;S<v;){let b=r.charCodeAt(e);if(b>=48&&b<=57)_=_*16+b-48;else if(b>=65&&b<=70)_=_*16+b-65+10;else if(b>=97&&b<=102)_=_*16+b-97+10;else break;e++,S++}return S<v&&(_=-1),_}function c(v){e=v,i="",o=0,s=16,a=0}function u(){let v=e;if(r.charCodeAt(e)===48)e++;else for(e++;e<r.length&&Wo(r.charCodeAt(e));)e++;if(e<r.length&&r.charCodeAt(e)===46)if(e++,e<r.length&&Wo(r.charCodeAt(e)))for(e++;e<r.length&&Wo(r.charCodeAt(e));)e++;else return a=3,r.substring(v,e);let S=e;if(e<r.length&&(r.charCodeAt(e)===69||r.charCodeAt(e)===101))if(e++,(e<r.length&&r.charCodeAt(e)===43||r.charCodeAt(e)===45)&&e++,e<r.length&&Wo(r.charCodeAt(e))){for(e++;e<r.length&&Wo(r.charCodeAt(e));)e++;S=e}else a=3;return r.substring(v,S)}function d(){let v="",S=e;for(;;){if(e>=n){v+=r.substring(S,e),a=2;break}let _=r.charCodeAt(e);if(_===34){v+=r.substring(S,e),e++;break}if(_===92){if(v+=r.substring(S,e),e++,e>=n){a=2;break}switch(r.charCodeAt(e++)){case 34:v+='"';break;case 92:v+="\\";break;case 47:v+="/";break;case 98:v+="\b";break;case 102:v+="\f";break;case 110:v+=`
`;break;case 114:v+="\r";break;case 116:v+="	";break;case 117:{let I=l(4);I>=0?v+=String.fromCharCode(I):a=4;break}default:a=5}S=e;continue}if(_>=0&&_<=31)if(cd(_)){v+=r.substring(S,e),a=2;break}else a=6;e++}return v}function f(){if(i="",a=0,o=e,e>=n)return o=n,s=17;let v=r.charCodeAt(e);if(wg(v)){do e++,i+=String.fromCharCode(v),v=r.charCodeAt(e);while(wg(v));return s=15}if(cd(v))return e++,i+=String.fromCharCode(v),v===13&&r.charCodeAt(e)===10&&(e++,i+=`
`),s=14;switch(v){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++,i=d(),s=10;case 47:{let S=e-1;if(r.charCodeAt(e+1)===47){for(e+=2;e<n&&!cd(r.charCodeAt(e));)e++;return i=r.substring(S,e),s=12}if(r.charCodeAt(e+1)===42){e+=2;let _=n-1,b=!1;for(;e<_;){if(r.charCodeAt(e)===42&&r.charCodeAt(e+1)===47){e+=2,b=!0;break}e++}return b||(e++,a=1),i=r.substring(S,e),s=13}return i+=String.fromCharCode(v),e++,s=16}case 45:if(i+=String.fromCharCode(v),e++,e===n||!Wo(r.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 i+=u(),s=11;default:for(;e<n&&m(v);)e++,v=r.charCodeAt(e);if(o!==e){switch(i=r.substring(o,e),i){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return i+=String.fromCharCode(v),e++,s=16}}function m(v){if(wg(v)||cd(v))return!1;switch(v){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function h(){let v;do v=f();while(v>=12&&v<=15);return v}return{setPosition:c,getPosition:()=>e,scan:t?h:f,getToken:()=>s,getTokenValue:()=>i,getTokenOffset:()=>o,getTokenLength:()=>e-o,getTokenError:()=>a}}function wg(r){return r===32||r===9||r===11||r===12||r===160||r===5760||r>=8192&&r<=8203||r===8239||r===8287||r===12288||r===65279}function cd(r){return r===10||r===13||r===8232||r===8233}function Wo(r){return r>=48&&r<=57}function ud(r,t=[],e=dd.DEFAULT){let n=null,i=[],o=[];function s(l){Array.isArray(i)?i.push(l):n!==null&&(i[n]=l)}return $o(r,{onObjectBegin:()=>{let l={};s(l),o.push(i),i=l,n=null},onObjectProperty:l=>{n=l},onObjectEnd:()=>{i=o.pop()},onArrayBegin:()=>{let l=[];s(l),o.push(i),i=l,n=null},onArrayEnd:()=>{i=o.pop()},onLiteralValue:s,onError:(l,c,u)=>{t.push({error:l,offset:c,length:u})}},e),i[0]}function ES(r,t=[],e=dd.DEFAULT){let n={type:"array",offset:-1,length:-1,children:[],parent:void 0};function i(l){n.type==="property"&&(n.length=l-n.offset,n=n.parent)}function o(l){return n.children.push(l),l}$o(r,{onObjectBegin:l=>{n=o({type:"object",offset:l,length:-1,parent:n,children:[]})},onObjectProperty:(l,c,u)=>{n=o({type:"property",offset:c,length:-1,parent:n,children:[]}),n.children.push({type:"string",value:l,offset:c,length:u,parent:n})},onObjectEnd:(l,c)=>{n.length=l+c-n.offset,n=n.parent,i(l+c)},onArrayBegin:(l,c)=>{n=o({type:"array",offset:l,length:-1,parent:n,children:[]})},onArrayEnd:(l,c)=>{n.length=l+c-n.offset,n=n.parent,i(l+c)},onLiteralValue:(l,c,u)=>{o({type:F0(l),offset:c,length:u,parent:n,value:l}),i(c+u)},onSeparator:(l,c,u)=>{n.type==="property"&&(l===":"?n.colonOffset=c:l===","&&i(c))},onError:(l,c,u)=>{t.push({error:l,offset:c,length:u})}},e);let a=n.children[0];return a&&delete a.parent,a}function Eg(r,t){if(!r)return;let e=r;for(let n of t)if(typeof n=="string"){if(e.type!=="object"||!Array.isArray(e.children))return;let i=!1;for(let o of e.children)if(Array.isArray(o.children)&&o.children[0].value===n){e=o.children[1],i=!0;break}if(!i)return}else{let i=n;if(e.type!=="array"||i<0||!Array.isArray(e.children)||i>=e.children.length)return;e=e.children[i]}return e}function $o(r,t,e=dd.DEFAULT){let n=Rg(r,!1);function i(O){return O?()=>O(n.getTokenOffset(),n.getTokenLength()):()=>!0}function o(O){return O?G=>O(G,n.getTokenOffset(),n.getTokenLength()):()=>!0}let s=i(t.onObjectBegin),a=o(t.onObjectProperty),l=i(t.onObjectEnd),c=i(t.onArrayBegin),u=i(t.onArrayEnd),d=o(t.onLiteralValue),f=o(t.onSeparator),m=i(t.onComment),h=o(t.onError),v=e&&e.disallowComments,S=e&&e.allowTrailingComma;function _(){for(;;){let O=n.scan();switch(n.getTokenError()){case 4:b(14);break;case 5:b(15);break;case 3:b(13);break;case 1:v||b(11);break;case 2:b(12);break;case 6:b(16);break}switch(O){case 12:case 13:v?b(10):m();break;case 16:b(1);break;case 15:case 14:break;default:return O}}}function b(O,G=[],te=[]){if(h(O),G.length+te.length>0){let ye=n.getToken();for(;ye!==17;){if(G.indexOf(ye)!==-1){_();break}else if(te.indexOf(ye)!==-1)break;ye=_()}}}function I(O){let G=n.getTokenValue();return O?d(G):a(G),_(),!0}function R(){switch(n.getToken()){case 11:{let O=0;try{O=JSON.parse(n.getTokenValue()),typeof O!="number"&&(b(2),O=0)}catch{b(2)}d(O);break}case 7:d(null);break;case 8:d(!0);break;case 9:d(!1);break;default:return!1}return _(),!0}function P(){return n.getToken()!==10?(b(3,[],[2,5]),!1):(I(!1),n.getToken()===6?(f(":"),_(),M()||b(4,[],[2,5])):b(5,[],[2,5]),!0)}function j(){s(),_();let O=!1;for(;n.getToken()!==2&&n.getToken()!==17;){if(n.getToken()===5){if(O||b(4,[],[]),f(","),_(),n.getToken()===2&&S)break}else O&&b(6,[],[]);P()||b(4,[],[2,5]),O=!0}return l(),n.getToken()!==2?b(7,[2],[]):_(),!0}function E(){c(),_();let O=!1;for(;n.getToken()!==4&&n.getToken()!==17;){if(n.getToken()===5){if(O||b(4,[],[]),f(","),_(),n.getToken()===4&&S)break}else O&&b(6,[],[]);M()||b(4,[],[4,5]),O=!0}return u(),n.getToken()!==4?b(8,[4],[]):_(),!0}function M(){switch(n.getToken()){case 3:return E();case 1:return j();case 10:return I(!0);default:return R()}}return _(),n.getToken()===17?e.allowEmptyContent?!0:(b(4,[],[]),!1):M()?(n.getToken()!==17&&b(9,[],[]),!0):(b(4,[],[]),!1)}function F0(r){switch(typeof r){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(r){if(Array.isArray(r))return"array"}else return"null";return"object"}default:return"null"}}function kS(r,t,e){let n,i,o,s,a;if(t){for(s=t.offset,a=s+t.length,o=s;o>0&&!Va(r,o-1);)o--;let I=a;for(;I<r.length&&!Va(r,I);)I++;i=r.substring(o,I),n=W0(i,e)}else i=r,n=0,o=0,s=0,a=r.length;let l=$0(e,r),c=!1,u=0,d;e.insertSpaces?d=Pg(" ",e.tabSize||4):d="	";let f=Rg(i,!1),m=!1;function h(){return l+Pg(d,n+u)}function v(){let I=f.scan();for(c=!1;I===15||I===14;)c=c||I===14,I=f.scan();return m=I===16||f.getTokenError()!==0,I}let S=[];function _(I,R,P){!m&&R<a&&P>s&&r.substring(R,P)!==I&&S.push({offset:R,length:P-R,content:I})}let b=v();if(b!==17){let I=f.getTokenOffset()+o,R=Pg(d,n);_(R,o,I)}for(;b!==17;){let I=f.getTokenOffset()+f.getTokenLength()+o,R=v(),P="";for(;!c&&(R===12||R===13);){let E=f.getTokenOffset()+o;_(" ",I,E),I=f.getTokenOffset()+f.getTokenLength()+o,P=R===12?h():"",R=v()}if(R===2)b!==1&&(u--,P=h());else if(R===4)b!==3&&(u--,P=h());else{switch(b){case 3:case 1:u++,P=h();break;case 5:case 12:P=h();break;case 13:c?P=h():P=" ";break;case 6:P=" ";break;case 10:if(R===6){P="";break}case 7:case 8:case 9:case 11:case 2:case 4:R===12||R===13?P=" ":R!==5&&R!==17&&(m=!0);break;case 16:m=!0;break}c&&(R===12||R===13)&&(P=h())}let j=f.getTokenOffset()+o;_(P,I,j),b=R}return S}function Pg(r,t){let e="";for(let n=0;n<t;n++)e+=r;return e}function W0(r,t){let e=0,n=0,i=t.tabSize||4;for(;e<r.length;){let o=r.charAt(e);if(o===" ")n++;else if(o==="	")n+=i;else break;e++}return Math.floor(n/i)}function $0(r,t){for(let e=0;e<t.length;e++){let n=t.charAt(e);if(n==="\r")return e+1<t.length&&t.charAt(e+1)===`
`?`\r
`:"\r";if(n===`
`)return`
`}return r&&r.eol||`
`}function Va(r,t){return`\r
`.indexOf(r.charAt(t))!==-1}function AS(r,t,e,n,i){let o=t.slice(),a=ES(r,[]),l,c;for(;o.length>0&&(c=o.pop(),l=Eg(a,o),l===void 0&&e!==void 0);)typeof c=="string"?e={[c]:e}:e=[e];if(l)if(l.type==="object"&&typeof c=="string"&&Array.isArray(l.children)){let u=Eg(l,[c]);if(u!==void 0)if(e===void 0){if(!u.parent)throw new Error("Malformed AST");let d=l.children.indexOf(u.parent),f,m=u.parent.offset+u.parent.length;if(d>0){let h=l.children[d-1];f=h.offset+h.length}else f=l.offset+1,l.children.length>1&&(m=l.children[1].offset);return Vo(r,{offset:f,length:m-f,content:""},n)}else return Vo(r,{offset:u.offset,length:u.length,content:JSON.stringify(e)},n);else{if(e===void 0)return[];let d=`${JSON.stringify(c)}: ${JSON.stringify(e)}`,f=i?i(l.children.map(h=>h.children[0].value)):l.children.length,m;if(f>0){let h=l.children[f-1];m={offset:h.offset+h.length,length:0,content:","+d}}else l.children.length===0?m={offset:l.offset+1,length:0,content:d}:m={offset:l.offset+1,length:0,content:d+","};return Vo(r,m,n)}}else if(l.type==="array"&&typeof c=="number"&&Array.isArray(l.children))if(e!==void 0){let u=`${JSON.stringify(e)}`,d;if(l.children.length===0||c===0)d={offset:l.offset+1,length:0,content:l.children.length===0?u:u+","};else{let f=c===-1||c>l.children.length?l.children.length:c,m=l.children[f-1];d={offset:m.offset+m.length,length:0,content:","+u}}return Vo(r,d,n)}else{let u=c,d=l.children[u],f;if(l.children.length===1)f={offset:l.offset+1,length:l.length-2,content:""};else if(l.children.length-1===u){let m=l.children[u-1],h=m.offset+m.length,v=l.offset+l.length;f={offset:h,length:v-2-h,content:""}}else f={offset:d.offset,length:l.children[u+1].offset-d.offset,content:""};return Vo(r,f,n)}else throw new Error(`Can not add ${typeof c!="number"?"index":"property"} to parent of type ${l.type}`);else return e===void 0?[]:Vo(r,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(e)},n)}function Vo(r,t,e){let n=kg(r,t),i=t.offset,o=t.offset+t.content.length;if(t.length===0||t.content.length===0){for(;i>0&&!Va(n,i-1);)i--;for(;o<n.length&&!Va(n,o);)o++}let s=kS(n,{offset:i,length:o-i},e);for(let l=s.length-1;l>=0;l--){let c=s[l];n=kg(n,c),i=Math.min(i,c.offset),o=Math.max(o,c.offset+c.length),o+=c.content.length-c.length}let a=r.length-(n.length-o)-i;return[{offset:i,length:a,content:n.substring(i,o)}]}function kg(r,t){return r.substring(0,t.offset)+t.content+r.substring(t.offset+t.length)}function DS(r,t){let e=t.slice(0).sort((i,o)=>{let s=i.offset-o.offset;return s===0?i.length-o.length:s}),n=r.length;for(let i=e.length-1;i>=0;i--){let o=e[i];if(o.offset+o.length<=n)r=kg(r,o);else throw new Error("Overlapping edit");n=o.offset}return r}var OS=V("configurationService");function pd(r){let t=r;return t&&typeof t=="object"&&(!t.overrideIdentifier||typeof t.overrideIdentifier=="string")&&(!t.resource||t.resource instanceof y)}function LS(r){let t=r;return t&&typeof t=="object"&&(!t.overrideIdentifiers||Array.isArray(t.overrideIdentifiers))&&!t.overrideIdentifier&&(!t.resource||t.resource instanceof y)}function fd(r,t){let e=Object.create(null);for(let n in r)Ag(e,n,r[n],t);return e}function Ag(r,t,e,n){let i=t.split("."),o=i.pop(),s=r;for(let a=0;a<i.length;a++){let l=i[a],c=s[l];switch(typeof c){case"undefined":c=s[l]=Object.create(null);break;case"object":if(c===null){n(`Ignoring ${t} as ${i.slice(0,a+1).join(".")} is null`);return}break;default:n(`Ignoring ${t} as ${i.slice(0,a+1).join(".")} is ${JSON.stringify(c)}`);return}s=c}if(typeof s=="object"&&s!==null)try{s[o]=e}catch{n(`Ignoring ${t} as ${i.join(".")} is ${JSON.stringify(s)}`)}else n(`Ignoring ${t} as ${i.join(".")} is ${JSON.stringify(s)}`)}function MS(r,t){let e=t.split(".");NS(r,e)}function NS(r,t){if(!r)return;let e=r,n=t.shift();if(t.length===0){delete e[n];return}if(Object.keys(e).indexOf(n)!==-1){let i=e[n];typeof i=="object"&&i!==null&&!Array.isArray(i)&&(NS(i,t),Object.keys(i).length===0&&delete e[n])}}function Ba(r,t,e){function n(s,a){let l=s;for(let c of a){if(typeof l!="object"||l===null)return;l=l[c]}return l}let i=t.split("."),o=n(r,i);return typeof o>"u"?e:o}function US(r){return r.replace(/^\[/,"").replace(/]$/g,"").replace(/\]\[/g,", ")}function FS(r){let t=!1,e=new Map,n=new Map;if(V0(r,u=>{if(r===u)return!0;let d=JSON.stringify(u);if(d.length<30)return!0;let f=e.get(d);if(!f){let m={schemas:[u]};return e.set(d,m),n.set(u,m),!0}return f.schemas.push(u),n.set(u,f),t=!0,!1}),e.clear(),!t)return JSON.stringify(r);let o="$defs";for(;r.hasOwnProperty(o);)o+="_";let s=[];function a(u){return JSON.stringify(u,(d,f)=>{if(f!==u){let m=n.get(f);if(m&&m.schemas.length>1)return m.id||(m.id=`_${s.length}`,s.push(m.schemas[0])),{$ref:`#/${o}/${m.id}`}}return f})}let l=a(r),c=[];for(let u=0;u<s.length;u++)c.push(`"_${u}":${a(s[u])}`);return c.length?`${l.substring(0,l.length-1)},"${o}":{${c.join(",")}}}`:l}function Bo(r){return typeof r=="object"&&r!==null}function V0(r,t){if(!r||typeof r!="object")return;let e=(...l)=>{for(let c of l)Bo(c)&&s.push(c)},n=(...l)=>{for(let c of l)if(Bo(c))for(let u in c){let d=c[u];Bo(d)&&s.push(d)}},i=(...l)=>{for(let c of l)if(Array.isArray(c))for(let u of c)Bo(u)&&s.push(u)},o=l=>{if(Array.isArray(l))for(let c of l)Bo(c)&&s.push(c);else Bo(l)&&s.push(l)},s=[r],a=s.pop();for(;a;)t(a)&&(e(a.additionalItems,a.additionalProperties,a.not,a.contains,a.propertyNames,a.if,a.then,a.else,a.unevaluatedItems,a.unevaluatedProperties),n(a.definitions,a.$defs,a.properties,a.patternProperties,a.dependencies,a.dependentSchemas),i(a.anyOf,a.allOf,a.oneOf,a.prefixItems),o(a.items)),a=s.pop()}var Og={JSONContribution:"base.contributions.json"};function WS(r){return r.length>0&&r.charAt(r.length-1)==="#"?r.substring(0,r.length-1):r}var Dg=class extends T{constructor(){super(...arguments);this.schemasById={};this.schemaAssociations={};this._onDidChangeSchema=this._register(new x);this.onDidChangeSchema=this._onDidChangeSchema.event;this._onDidChangeSchemaAssociations=this._register(new x);this.onDidChangeSchemaAssociations=this._onDidChangeSchemaAssociations.event}registerSchema(e,n,i){let o=WS(e);this.schemasById[o]=n,this._onDidChangeSchema.fire(e),i&&i.add(A(()=>{delete this.schemasById[o],this._onDidChangeSchema.fire(e)}))}registerSchemaAssociation(e,n){let i=WS(e);return this.schemaAssociations[i]||(this.schemaAssociations[i]=[]),this.schemaAssociations[i].includes(n)||(this.schemaAssociations[i].push(n),this._onDidChangeSchemaAssociations.fire()),A(()=>{let o=this.schemaAssociations[i];if(o){let s=o.indexOf(n);s!==-1&&(o.splice(s,1),o.length===0&&delete this.schemaAssociations[i],this._onDidChangeSchemaAssociations.fire())}})}notifySchemaChanged(e){this._onDidChangeSchema.fire(e)}getSchemaContributions(){return{schemas:this.schemasById}}getSchemaContent(e){let n=this.schemasById[e];return n?FS(n):void 0}hasSchemaContent(e){return!!this.schemasById[e]}getSchemaAssociations(){return this.schemaAssociations}},B0=new Dg;lt.add(Og.JSONContribution,B0);var pt,Lg=globalThis.vscode;if(typeof Lg<"u"&&typeof Lg.context<"u"){let r=Lg.context.configuration();if(r)pt=r.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(pt=globalThis._VSCODE_PRODUCT_JSON,ke.VSCODE_DEV&&Object.assign(pt,{nameShort:`${pt.nameShort} Dev`,nameLong:`${pt.nameLong} Dev`,dataFolderName:`${pt.dataFolderName}-dev`,serverDataFolderName:pt.serverDataFolderName?`${pt.serverDataFolderName}-dev`:void 0}),!pt.version){let r=globalThis._VSCODE_PACKAGE_JSON;Object.assign(pt,{version:r.version})}Object.assign(pt,{extensionsGallery:ke.EXTENSIONS_GALLERY?JSON.parse(ke.EXTENSIONS_GALLERY):pt.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:ke.CS_TELEMETRY_URL||pt.telemetryEndpoint||"https://v1.telemetry.coder.com/track"})}else pt={nameShort:"code-server",nameLong:"code-server",applicationName:"code-server",dataFolderName:".code-server",sharedDataFolderName:".vscode-oss-shared",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",agentsTelemetryAppName:"agents",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",managePlanUrl:"https://aka.ms/github-copilot-manage-plan",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",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",managedSettingsUrl:"https://api.github.com/copilot_internal/managed_settings"},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"],sessionsWindowAllowedExtensions:[],enableTelemetry:!0,quality:"stable",codeServerVersion:"4.123.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.123.0",commit:"77d880d0c3fcbf4ac613644b3e113cedd6173a16",date:"2026-06-03T11:29:03+02:00"},Object.keys(pt).length===0&&Object.assign(pt,{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 Ut=pt;var rn={Configuration:"base.contributions.configuration"};function H0(r,t){return r===t?!0:!r||!t?!1:typeof r=="string"||typeof t=="string"?r===t:r.id===t.id}var gd={properties:{},patternProperties:{}},md={properties:{},patternProperties:{}},hd={properties:{},patternProperties:{}},yd={properties:{},patternProperties:{}},vd={properties:{},patternProperties:{}},bd={properties:{},patternProperties:{}},Ha={properties:{},patternProperties:{}},xr="vscode://schemas/settings/resourceLanguage";var Sd=lt.as(Og.JSONContribution),Mg=class extends T{constructor(){super();this.registeredConfigurationDefaults=[];this.overrideIdentifiers=new Set;this._onDidSchemaChange=this._register(new x);this.onDidSchemaChange=this._onDidSchemaChange.event;this._onDidUpdateConfiguration=this._register(new x);this.onDidUpdateConfiguration=this._onDidUpdateConfiguration.event;this.configurationDefaultsOverrides=new Map,this.defaultLanguageConfigurationOverridesNode={id:"defaultOverrides",title:g(2143,null),properties:{}},this.configurationContributors=[this.defaultLanguageConfigurationOverridesNode],this.resourceLanguageSettingsSchema={properties:{},patternProperties:{},additionalProperties:!0,allowTrailingCommas:!0,allowComments:!0},this.configurationProperties={},this.policyConfigurations=new Map,this.excludedConfigurationProperties={},Sd.registerSchema(xr,this.resourceLanguageSettingsSchema),this.registerOverridePropertyPatternKey()}registerConfiguration(e,n=!0){return this.registerConfigurations([e],n),e}registerConfigurations(e,n=!0){let i=new Set;this.doRegisterConfigurations(e,n,i),Sd.registerSchema(xr,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:i})}deregisterConfigurations(e){let n=new Set;this.doDeregisterConfigurations(e,n),Sd.registerSchema(xr,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:n})}updateConfigurations({add:e,remove:n}){let i=new Set;this.doDeregisterConfigurations(n,i),this.doRegisterConfigurations(e,!1,i),Sd.registerSchema(xr,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:i})}registerDefaultConfigurations(e){let n=new Set;this.doRegisterDefaultConfigurations(e,n),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:n,defaultsOverrides:!0})}doRegisterDefaultConfigurations(e,n){this.registeredConfigurationDefaults.push(...e);let i=[];for(let{overrides:o,source:s}of e)for(let a in o){n.add(a);let l=this.configurationDefaultsOverrides.get(a)??this.configurationDefaultsOverrides.set(a,{configurationDefaultOverrides:[]}).get(a),c=o[a];if(l.configurationDefaultOverrides.push({value:c,source:s}),kn.test(a)){let u=this.mergeDefaultConfigurationsForOverrideIdentifier(a,c,s,l.configurationDefaultOverrideValue);if(!u)continue;l.configurationDefaultOverrideValue=u,this.updateDefaultOverrideProperty(a,u,s),i.push(...Ho(a))}else{let u=this.mergeDefaultConfigurationsForConfigurationProperty(a,c,s,l.configurationDefaultOverrideValue);if(!u)continue;l.configurationDefaultOverrideValue=u;let d=this.configurationProperties[a];d&&(this.updatePropertyDefaultValue(a,d),this.updateSchema(a,d))}}this.doRegisterOverrideIdentifiers(i)}deregisterDefaultConfigurations(e){let n=new Set;this.doDeregisterDefaultConfigurations(e,n),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:n,defaultsOverrides:!0})}doDeregisterDefaultConfigurations(e,n){for(let i of e){let o=this.registeredConfigurationDefaults.indexOf(i);o!==-1&&this.registeredConfigurationDefaults.splice(o,1)}for(let{overrides:i,source:o}of e)for(let s in i){let a=this.configurationDefaultsOverrides.get(s);if(!a)continue;let l=a.configurationDefaultOverrides.findIndex(c=>o?H0(c.source,o):c.value===i[s]);if(l!==-1){if(a.configurationDefaultOverrides.splice(l,1),a.configurationDefaultOverrides.length===0&&this.configurationDefaultsOverrides.delete(s),kn.test(s)){let c;for(let u of a.configurationDefaultOverrides)c=this.mergeDefaultConfigurationsForOverrideIdentifier(s,u.value,u.source,c);c&&!xl(c.value)?(a.configurationDefaultOverrideValue=c,this.updateDefaultOverrideProperty(s,c,o)):(this.configurationDefaultsOverrides.delete(s),delete this.configurationProperties[s],delete this.defaultLanguageConfigurationOverridesNode.properties[s])}else{let c;for(let d of a.configurationDefaultOverrides)c=this.mergeDefaultConfigurationsForConfigurationProperty(s,d.value,d.source,c);a.configurationDefaultOverrideValue=c;let u=this.configurationProperties[s];u&&(this.updatePropertyDefaultValue(s,u),this.updateSchema(s,u))}n.add(s)}}this.updateOverridePropertyPatternKey()}updateDefaultOverrideProperty(e,n,i){let o={section:{id:this.defaultLanguageConfigurationOverridesNode.id,title:this.defaultLanguageConfigurationOverridesNode.title,order:this.defaultLanguageConfigurationOverridesNode.order,extensionInfo:this.defaultLanguageConfigurationOverridesNode.extensionInfo},type:"object",default:n.value,description:g(2142,null,US(e)),$ref:xr,defaultDefaultValue:n.value,source:i,defaultValueSource:i};this.configurationProperties[e]=o,this.defaultLanguageConfigurationOverridesNode.properties[e]=o}mergeDefaultConfigurationsForOverrideIdentifier(e,n,i,o){let s=o?.value||{},a=o?.source??new Map;if(!(a instanceof Map)){console.error("objectConfigurationSources is not a Map");return}for(let l of Object.keys(n)){let c=n[l];if(Oe(c)&&(Mr(s[l])||Oe(s[l]))){if(s[l]={...s[l]??{},...c},i)for(let d in c)a.set(`${l}.${d}`,i)}else s[l]=c,i?a.set(l,i):a.delete(l)}return{value:s,source:a}}mergeDefaultConfigurationsForConfigurationProperty(e,n,i,o){let s=this.configurationProperties[e],a=o?.value??s?.defaultDefaultValue,l=i;if(Oe(n)&&(s!==void 0&&s.type==="object"||s===void 0&&(Mr(a)||Oe(a)))){if(l=o?.source??new Map,!(l instanceof Map)){console.error("defaultValueSource is not a Map");return}for(let u in n)i&&l.set(`${e}.${u}`,i);n={...Oe(a)?a:{},...n}}return{value:n,source:l}}deltaConfiguration(e){let n=!1,i=new Set;e.removedDefaults&&(this.doDeregisterDefaultConfigurations(e.removedDefaults,i),n=!0),e.addedDefaults&&(this.doRegisterDefaultConfigurations(e.addedDefaults,i),n=!0),e.removedConfigurations&&this.doDeregisterConfigurations(e.removedConfigurations,i),e.addedConfigurations&&this.doRegisterConfigurations(e.addedConfigurations,!1,i),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:i,defaultsOverrides:n})}notifyConfigurationSchemaUpdated(...e){this._onDidSchemaChange.fire()}registerOverrideIdentifiers(e){this.doRegisterOverrideIdentifiers(e),this._onDidSchemaChange.fire()}doRegisterOverrideIdentifiers(e){for(let n of e)this.overrideIdentifiers.add(n);this.updateOverridePropertyPatternKey()}doRegisterConfigurations(e,n,i){e.forEach(o=>{this.validateAndRegisterProperties(o,n,o.extensionInfo,o.restrictedProperties,void 0,i),this.configurationContributors.push(o),this.registerJSONConfiguration(o)})}doDeregisterConfigurations(e,n){let i=o=>{if(o.properties)for(let s in o.properties){n.add(s);let a=this.configurationProperties[s];a?.policy?.name&&this.policyConfigurations.delete(a.policy.name),delete this.configurationProperties[s],this.removeFromSchema(s,o.properties[s])}o.allOf?.forEach(s=>i(s))};for(let o of e){i(o);let s=this.configurationContributors.indexOf(o);s!==-1&&this.configurationContributors.splice(s,1)}}validateAndRegisterProperties(e,n=!0,i,o,s=4,a){s=sn(e.scope)?s:e.scope;let l=e.properties;if(l)for(let u in l){let d=l[u];if(d.section={id:e.id,title:e.title,order:e.order,extensionInfo:e.extensionInfo},n&&q0(u,d,i?.id)){delete l[u];continue}d.source=i,d.defaultDefaultValue=l[u].default,this.updatePropertyDefaultValue(u,d),kn.test(u)?d.scope=void 0:(d.scope=sn(d.scope)?s:d.scope,d.restricted=sn(d.restricted)?!!o?.includes(u):d.restricted),d.experiment?d.tags?.some(h=>h.toLowerCase()==="onexp")||(d.tags=d.tags??[],d.tags.push("onExP")):d.tags?.some(h=>h.toLowerCase()==="onexp")&&(console.error(`Invalid tag 'onExP' found for property '${u}'. Please use 'experiment' property instead.`),d.experiment={mode:"startup"});let f=l[u].hasOwnProperty("included")&&!l[u].included,m=l[u].policy?.name;f?(this.excludedConfigurationProperties[u]=l[u],m&&(this.policyConfigurations.set(m,u),a.add(u)),delete l[u]):(a.add(u),m&&this.policyConfigurations.set(m,u),this.configurationProperties[u]=l[u],!l[u].deprecationMessage&&l[u].markdownDeprecationMessage&&(l[u].deprecationMessage=l[u].markdownDeprecationMessage))}let c=e.allOf;if(c)for(let u of c)this.validateAndRegisterProperties(u,n,i,o,s,a)}getConfigurations(){return this.configurationContributors}getConfigurationProperties(){return this.configurationProperties}getPolicyConfigurations(){return this.policyConfigurations}getExcludedConfigurationProperties(){return this.excludedConfigurationProperties}getRegisteredDefaultConfigurations(){return[...this.registeredConfigurationDefaults]}getConfigurationDefaultsOverrides(){let e=new Map;for(let[n,i]of this.configurationDefaultsOverrides)i.configurationDefaultOverrideValue&&e.set(n,i.configurationDefaultOverrideValue);return e}registerJSONConfiguration(e){let n=i=>{let o=i.properties;if(o)for(let a in o)this.updateSchema(a,o[a]);i.allOf?.forEach(n)};n(e)}updateSchema(e,n){switch(gd.properties[e]=n,n.scope){case 1:md.properties[e]=n;break;case 2:yd.properties[e]=n;break;case 3:hd.properties[e]=n;break;case 7:vd.properties[e]=n;break;case 4:bd.properties[e]=n;break;case 5:Ha.properties[e]=n;break;case 6:Ha.properties[e]=n,this.resourceLanguageSettingsSchema.properties[e]=n;break}}removeFromSchema(e,n){switch(delete gd.properties[e],n.scope){case 1:delete md.properties[e];break;case 2:delete yd.properties[e];break;case 3:delete hd.properties[e];break;case 7:delete vd.properties[e];break;case 4:delete bd.properties[e];break;case 5:case 6:delete Ha.properties[e],delete this.resourceLanguageSettingsSchema.properties[e];break}}updateOverridePropertyPatternKey(){for(let e of this.overrideIdentifiers.values()){let n=`[${e}]`,i={type:"object",description:g(2144,null),errorMessage:g(2145,null),$ref:xr};this.updatePropertyDefaultValue(n,i),gd.properties[n]=i,md.properties[n]=i,hd.properties[n]=i,yd.properties[n]=i,vd.properties[n]=i,bd.properties[n]=i,Ha.properties[n]=i}}registerOverridePropertyPatternKey(){let e={type:"object",description:g(2144,null),errorMessage:g(2145,null),$ref:xr};gd.patternProperties[Wi]=e,md.patternProperties[Wi]=e,hd.patternProperties[Wi]=e,yd.patternProperties[Wi]=e,vd.patternProperties[Wi]=e,bd.patternProperties[Wi]=e,Ha.patternProperties[Wi]=e,this._onDidSchemaChange.fire()}updatePropertyDefaultValue(e,n){let i=this.configurationDefaultsOverrides.get(e)?.configurationDefaultOverrideValue,o,s;i&&(!n.disallowConfigurationDefault||!i.source)&&(o=i.value,s=i.source),Mr(o)&&(o=n.defaultDefaultValue,s=void 0),Mr(o)&&(o=z0(n.type)),n.default=o,n.defaultValueSource=s}},VS="\\[([^\\]]+)\\]",$S=new RegExp(VS,"g"),Wi=`^(${VS})+$`,kn=new RegExp(Wi);function Ho(r){let t=[];if(kn.test(r)){let e=$S.exec(r);for(;e?.length;){let n=e[1].trim();n&&t.push(n),e=$S.exec(r)}}return Bn(t)}function BS(r){return r.reduce((t,e)=>`${t}[${e}]`,"")}function z0(r){switch(Array.isArray(r)?r[0]:r){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};default:return null}}var Id=new Mg;lt.add(rn.Configuration,Id);function q0(r,t,e){return r.trim()?kn.test(r)?g(2141,null,r):Id.getConfigurationProperties()[r]!==void 0&&(!e||!K0.has(e.toLowerCase()))?g(2139,null,r):t.policy?.name&&Id.getPolicyConfigurations().get(t.policy?.name)!==void 0?g(2138,null,r,t.policy?.name,Id.getPolicyConfigurations().get(t.policy?.name)):null:g(2140,null)}var K0=new Set(Ut.defaultChatAgent?[Ut.defaultChatAgent.extensionId,Ut.defaultChatAgent.chatExtensionId].map(r=>r.toLowerCase()):[]);function za(r){return Object.isFrozen(r)?r:Jy(r)}var De=class r{constructor(t,e,n,i,o){this._contents=t;this._keys=e;this._overrides=n;this._raw=i;this.logService=o;this.overrideConfigurations=new Map}static createEmptyModel(t){return new r({},[],[],void 0,t)}get rawConfiguration(){if(!this._rawConfiguration)if(this._raw){let t=(Array.isArray(this._raw)?this._raw:[this._raw]).map(e=>{if(e instanceof r)return e;let n=new _d("",this.logService);return n.parseRaw(e),n.configurationModel});this._rawConfiguration=t.reduce((e,n)=>n===e?n:e.merge(n),t[0])}else this._rawConfiguration=this;return this._rawConfiguration}get contents(){return this._contents}get overrides(){return this._overrides}get keys(){return this._keys}get raw(){if(this._raw&&!(Array.isArray(this._raw)&&this._raw.every(t=>t instanceof r)))return this._raw}isEmpty(){return this._keys.length===0&&Object.keys(this._contents).length===0&&this._overrides.length===0}getValue(t){return t?Ba(this.contents,t):this.contents}inspect(t,e){let n=this;return{get value(){return za(n.rawConfiguration.getValue(t))},get override(){return e?za(n.rawConfiguration.getOverrideValue(t,e)):void 0},get merged(){return za(e?n.rawConfiguration.override(e).getValue(t):n.rawConfiguration.getValue(t))},get overrides(){let i=[];for(let{contents:o,identifiers:s,keys:a}of n.rawConfiguration.overrides){let l=new r(o,a,[],void 0,n.logService).getValue(t);l!==void 0&&i.push({identifiers:s,value:l})}return i.length?za(i):void 0}}}getOverrideValue(t,e){let n=this.getContentsForOverrideIdentifer(e);return n?t?Ba(n,t):n:void 0}getKeysForOverrideIdentifier(t){let e=[];for(let n of this.overrides)n.identifiers.includes(t)&&e.push(...n.keys);return Bn(e)}getAllOverrideIdentifiers(){let t=[];for(let e of this.overrides)t.push(...e.identifiers);return Bn(t)}override(t){let e=this.overrideConfigurations.get(t);return e||(e=this.createOverrideConfigurationModel(t),this.overrideConfigurations.set(t,e)),e}merge(...t){let e=Xt(this.contents),n=Xt(this.overrides),i=[...this.keys],o=this._raw?Array.isArray(this._raw)?[...this._raw]:[this._raw]:[this];for(let s of t)if(o.push(...s._raw?Array.isArray(s._raw)?s._raw:[s._raw]:[s]),!s.isEmpty()){this.mergeContents(e,s.contents);for(let a of s.overrides){let[l]=n.filter(c=>Vt(c.identifiers,a.identifiers));l?(this.mergeContents(l.contents,a.contents),l.keys.push(...a.keys),l.keys=Bn(l.keys)):n.push(Xt(a))}for(let a of s.keys)i.indexOf(a)===-1&&i.push(a)}return new r(e,i,n,!o.length||o.every(s=>s instanceof r)?void 0:o,this.logService)}createOverrideConfigurationModel(t){let e=this.getContentsForOverrideIdentifer(t);if(!e||typeof e!="object"||!Object.keys(e).length)return this;let n={};for(let i of Bn([...Object.keys(this.contents),...Object.keys(e)])){let o=this.contents[i],s=e[i];s&&(typeof o=="object"&&typeof s=="object"?(o=Xt(o),this.mergeContents(o,s)):o=s),n[i]=o}return new r(n,this.keys,this.overrides,void 0,this.logService)}mergeContents(t,e){for(let n of Object.keys(e)){if(n in t&&Oe(t[n])&&Oe(e[n])){this.mergeContents(t[n],e[n]);continue}t[n]=Xt(e[n])}}getContentsForOverrideIdentifer(t){let e=null,n=null,i=o=>{o&&(n?this.mergeContents(n,o):n=Xt(o))};for(let o of this.overrides)o.identifiers.length===1&&o.identifiers[0]===t?e=o.contents:o.identifiers.includes(t)&&i(o.contents);return i(e),n}toJSON(){return{contents:this.contents,overrides:this.overrides,keys:this.keys}}addValue(t,e){this.updateValue(t,e,!0)}setValue(t,e){this.updateValue(t,e,!1)}removeValue(t){let e=this.keys.indexOf(t);e!==-1&&(this.keys.splice(e,1),MS(this.contents,t),kn.test(t)&&this.overrides.splice(this.overrides.findIndex(n=>Vt(n.identifiers,Ho(t))),1))}updateValue(t,e,n){if(Ag(this.contents,t,e,i=>this.logService.error(i)),n=n||this.keys.indexOf(t)===-1,n&&this.keys.push(t),kn.test(t)){let i=this.contents[t],o=Ho(t),s={identifiers:o,keys:Object.keys(i),contents:fd(i,l=>this.logService.error(l))},a=this.overrides.findIndex(l=>Vt(l.identifiers,o));a!==-1?this.overrides[a]=s:this.overrides.push(s)}}},_d=class{constructor(t,e){this._name=t;this.logService=e;this._raw=null;this._configurationModel=null;this._restrictedConfigurations=[];this._parseErrors=[]}get configurationModel(){return this._configurationModel||De.createEmptyModel(this.logService)}get restrictedConfigurations(){return this._restrictedConfigurations}get errors(){return this._parseErrors}parse(t,e){if(!sn(t)){let n=this.doParseContent(t);this.parseRaw(n,e)}}reparse(t){this._raw&&this.parseRaw(this._raw,t)}parseRaw(t,e){this._raw=t;let{contents:n,keys:i,overrides:o,restricted:s,hasExcludedProperties:a}=this.doParseRaw(t,e);this._configurationModel=new De(n,i,o,a?[t]:void 0,this.logService),this._restrictedConfigurations=s||[]}doParseContent(t){let e={},n=null,i=[],o=[],s=[];function a(c){Array.isArray(i)?i.push(c):n!==null&&(i[n]=c)}let l={onObjectBegin:()=>{let c={};a(c),o.push(i),i=c,n=null},onObjectProperty:c=>{n=c},onObjectEnd:()=>{i=o.pop()},onArrayBegin:()=>{let c=[];a(c),o.push(i),i=c,n=null},onArrayEnd:()=>{i=o.pop()},onLiteralValue:a,onError:(c,u,d)=>{s.push({error:c,offset:u,length:d})}};if(t)try{$o(t,l),e=i[0]||{}}catch(c){this.logService.error(`Error while parsing settings file ${this._name}: ${c}`),this._parseErrors=[c]}return e}doParseRaw(t,e){let n=lt.as(rn.Configuration),i=n.getConfigurationProperties(),o=n.getExcludedConfigurationProperties(),s=this.filter(t,i,o,!0,e);t=s.raw;let a=fd(t,u=>this.logService.error(`Conflict in settings file ${this._name}: ${u}`)),l=Object.keys(t),c=this.toOverrides(t,u=>this.logService.error(`Conflict in settings file ${this._name}: ${u}`));return{contents:a,keys:l,overrides:c,restricted:s.restricted,hasExcludedProperties:s.hasExcludedProperties}}filter(t,e,n,i,o){let s=!1;if(!o?.scopes&&!o?.skipRestricted&&!o?.skipUnregistered&&!o?.exclude?.length)return{raw:t,restricted:[],hasExcludedProperties:s};let a={},l=[];for(let c in t)if(kn.test(c)&&i){let u=this.filter(t[c],e,n,!1,o);a[c]=u.raw,s=s||u.hasExcludedProperties,l.push(...u.restricted)}else{let u=e[c];u?.restricted&&l.push(c),this.shouldInclude(c,u,n,o)?a[c]=t[c]:s=!0}return{raw:a,restricted:l,hasExcludedProperties:s}}shouldInclude(t,e,n,i){if(i.exclude?.includes(t))return!1;if(i.include?.includes(t))return!0;if(i.skipRestricted&&e?.restricted||i.skipUnregistered&&!e)return!1;let o=e??n[t],s=o?typeof o.scope<"u"?o.scope:4:void 0;return s===void 0||i.scopes===void 0?!0:i.scopes.includes(s)}toOverrides(t,e){let n=[];for(let i of Object.keys(t))if(kn.test(i)){let o={},s=t[i];for(let a in s)o[a]=s[a];n.push({identifiers:Ho(i),keys:Object.keys(o),contents:fd(o,e)})}return n}},Cd=class extends T{constructor(e,n,i,o,s){super();this.userSettingsResource=e;this.parseOptions=n;this.fileService=o;this.logService=s;this._onDidChange=this._register(new x);this.onDidChange=this._onDidChange.event;this.parser=new _d(this.userSettingsResource.toString(),s),this._register(this.fileService.watch(i.dirname(this.userSettingsResource))),this._register(this.fileService.watch(this.userSettingsResource)),this._register(Q.any(Q.filter(this.fileService.onDidFilesChange,a=>a.contains(this.userSettingsResource)),Q.filter(this.fileService.onDidRunOperation,a=>(a.isOperation(0)||a.isOperation(3)||a.isOperation(1)||a.isOperation(4))&&i.isEqual(a.resource,e)))(()=>this._onDidChange.fire()))}async loadConfiguration(){try{let e=await this.fileService.readFile(this.userSettingsResource);return this.parser.parse(e.value.toString()||"{}",this.parseOptions),this.parser.configurationModel}catch{return De.createEmptyModel(this.logService)}}reparse(e){return e&&(this.parseOptions=e),this.parser.reparse(this.parseOptions),this.parser.configurationModel}getRestrictedSettings(){return this.parser.restrictedConfigurations}},Ng=class{constructor(t,e,n,i,o,s,a,l,c,u,d,f,m){this.key=t;this.overrides=e;this._value=n;this.overrideIdentifiers=i;this.defaultConfiguration=o;this.policyConfiguration=s;this.applicationConfiguration=a;this.userConfiguration=l;this.localUserConfiguration=c;this.remoteUserConfiguration=u;this.workspaceConfiguration=d;this.folderConfigurationModel=f;this.memoryConfigurationModel=m}get value(){return za(this._value)}toInspectValue(t){return t?.value!==void 0||t?.override!==void 0||t?.overrides!==void 0?t:void 0}get defaultInspectValue(){return this._defaultInspectValue||(this._defaultInspectValue=this.defaultConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._defaultInspectValue}get defaultValue(){return this.defaultInspectValue.merged}get default(){return this.toInspectValue(this.defaultInspectValue)}get policyInspectValue(){return this._policyInspectValue===void 0&&(this._policyInspectValue=this.policyConfiguration?this.policyConfiguration.inspect(this.key):null),this._policyInspectValue}get policyValue(){return this.policyInspectValue?.merged}get policy(){return this.policyInspectValue?.value!==void 0?{value:this.policyInspectValue.value}:void 0}get applicationInspectValue(){return this._applicationInspectValue===void 0&&(this._applicationInspectValue=this.applicationConfiguration?this.applicationConfiguration.inspect(this.key):null),this._applicationInspectValue}get applicationValue(){return this.applicationInspectValue?.merged}get application(){return this.toInspectValue(this.applicationInspectValue)}get userInspectValue(){return this._userInspectValue||(this._userInspectValue=this.userConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._userInspectValue}get userValue(){return this.userInspectValue.merged}get user(){return this.toInspectValue(this.userInspectValue)}get userLocalInspectValue(){return this._userLocalInspectValue||(this._userLocalInspectValue=this.localUserConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._userLocalInspectValue}get userLocalValue(){return this.userLocalInspectValue.merged}get userLocal(){return this.toInspectValue(this.userLocalInspectValue)}get userRemoteInspectValue(){return this._userRemoteInspectValue||(this._userRemoteInspectValue=this.remoteUserConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._userRemoteInspectValue}get userRemoteValue(){return this.userRemoteInspectValue.merged}get userRemote(){return this.toInspectValue(this.userRemoteInspectValue)}get workspaceInspectValue(){return this._workspaceInspectValue===void 0&&(this._workspaceInspectValue=this.workspaceConfiguration?this.workspaceConfiguration.inspect(this.key,this.overrides.overrideIdentifier):null),this._workspaceInspectValue}get workspaceValue(){return this.workspaceInspectValue?.merged}get workspace(){return this.toInspectValue(this.workspaceInspectValue)}get workspaceFolderInspectValue(){return this._workspaceFolderInspectValue===void 0&&(this._workspaceFolderInspectValue=this.folderConfigurationModel?this.folderConfigurationModel.inspect(this.key,this.overrides.overrideIdentifier):null),this._workspaceFolderInspectValue}get workspaceFolderValue(){return this.workspaceFolderInspectValue?.merged}get workspaceFolder(){return this.toInspectValue(this.workspaceFolderInspectValue)}get memoryInspectValue(){return this._memoryInspectValue===void 0&&(this._memoryInspectValue=this.memoryConfigurationModel.inspect(this.key,this.overrides.overrideIdentifier)),this._memoryInspectValue}get memoryValue(){return this.memoryInspectValue.merged}get memory(){return this.toInspectValue(this.memoryInspectValue)}},zo=class r{constructor(t,e,n,i,o,s,a,l,c,u){this._defaultConfiguration=t;this._policyConfiguration=e;this._applicationConfiguration=n;this._localUserConfiguration=i;this._remoteUserConfiguration=o;this._workspaceConfiguration=s;this._folderConfigurations=a;this._memoryConfiguration=l;this._memoryConfigurationByResource=c;this.logService=u;this._workspaceConsolidatedConfiguration=null;this._foldersConsolidatedConfigurations=new Fe;this._userConfiguration=null}getValue(t,e,n){return this.getConsolidatedConfigurationModel(t,e,n).getValue(t)}updateValue(t,e,n={}){let i;n.resource?(i=this._memoryConfigurationByResource.get(n.resource),i||(i=De.createEmptyModel(this.logService),this._memoryConfigurationByResource.set(n.resource,i))):i=this._memoryConfiguration,e===void 0?i.removeValue(t):i.setValue(t,e),n.resource||(this._workspaceConsolidatedConfiguration=null)}inspect(t,e,n){let i=this.getConsolidatedConfigurationModel(t,e,n),o=this.getFolderConfigurationModelForResource(e.resource,n),s=e.resource?this._memoryConfigurationByResource.get(e.resource)||this._memoryConfiguration:this._memoryConfiguration,a=new Set;for(let l of i.overrides)for(let c of l.identifiers)i.getOverrideValue(t,c)!==void 0&&a.add(c);return new Ng(t,e,i.getValue(t),a.size?[...a]:void 0,this._defaultConfiguration,this._policyConfiguration.isEmpty()?void 0:this._policyConfiguration,this.applicationConfiguration.isEmpty()?void 0:this.applicationConfiguration,this.userConfiguration,this.localUserConfiguration,this.remoteUserConfiguration,n?this._workspaceConfiguration:void 0,o||void 0,s)}keys(t){let e=this.getFolderConfigurationModelForResource(void 0,t);return{default:this._defaultConfiguration.keys.slice(0),policy:this._policyConfiguration.keys.slice(0),user:this.userConfiguration.keys.slice(0),workspace:this._workspaceConfiguration.keys.slice(0),workspaceFolder:e?e.keys.slice(0):[]}}updateDefaultConfiguration(t){this._defaultConfiguration=t,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updatePolicyConfiguration(t){this._policyConfiguration=t}updateApplicationConfiguration(t){this._applicationConfiguration=t,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateLocalUserConfiguration(t){this._localUserConfiguration=t,this._userConfiguration=null,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateRemoteUserConfiguration(t){this._remoteUserConfiguration=t,this._userConfiguration=null,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateWorkspaceConfiguration(t){this._workspaceConfiguration=t,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateFolderConfiguration(t,e){this._folderConfigurations.set(t,e),this._foldersConsolidatedConfigurations.delete(t)}deleteFolderConfiguration(t){this.folderConfigurations.delete(t),this._foldersConsolidatedConfigurations.delete(t)}compareAndUpdateDefaultConfiguration(t,e){let n=[];if(!e){let{added:i,updated:o,removed:s}=$i(this._defaultConfiguration,t);e=[...i,...o,...s]}for(let i of e)for(let o of Ho(i)){let s=this._defaultConfiguration.getKeysForOverrideIdentifier(o),a=t.getKeysForOverrideIdentifier(o),l=[...a.filter(c=>s.indexOf(c)===-1),...s.filter(c=>a.indexOf(c)===-1),...s.filter(c=>!Me(this._defaultConfiguration.override(o).getValue(c),t.override(o).getValue(c)))];n.push([o,l])}return this.updateDefaultConfiguration(t),{keys:e,overrides:n}}compareAndUpdatePolicyConfiguration(t){let{added:e,updated:n,removed:i}=$i(this._policyConfiguration,t),o=[...e,...n,...i];return o.length&&this.updatePolicyConfiguration(t),{keys:o,overrides:[]}}compareAndUpdateApplicationConfiguration(t){let{added:e,updated:n,removed:i,overrides:o}=$i(this.applicationConfiguration,t),s=[...e,...n,...i];return s.length&&this.updateApplicationConfiguration(t),{keys:s,overrides:o}}compareAndUpdateLocalUserConfiguration(t){let{added:e,updated:n,removed:i,overrides:o}=$i(this.localUserConfiguration,t),s=[...e,...n,...i];return s.length&&this.updateLocalUserConfiguration(t),{keys:s,overrides:o}}compareAndUpdateRemoteUserConfiguration(t){let{added:e,updated:n,removed:i,overrides:o}=$i(this.remoteUserConfiguration,t),s=[...e,...n,...i];return s.length&&this.updateRemoteUserConfiguration(t),{keys:s,overrides:o}}compareAndUpdateWorkspaceConfiguration(t){let{added:e,updated:n,removed:i,overrides:o}=$i(this.workspaceConfiguration,t),s=[...e,...n,...i];return s.length&&this.updateWorkspaceConfiguration(t),{keys:s,overrides:o}}compareAndUpdateFolderConfiguration(t,e){let n=this.folderConfigurations.get(t),{added:i,updated:o,removed:s,overrides:a}=$i(n,e),l=[...i,...o,...s];return(l.length||!n)&&this.updateFolderConfiguration(t,e),{keys:l,overrides:a}}compareAndDeleteFolderConfiguration(t){let e=this.folderConfigurations.get(t);if(!e)throw new Error("Unknown folder");this.deleteFolderConfiguration(t);let{added:n,updated:i,removed:o,overrides:s}=$i(e,void 0);return{keys:[...n,...i,...o],overrides:s}}get defaults(){return this._defaultConfiguration}get applicationConfiguration(){return this._applicationConfiguration}get userConfiguration(){if(!this._userConfiguration)if(this._remoteUserConfiguration.isEmpty())this._userConfiguration=this._localUserConfiguration;else{let t=this._localUserConfiguration.merge(this._remoteUserConfiguration);this._userConfiguration=new De(t.contents,t.keys,t.overrides,void 0,this.logService)}return this._userConfiguration}get localUserConfiguration(){return this._localUserConfiguration}get remoteUserConfiguration(){return this._remoteUserConfiguration}get workspaceConfiguration(){return this._workspaceConfiguration}get folderConfigurations(){return this._folderConfigurations}getConsolidatedConfigurationModel(t,e,n){let i=this.getConsolidatedConfigurationModelForResource(e,n);if(e.overrideIdentifier&&(i=i.override(e.overrideIdentifier)),!this._policyConfiguration.isEmpty()&&this._policyConfiguration.getValue(t)!==void 0){i=i.merge();for(let o of this._policyConfiguration.keys)i.setValue(o,this._policyConfiguration.getValue(o))}return i}getConsolidatedConfigurationModelForResource({resource:t},e){let n=this.getWorkspaceConsolidatedConfiguration();if(e&&t){let i=e.getFolder(t);i&&(n=this.getFolderConsolidatedConfiguration(i.uri)||n);let o=this._memoryConfigurationByResource.get(t);o&&(n=n.merge(o))}return n}getWorkspaceConsolidatedConfiguration(){return this._workspaceConsolidatedConfiguration||(this._workspaceConsolidatedConfiguration=this._defaultConfiguration.merge(this.applicationConfiguration,this.userConfiguration,this._workspaceConfiguration,this._memoryConfiguration)),this._workspaceConsolidatedConfiguration}getFolderConsolidatedConfiguration(t){let e=this._foldersConsolidatedConfigurations.get(t);if(!e){let n=this.getWorkspaceConsolidatedConfiguration(),i=this._folderConfigurations.get(t);i?(e=n.merge(i),this._foldersConsolidatedConfigurations.set(t,e)):e=n}return e}getFolderConfigurationModelForResource(t,e){if(e&&t){let n=e.getFolder(t);if(n)return this._folderConfigurations.get(n.uri)}}toData(){return{defaults:{contents:this._defaultConfiguration.contents,overrides:this._defaultConfiguration.overrides,keys:this._defaultConfiguration.keys},policy:{contents:this._policyConfiguration.contents,overrides:this._policyConfiguration.overrides,keys:this._policyConfiguration.keys},application:{contents:this.applicationConfiguration.contents,overrides:this.applicationConfiguration.overrides,keys:this.applicationConfiguration.keys,raw:Array.isArray(this.applicationConfiguration.raw)?void 0:this.applicationConfiguration.raw},userLocal:{contents:this.localUserConfiguration.contents,overrides:this.localUserConfiguration.overrides,keys:this.localUserConfiguration.keys,raw:Array.isArray(this.localUserConfiguration.raw)?void 0:this.localUserConfiguration.raw},userRemote:{contents:this.remoteUserConfiguration.contents,overrides:this.remoteUserConfiguration.overrides,keys:this.remoteUserConfiguration.keys,raw:Array.isArray(this.remoteUserConfiguration.raw)?void 0:this.remoteUserConfiguration.raw},workspace:{contents:this._workspaceConfiguration.contents,overrides:this._workspaceConfiguration.overrides,keys:this._workspaceConfiguration.keys},folders:[...this._folderConfigurations.keys()].reduce((t,e)=>{let{contents:n,overrides:i,keys:o}=this._folderConfigurations.get(e);return t.push([e,{contents:n,overrides:i,keys:o}]),t},[])}}allKeys(){let t=new Set;return this._defaultConfiguration.keys.forEach(e=>t.add(e)),this.userConfiguration.keys.forEach(e=>t.add(e)),this._workspaceConfiguration.keys.forEach(e=>t.add(e)),this._folderConfigurations.forEach(e=>e.keys.forEach(n=>t.add(n))),[...t.values()]}allOverrideIdentifiers(){let t=new Set;return this._defaultConfiguration.getAllOverrideIdentifiers().forEach(e=>t.add(e)),this.userConfiguration.getAllOverrideIdentifiers().forEach(e=>t.add(e)),this._workspaceConfiguration.getAllOverrideIdentifiers().forEach(e=>t.add(e)),this._folderConfigurations.forEach(e=>e.getAllOverrideIdentifiers().forEach(n=>t.add(n))),[...t.values()]}getAllKeysForOverrideIdentifier(t){let e=new Set;return this._defaultConfiguration.getKeysForOverrideIdentifier(t).forEach(n=>e.add(n)),this.userConfiguration.getKeysForOverrideIdentifier(t).forEach(n=>e.add(n)),this._workspaceConfiguration.getKeysForOverrideIdentifier(t).forEach(n=>e.add(n)),this._folderConfigurations.forEach(n=>n.getKeysForOverrideIdentifier(t).forEach(i=>e.add(i))),[...e.values()]}static parse(t,e){let n=this.parseConfigurationModel(t.defaults,e),i=this.parseConfigurationModel(t.policy,e),o=this.parseConfigurationModel(t.application,e),s=this.parseConfigurationModel(t.userLocal,e),a=this.parseConfigurationModel(t.userRemote,e),l=this.parseConfigurationModel(t.workspace,e),c=t.folders.reduce((u,d)=>(u.set(y.revive(d[0]),this.parseConfigurationModel(d[1],e)),u),new Fe);return new r(n,i,o,s,a,l,c,De.createEmptyModel(e),new Fe,e)}static parseConfigurationModel(t,e){return new De(t.contents,t.keys,t.overrides,t.raw,e)}};var Td=class{constructor(t,e,n,i,o){this.change=t;this.previous=e;this.currentConfiguraiton=n;this.currentWorkspace=i;this.logService=o;this._marker=`
`;this._markerCode1=this._marker.charCodeAt(0);this._markerCode2=46;this.affectedKeys=new Set;this._previousConfiguration=void 0;for(let s of t.keys)this.affectedKeys.add(s);for(let[,s]of t.overrides)for(let a of s)this.affectedKeys.add(a);this._affectsConfigStr=this._marker;for(let s of this.affectedKeys)this._affectsConfigStr+=s+this._marker}get previousConfiguration(){return!this._previousConfiguration&&this.previous&&(this._previousConfiguration=zo.parse(this.previous.data,this.logService)),this._previousConfiguration}affectsConfiguration(t,e){let n=this._marker+t,i=this._affectsConfigStr.indexOf(n);if(i<0)return!1;let o=i+n.length;if(o>=this._affectsConfigStr.length)return!1;let s=this._affectsConfigStr.charCodeAt(o);if(s!==this._markerCode1&&s!==this._markerCode2)return!1;if(e){let a=this.previousConfiguration?this.previousConfiguration.getValue(t,e,this.previous?.workspace):void 0,l=this.currentConfiguraiton.getValue(t,e,this.currentWorkspace);return!Me(a,l)}return!0}};function $i(r,t){let{added:e,removed:n,updated:i}=HS(t?.rawConfiguration,r?.rawConfiguration),o=[],s=r?.getAllOverrideIdentifiers()||[],a=t?.getAllOverrideIdentifiers()||[];if(t){let l=a.filter(c=>!s.includes(c));for(let c of l)o.push([c,t.getKeysForOverrideIdentifier(c)])}if(r){let l=s.filter(c=>!a.includes(c));for(let c of l)o.push([c,r.getKeysForOverrideIdentifier(c)])}if(t&&r){for(let l of s)if(a.includes(l)){let c=HS({contents:r.getOverrideValue(void 0,l)||{},keys:r.getKeysForOverrideIdentifier(l)},{contents:t.getOverrideValue(void 0,l)||{},keys:t.getKeysForOverrideIdentifier(l)});o.push([l,[...c.added,...c.removed,...c.updated]])}}return{added:e,removed:n,updated:i,overrides:o}}function HS(r,t){let e=r?t?r.keys.filter(o=>t.keys.indexOf(o)===-1):[...r.keys]:[],n=t?r?t.keys.filter(o=>r.keys.indexOf(o)===-1):[...t.keys]:[],i=[];if(r&&t){for(let o of t.keys)if(r.keys.indexOf(o)!==-1){let s=Ba(t.contents,o),a=Ba(r.contents,o);Me(s,a)||i.push(o)}}return{added:e,removed:n,updated:i}}var qS=V("policy");var qo=class{constructor(){this.onDidChange=Q.None;this.policyDefinitions={}}async updatePolicyDefinitions(){return{}}getPolicyValue(){}serialize(){}};var xd=class extends T{constructor(e){super();this.logService=e;this._onDidChangeConfiguration=this._register(new x);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=De.createEmptyModel(e)}get configurationModel(){return this._configurationModel}async initialize(){return this.resetConfigurationModel(),this._register(lt.as(rn.Configuration).onDidUpdateConfiguration(({properties:e,defaultsOverrides:n})=>this.onDidUpdateConfiguration(Array.from(e),n))),this.configurationModel}reload(){return this.resetConfigurationModel(),this.configurationModel}onDidUpdateConfiguration(e,n){this.updateConfigurationModel(e,lt.as(rn.Configuration).getConfigurationProperties()),this._onDidChangeConfiguration.fire({defaults:this.configurationModel,properties:e})}getConfigurationDefaultOverrides(){return{}}resetConfigurationModel(){this._configurationModel=De.createEmptyModel(this.logService);let e=lt.as(rn.Configuration).getConfigurationProperties();this.updateConfigurationModel(Object.keys(e),e)}updateConfigurationModel(e,n){let i=this.getConfigurationDefaultOverrides();for(let o of e){let s=i[o],a=n[o];s!==void 0?this._configurationModel.setValue(o,s):a?this._configurationModel.setValue(o,this.getDefaultValue(o,a)):this._configurationModel.removeValue(o)}}getDefaultValue(e,n){return Xt(n.default)}},wd=class{constructor(){this.onDidChangeConfiguration=Q.None;this.configurationModel=De.createEmptyModel(new Rc)}async initialize(){return this.configurationModel}},Ko=class extends T{constructor(e,n,i){super();this.defaultConfiguration=e;this.policyService=n;this.logService=i;this._onDidChangeConfiguration=this._register(new x);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=De.createEmptyModel(this.logService),this.configurationRegistry=lt.as(rn.Configuration)}get configurationModel(){return this._configurationModel}async initialize(){return this.logService.trace("PolicyConfiguration#initialize"),this.update(await this.updatePolicyDefinitions(this.defaultConfiguration.configurationModel.keys),!1),this.update(await this.updatePolicyDefinitions(Object.keys(this.configurationRegistry.getExcludedConfigurationProperties())),!1),this._register(this.policyService.onDidChange(e=>this.onDidChangePolicies(e))),this._register(this.defaultConfiguration.onDidChangeConfiguration(async({properties:e})=>this.update(await this.updatePolicyDefinitions(e),!0))),this._configurationModel}async updatePolicyDefinitions(e){this.logService.trace("PolicyConfiguration#updatePolicyDefinitions",e);let n={},i=[],o=this.configurationRegistry.getConfigurationProperties(),s=this.configurationRegistry.getExcludedConfigurationProperties();for(let a of e){let l=o[a]??s[a];if(!l){i.push(a);continue}if(l.policy){if(l.type!=="string"&&l.type!=="number"&&l.type!=="array"&&l.type!=="object"&&l.type!=="boolean"){this.logService.warn(`Policy ${l.policy.name} has unsupported type ${l.type}`);continue}let{value:c,restrictedValue:u}=l.policy;i.push(a),n[l.policy.name]={type:l.type==="number"?"number":l.type==="boolean"?"boolean":"string",value:c,restrictedValue:u}}}return xl(n)||await this.policyService.updatePolicyDefinitions(n),i}onDidChangePolicies(e){this.logService.trace("PolicyConfiguration#onDidChangePolicies",e);let n=this.configurationRegistry.getPolicyConfigurations(),i=Or(e.map(o=>n.get(o)));this.update(i,!0)}update(e,n){this.logService.trace("PolicyConfiguration#update",e);let i=this.configurationRegistry.getConfigurationProperties(),o=this.configurationRegistry.getExcludedConfigurationProperties(),s=[],a=this._configurationModel.isEmpty();for(let l of e){let c=i[l]??o[l],u=c?.policy?.name;if(u){let d=this.policyService.getPolicyValue(u);if(Pe(d)&&c.type!=="string")try{d=this.parse(d)}catch(f){this.logService.error(`Error parsing policy value ${u}:`,Sl(f));continue}(a?d!==void 0:!Me(this._configurationModel.getValue(l),d))&&s.push([l,d])}else this._configurationModel.getValue(l)!==void 0&&s.push([l,void 0])}if(s.length){this.logService.trace("PolicyConfiguration#changed",s);let l=this._configurationModel;this._configurationModel=De.createEmptyModel(this.logService);for(let c of l.keys)this._configurationModel.setValue(c,l.getValue(c));for(let[c,u]of s)u===void 0?this._configurationModel.removeValue(c):this._configurationModel.setValue(c,u);n&&this._onDidChangeConfiguration.fire(this._configurationModel)}}parse(e){let n={},i=null,o=[],s=[],a=[];function l(u){if(Array.isArray(o))o.push(u);else if(i!==null){if(o[i]!==void 0)throw new Error(`Duplicate property found: ${i}`);o[i]=u}}if(e&&($o(e,{onObjectBegin:()=>{let u={};l(u),s.push(o),o=u,i=null},onObjectProperty:u=>{i=u},onObjectEnd:()=>{o=s.pop()},onArrayBegin:()=>{let u=[];l(u),s.push(o),o=u,i=null},onArrayEnd:()=>{o=s.pop()},onLiteralValue:l,onError:(u,d,f)=>{a.push({error:u,offset:d,length:f})}}),n=o[0]||n),a.length>0)throw new Error(a.map(u=>Sl(u.error)).join(`
`));return n}};Ko=w([C(1,qS),C(2,L)],Ko);var Rd=class extends T{constructor(e,n,i,o){super();this.settingsResource=e;this.logService=o;this._onDidChangeConfiguration=this._register(new x);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this.defaultConfiguration=this._register(new xd(o)),this.policyConfiguration=i instanceof qo?new wd:this._register(new Ko(this.defaultConfiguration,i,o)),this.userConfiguration=this._register(new Cd(this.settingsResource,{},Ve,n,o)),this.configuration=new zo(this.defaultConfiguration.configurationModel,this.policyConfiguration.configurationModel,De.createEmptyModel(o),De.createEmptyModel(o),De.createEmptyModel(o),De.createEmptyModel(o),new Fe,De.createEmptyModel(o),new Fe,o),this.configurationEditing=new Ug(e,n,this),this.reloadConfigurationScheduler=this._register(new wi(()=>this.reloadConfiguration(),50)),this._register(this.defaultConfiguration.onDidChangeConfiguration(({defaults:s,properties:a})=>this.onDidDefaultConfigurationChange(s,a))),this._register(this.policyConfiguration.onDidChangeConfiguration(s=>this.onDidPolicyConfigurationChange(s))),this._register(this.userConfiguration.onDidChange(()=>this.reloadConfigurationScheduler.schedule()))}async initialize(){let[e,n,i]=await Promise.all([this.defaultConfiguration.initialize(),this.policyConfiguration.initialize(),this.userConfiguration.loadConfiguration()]);this.configuration=new zo(e,n,De.createEmptyModel(this.logService),i,De.createEmptyModel(this.logService),De.createEmptyModel(this.logService),new Fe,De.createEmptyModel(this.logService),new Fe,this.logService)}getConfigurationData(){return this.configuration.toData()}getValue(e,n){let i=typeof e=="string"?e:void 0,o=pd(e)?e:pd(n)?n:{};return this.configuration.getValue(i,o,void 0)}async updateValue(e,n,i,o,s){let a=LS(i)?i:pd(i)?{resource:i.resource,overrideIdentifiers:i.overrideIdentifier?[i.overrideIdentifier]:void 0}:void 0,l=a?o:i;if(l!==void 0&&l!==3&&l!==2)throw new Error(`Unable to write ${e} to target ${l}.`);a?.overrideIdentifiers&&(a.overrideIdentifiers=Bn(a.overrideIdentifiers),a.overrideIdentifiers=a.overrideIdentifiers.length?a.overrideIdentifiers:void 0);let c=this.inspect(e,{resource:a?.resource,overrideIdentifier:a?.overrideIdentifiers?a.overrideIdentifiers[0]:void 0});if(c.policyValue!==void 0)throw new Error(`Unable to write ${e} because it is configured in system policy.`);if(Me(n,c.defaultValue)&&(n=void 0),a?.overrideIdentifiers?.length&&a.overrideIdentifiers.length>1){let d=a.overrideIdentifiers.sort(),f=this.configuration.localUserConfiguration.overrides.find(m=>Vt([...m.identifiers].sort(),d));f&&(a.overrideIdentifiers=f.identifiers)}let u=a?.overrideIdentifiers?.length?[BS(a.overrideIdentifiers),e]:[e];await this.configurationEditing.write(u,n),await this.reloadConfiguration()}inspect(e,n={}){return this.configuration.inspect(e,n,void 0)}keys(){return this.configuration.keys(void 0)}async reloadConfiguration(){let e=await this.userConfiguration.loadConfiguration();this.onDidChangeUserConfiguration(e)}onDidChangeUserConfiguration(e){let n=this.configuration.toData(),i=this.configuration.compareAndUpdateLocalUserConfiguration(e);this.trigger(i,n,2)}onDidDefaultConfigurationChange(e,n){let i=this.configuration.toData(),o=this.configuration.compareAndUpdateDefaultConfiguration(e,n);this.trigger(o,i,7)}onDidPolicyConfigurationChange(e){let n=this.configuration.toData(),i=this.configuration.compareAndUpdatePolicyConfiguration(e);this.trigger(i,n,7)}trigger(e,n,i){let o=new Td(e,{data:n},this.configuration,void 0,this.logService);o.source=i,this._onDidChangeConfiguration.fire(o)}},Ug=class{constructor(t,e,n){this.settingsResource=t;this.fileService=e;this.configurationService=n;this.queue=new xi}write(t,e){return this.queue.queue(()=>this.doWriteConfiguration(t,e))}async doWriteConfiguration(t,e){let n;try{n=(await this.fileService.readFile(this.settingsResource)).value.toString()}catch(s){if(s.fileOperationResult===1)n="{}";else throw s}let i=[];if(ud(n,i,{allowTrailingComma:!0,allowEmptyContent:!0}),i.length>0)throw new Error("Unable to write into the settings file. Please open the file to correct errors/warnings in the file and try again.");let o=this.getEdits(n,t,e);n=DS(n,o),await this.fileService.writeFile(this.settingsResource,k.fromString(n))}getEdits(t,e,n){let{tabSize:i,insertSpaces:o,eol:s}=this.formattingOptions;if(!e.length){let a=JSON.stringify(n,null,o?" ".repeat(i):"	");return[{content:a,length:a.length,offset:0}]}return AS(t,e,n,{tabSize:i,insertSpaces:o,eol:s})}get formattingOptions(){if(!this._formattingOptions){let t=mt===3||mt===2?`
`:`\r
`,e=this.configurationService.getValue("files.eol",{overrideIdentifier:"jsonc"});e&&typeof e=="string"&&e!=="auto"&&(t=e),this._formattingOptions={eol:t,insertSpaces:!!this.configurationService.getValue("editor.insertSpaces",{overrideIdentifier:"jsonc"}),tabSize:this.configurationService.getValue("editor.tabSize",{overrideIdentifier:"jsonc"})}}return this._formattingOptions}};var NH=V("requestService"),JS="NO_FETCH_TELEMETRY";var G0=!1,Fg=[],jS,GS;function J0(r=!0,t=!0){if(jS===r&&GS===t)return;jS=r,GS=t;let e=lt.as(rn.Configuration),n=Fg;Fg=[{id:"http",order:15,title:g(2514,null),type:"object",scope:2,properties:{"http.useLocalProxyConfiguration":{type:"boolean",default:t,markdownDescription:g(2529,null),restricted:!0}}},{id:"http",order:15,title:g(2514,null),type:"object",scope:1,properties:{"http.electronFetch":{type:"boolean",default:!1,description:g(2512,null),restricted:!0}}},{id:"http",order:15,title:g(2514,null),type:"object",scope:r?1:2,properties:{"http.proxy":{type:"string",pattern:"^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",markdownDescription:g(2517,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyStrictSSL":{type:"boolean",default:!0,markdownDescription:g(2525,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyKerberosServicePrincipal":{type:"string",markdownDescription:g(2519,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.noProxy":{type:"array",items:{type:"string"},markdownDescription:g(2516,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyAuthorization":{type:["null","string"],default:null,markdownDescription:g(2518,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxySupport":{type:"string",enum:["off","on","fallback","override"],enumDescriptions:[g(2522,null),g(2523,null),g(2521,null),g(2524,null)],default:"override",markdownDescription:g(2520,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificates":{type:"boolean",default:!0,markdownDescription:g(2526,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificatesNode":{type:"boolean",tags:["experimental"],default:G0,markdownDescription:g(2527,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}},"http.experimental.systemCertificatesV2":{type:"boolean",tags:["experimental"],default:!1,markdownDescription:g(2528,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.fetchAdditionalSupport":{type:"boolean",default:!0,markdownDescription:g(2513,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.webSocketAdditionalSupport":{type:"boolean",default:!0,markdownDescription:g(2530,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.experimental.networkInterfaceCheckInterval":{type:"number",default:300,minimum:-1,tags:["experimental"],markdownDescription:g(2515,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}}}}],e.updateConfigurations({add:Fg,remove:n})}J0();var Q0=!1,$g=class{constructor(t,e,n){this.id=t;this.dependencies=e;this.callback=n}};var Vg=class r{constructor(){this._isWebWorker=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope";this._isRenderer=typeof document=="object";this._defineCalls=[];this._state=1}static{this.INSTANCE=new r}_initialize(){if(this._state===1){if(globalThis.define){this._state=3;return}}else return;this._state=2,globalThis.define=(t,e,n)=>{typeof t!="string"&&(n=e,e=t,t=null),(typeof e!="object"||!Array.isArray(e))&&(n=e,e=null),this._defineCalls.push(new $g(t,e,n))},globalThis.define.amd=!0,this._isRenderer?this._amdPolicy=globalThis._VSCODE_WEB_PACKAGE_TTP??window.trustedTypes?.createPolicy("amdLoader",{createScriptURL(t){if(t.startsWith(window.location.origin)||t.startsWith(`${oe.vscodeFileResource}://${Xp}`))return t;throw new Error(`[trusted_script_src] Invalid script url: ${t}`)}}):this._isWebWorker&&(this._amdPolicy=globalThis._VSCODE_WEB_PACKAGE_TTP??globalThis.trustedTypes?.createPolicy("amdLoader",{createScriptURL(t){return t}}))}async load(t){if(this._initialize(),this._state===3)return new Promise(s=>{let a=q();globalThis.define(a,[t],function(l){s(l)})});let e=await(this._isWebWorker?this._workerLoadScript(t):this._isRenderer?this._rendererLoadScript(t):this._nodeJSLoadScript(t));if(!e){console.warn(`Did not receive a define call from script ${t}`);return}let n={},i=[],o=[];if(Array.isArray(e.dependencies))for(let s of e.dependencies)s==="exports"?i.push(n):o.push(s);if(o.length>0)throw new Error(`Cannot resolve dependencies for script ${t}. The dependencies are: ${o.join(", ")}`);return typeof e.callback=="function"?e.callback(...i)??n:e.callback}_rendererLoadScript(t){return new Promise((e,n)=>{let i=document.createElement("script");i.setAttribute("async","async"),i.setAttribute("type","text/javascript");let o=()=>{i.removeEventListener("load",s),i.removeEventListener("error",a)},s=l=>{o(),e(this._defineCalls.pop())},a=l=>{o(),n(l)};i.addEventListener("load",s),i.addEventListener("error",a),this._amdPolicy&&(t=this._amdPolicy.createScriptURL(t)),i.setAttribute("src",t),window.document.getElementsByTagName("head")[0].appendChild(i)})}async _workerLoadScript(t){return this._amdPolicy&&(t=this._amdPolicy.createScriptURL(t)),await import(t),this._defineCalls.pop()}async _nodeJSLoadScript(t){try{let e=(await import("fs")).default,n=(await import("vm")).default,i=(await import("module")).default,o=y.parse(t).fsPath,s=e.readFileSync(o).toString(),a=i.wrap(s.replace(/^#!.*/,""));return new n.Script(a).runInThisContext().apply(),this._defineCalls.pop()}catch(e){throw e}}},Wg=new Map;async function Bg(r,t,e){e===void 0&&(e=!!(globalThis._VSCODE_PRODUCT_JSON??globalThis.vscode?.context?.configuration()?.product)?.commit);let n=t?`${r}/${t}`:r;if(Wg.has(n))return Wg.get(n);let i;if(/^\w[\w\d+.-]*:\/\//.test(n))i=n;else{let l=`${Q0&&e&&!It?wy:xy}/${n}`;i=rt.asBrowserUri(l).toString(!0)}let o=Vg.INSTANCE.load(i);return Wg.set(n,o),o}function Y0(r){if(kp===2&&/^penguin(\.|$)/i.test(r))return"chromebook"}function QS(r,t,e,n,i,o,s,a,l,c,u){let d=Object.create(null);d["common.machineId"]=o,d["common.sqmId"]=s,d["common.devDeviceId"]=a,d.sessionID=q()+Date.now(),d.commitHash=n,d.version=i,d["common.releaseDate"]=c,d["common.platformVersion"]=(r||"").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/,"$1$2$3"),d["common.platform"]=Fh(kp),d["common.nodePlatform"]=Vr,d["common.nodeArch"]=e,d["common.product"]=u||"desktop",l&&(d["common.msftInternal"]=l);let f=0,m=Date.now();Object.defineProperties(d,{timestamp:{get:()=>new Date,enumerable:!0},"common.timesincesessionstart":{get:()=>Date.now()-m,enumerable:!0},"common.sequence":{get:()=>f++,enumerable:!0}}),Wh&&(d["common.snap"]="true");let h=Y0(t);return h&&(d["common.platformDetail"]=h),d}function YS(r){let t=ke.USERDNSDOMAIN;if(!t)return!1;let e=t.toLowerCase();return r.some(n=>e===n)}var qa=class{constructor(t){this.value=t;this.isTrustedTelemetryValue=!0}},Hg=class{constructor(){this.telemetryLevel=0;this.sessionId="someValue.sessionId";this.machineId="someValue.machineId";this.sqmId="someValue.sqmId";this.devDeviceId="someValue.devDeviceId";this.firstSessionDate="someValue.firstSessionDate";this.sendErrorTelemetry=!1}publicLog(){}publicLog2(){}publicLogError(){}publicLogError2(){}setExperimentProperty(){}setCommonProperty(){}},Ed=new Hg;var zg="telemetry",XS={id:zg,name:g(2554,null)};function ZS(r,t){return!t.isBuilt&&!t.disableTelemetry?!0:!(t.disableTelemetry||!r.enableTelemetry)}function Pd(r,t){return t.extensionTestsLocationURI?!0:!(t.isBuilt||t.disableTelemetry||r.enableTelemetry&&r.aiConfig?.ariaKey)}function eI(r){let t=r.getValue(To),e=r.getValue(Mc);if(r.getValue(wa)===!1||e===!1)return 0;switch(t??"all"){case"all":return 3;case"error":return 2;case"crash":return 1;case"off":return 0}}function kd(r){let t={},e={},n={};tI(r,n);for(let i in n){i=i.length>150?i.substr(i.length-149):i;let o=n[i];typeof o=="number"?e[i]=o:typeof o=="boolean"?e[i]=o?1:0:typeof o=="string"?(o.length>8192&&console.warn(`Telemetry property: ${i} has been trimmed to 8192, the original length is ${o.length}`),t[i]=o.substring(0,8191)):typeof o<"u"&&o!==null&&(t[i]=String(o))}return{properties:t,measurements:e}}function tI(r,t,e=0,n){if(!r||typeof r!="object"&&typeof r!="function")return;let i=r;for(let o of Object.getOwnPropertyNames(i)){let s=i[o],a=n?n+o:o;Array.isArray(s)?t[a]=uf(s):s instanceof Date?t[a]=s.toISOString():Oe(s)?e<2?tI(s,t,e+1,a+"."):t[a]=uf(s):t[a]=s}}function nI(r,t){let e=r.msftInternalDomains||[],n=t.getValue("telemetry.internalTesting");return YS(e)||n}function iI(r){return[r.appRoot,r.extensionsPath,r.userHome.fsPath,r.tmpDir.fsPath,r.userDataPath]}function X0(r,t){if(!r||!r.includes("/")&&!r.includes("\\"))return r;let e=r,n=[];for(let l of t)for(;;){let c=l.exec(r);if(!c)break;n.push([c.index,l.lastIndex])}let i=/(?:^|[\\\/])((node_modules|node_modules\.asar)[\\\/].*)$/,o=/^(.*?)((?:\.vscode(?:-[a-z]+)*|resources[\\\/]app)[\\\/]extensions[\\\/].*)$/i,s=/(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w\-\._@]+(\\\\|\\|\/))+[\w\-\._@]*/g,a=0;for(e="";;){let l=s.exec(r);if(!l)break;if(!n.some(([u,d])=>l.index<d&&u<s.lastIndex)){let u=o.exec(l[0]);if(u)e+=r.substring(a,l.index)+"<REDACTED: user-file-path>/"+u[2];else{let d=i.exec(l[0]);d?e+=r.substring(a,l.index)+"<REDACTED: user-file-path>/"+d[1]:e+=r.substring(a,l.index)+"<REDACTED: user-file-path>"}a=s.lastIndex}}return a<r.length&&(e+=r.substr(a)),e}function Z0(r){if(!r)return r;let t=[{label:"URL",regex:/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s]*/},{label:"Google API Key",regex:/AIza[A-Za-z0-9_\\\-]{35}/},{label:"JWT",regex:/eyJ[0eXAiOiJKV1Qi|hbGci|a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+/},{label:"Slack Token",regex:/xox[pbar]\-[A-Za-z0-9]/},{label:"GitHub Token",regex:/(gh[psuro]_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})/},{label:"Generic Secret",regex:/(key|token|sig|secret|signature|password|passwd|pwd|android:value)[^a-zA-Z0-9]/i},{label:"CLI Credentials",regex:/((login|psexec|(certutil|psexec)\.exe).{1,50}(\s-u(ser(name)?)?\s+.{3,100})?\s-(admin|user|vm|root)?p(ass(word)?)?\s+["']?[^$\-\/\s]|(^|[\s\r\n\\])net(\.exe)?.{1,5}(user\s+|share\s+\/user:| user -? secrets ? set) \s + [^ $\s \/])/},{label:"Microsoft Entra ID",regex:/eyJ(?:0eXAiOiJKV1Qi|hbGci|[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.)/},{label:"Email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/}];for(let e of t)if(e.regex.test(r))return`<REDACTED: ${e.label}>`;return r}function rI(r,t){return r?ta(r,e=>{if(e instanceof qa||Object.hasOwnProperty.call(e,"isTrustedTelemetryValue"))return e.value;if(typeof e=="string"){let n=e.replaceAll("%20"," ");n=X0(n,t);for(let i of t)n=n.replace(i,"");return n=Z0(n),n}}):{}}var oI="https://mobile.events.data.microsoft.com/OneCollector/1.0",eR="https://mobile.events.data.microsoft.com/ping";async function tR(r,t,e){let n=It?await Bg("@microsoft/1ds-core-js","bundle/ms.core.min.js"):await import("@microsoft/1ds-core-js"),i=It?await Bg("@microsoft/1ds-post-js","bundle/ms.post.min.js"):await import("@microsoft/1ds-post-js"),o=new n.AppInsightsCore,s=new i.PostChannel,a={instrumentationKey:r,endpointUrl:oI,loggingLevelTelemetry:0,loggingLevelConsole:0,disableCookiesUsage:!0,disableDbgExt:!0,disableInstrumentationKeyValidation:!0,channels:[[s]]};if(e){a.extensionConfig={};let l={alwaysUseXhrOverride:!0,ignoreMc1Ms0CookieProcessing:!0,httpXHROverride:e};a.extensionConfig[s.identifier]=l}return o.initialize(a,[]),o.addTelemetryInitializer(l=>{l.ext=l.ext??{},l.ext.web=l.ext.web??{},l.ext.web.consentDetails='{"GPC_DataSharingOptIn":false}',t&&(l.ext.utc=l.ext.utc??{},l.ext.utc.flags=8462029)}),o}var Ad=class{constructor(t,e,n,i,o){this._isInternalTelemetry=t;this._eventPrefix=e;this._defaultData=n;this._xhrOverride=o;this.endPointUrl=oI;this.endPointHealthUrl=eR;this._defaultData||(this._defaultData={}),typeof i=="function"?this._aiCoreOrKey=i():this._aiCoreOrKey=i,this._asyncAiCore=null}_withAIClient(t){if(this._aiCoreOrKey){if(typeof this._aiCoreOrKey!="string"){t(this._aiCoreOrKey);return}this._asyncAiCore||(this._asyncAiCore=tR(this._aiCoreOrKey,this._isInternalTelemetry,this._xhrOverride)),this._asyncAiCore.then(e=>{t(e)},e=>{Ue(e),console.error(e)})}}log(t,e){if(!this._aiCoreOrKey)return;e=ao(e,this._defaultData);let n=kd(e),i=this._eventPrefix+"/"+t;try{this._withAIClient(o=>{o.pluginVersionString=n?.properties.version??"Unknown",o.track({name:i,baseData:{name:i,properties:n?.properties,measurements:n?.measurements}})})}catch{}}flush(){return this._aiCoreOrKey?new Promise(t=>{this._withAIClient(e=>{e.unload(!0,()=>{this._aiCoreOrKey=void 0,t(void 0)})})}):Promise.resolve(void 0)}};async function nR(r,t){let e=await t.request(r,ze.None),n=(await Ei(e.stream)).toString(),i=e.res.statusCode??200;return{headers:e.res.headers,statusCode:i,responseData:n}}async function iR(r){let t=await import("https"),e={method:r.type,headers:r.headers};return new Promise((i,o)=>{let s=t.request(r.url??"",e,a=>{a.on("data",function(l){i({headers:a.headers,statusCode:a.statusCode??200,responseData:l.toString()})}),a.on("error",function(l){o(l)})});s.write(r.data,a=>{a&&o(a)}),s.end()})}async function rR(r,t,e){let n=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data),i={type:"POST",headers:{...t.headers,"Content-Type":"application/json","Content-Length":Buffer.byteLength(t.data).toString()},url:t.urlString,data:n,callSite:JS};try{let o=r?await nR(i,r):await iR(i);e(o.statusCode,o.headers,o.responseData)}catch{e(0,{})}}var Dd=class extends Ad{constructor(t,e,n,i,o){let s={sendPOST:(a,l)=>{rR(t,a,l)}};super(e,n,i,o,s)}};var jo=class extends T{constructor(e,n,i,o,s){super();this.prefix=e;let a=n?"remoteTelemetry":zg,l=i.getLogger(a);if(l)this.logger=this._register(l);else{let u=Pd(s,o)?" (Not Sent)":"";this.logger=this._register(i.createLogger(a,{name:g(2534,null,u),group:XS,hidden:!0}))}}flush(){return Promise.resolve()}log(e,n){this.logger.trace(`${this.prefix}telemetry/${e}`,kd(n))}};jo=w([C(2,Kv),C(3,Ma),C(4,Lt)],jo);var Oz={Extensions:{name:{key:"extensionsConfigurationTitle",value:g(138,null)}},IntegratedTerminal:{name:{key:"terminalIntegratedConfigurationTitle",value:g(141,null)}},InteractiveSession:{name:{key:"interactiveSessionConfigurationTitle",value:g(139,null)}},Telemetry:{name:{key:"telemetryConfigurationTitle",value:g(140,null)}},Update:{name:{key:"updateConfigurationTitle",value:g(142,null)}}};var ui=class{constructor(t,e,n){this._configurationService=e;this._productService=n;this._experimentProperties={};this._pendingEvents=[];this._isExperimentPropertySet=!1;this._disposables=new z;this._cleanupPatterns=[];this._appenders=t.appenders,this._commonProperties=t.commonProperties??Object.create(null),this.sessionId=this._commonProperties.sessionID,this.machineId=this._commonProperties["common.machineId"],this.sqmId=this._commonProperties["common.sqmId"],this.devDeviceId=this._commonProperties["common.devDeviceId"],this.firstSessionDate=this._commonProperties["common.firstSessionDate"],this.msftInternal=this._commonProperties["common.msftInternal"],this._piiPaths=t.piiPaths||[],this._telemetryLevel=3,this._sendErrorTelemetry=!!t.sendErrorTelemetry,this._meteredConnectionService=t.meteredConnectionService,this._cleanupPatterns=[/(vscode-)?file:\/\/.*?\/resources\/app\//gi];for(let i of this._piiPaths)this._cleanupPatterns.push(new RegExp(Bt(i),"gi")),i.indexOf("\\")>=0&&this._cleanupPatterns.push(new RegExp(Bt(i.replace(/\\/g,"/")),"gi"));this._updateTelemetryLevel(),this._disposables.add(this._configurationService.onDidChangeConfiguration(i=>{(i.affectsConfiguration(To)||i.affectsConfiguration(wa)||i.affectsConfiguration(Mc))&&this._updateTelemetryLevel()})),t.waitForExperimentProperties?this._flushTimeout=setTimeout(()=>this._flushPendingEvents(),ui.BUFFER_FLUSH_TIMEOUT):this._isExperimentPropertySet=!0}static{this.IDLE_START_EVENT_NAME="UserIdleStart"}static{this.IDLE_STOP_EVENT_NAME="UserIdleStop"}static{this.BUFFER_FLUSH_TIMEOUT=1e4}static{this.MAX_BUFFER_SIZE=1e3}setExperimentProperty(t,e){this._experimentProperties[t]=new qa(e),this._isExperimentPropertySet||this._flushPendingEvents()}setCommonProperty(t,e){this._commonProperties[t]=e}_flushPendingEvents(){if(!this._isExperimentPropertySet){this._isExperimentPropertySet=!0,this._flushTimeout!==void 0&&(clearTimeout(this._flushTimeout),this._flushTimeout=void 0);for(let t of this._pendingEvents)this._doLog(t.eventName,t.eventLevel,t.data);this._pendingEvents=[]}}_updateTelemetryLevel(){let t=eI(this._configurationService),e=this._productService.enabledTelemetryLevels;if(e){this._sendErrorTelemetry=this.sendErrorTelemetry?e.error:!1;let n=e.usage?3:e.error?2:0;t=Math.min(t,n)}this._telemetryLevel=t}get sendErrorTelemetry(){return this._sendErrorTelemetry}get telemetryLevel(){return this._telemetryLevel}dispose(){this._flushPendingEvents(),this._disposables.dispose()}_log(t,e,n){if(!(this._telemetryLevel<e)&&!this._meteredConnectionService?.isConnectionMetered){if(!this._isExperimentPropertySet){this._pendingEvents.length<ui.MAX_BUFFER_SIZE&&this._pendingEvents.push({eventName:t,eventLevel:e,data:n});return}this._doLog(t,e,n)}}_doLog(t,e,n){n=ao(n,this._experimentProperties),n=rI(n,this._cleanupPatterns),n=ao(n,this._commonProperties),e===2&&(n={...n,isError:!0}),this._appenders.forEach(i=>i.log(t,n??{}))}publicLog(t,e){this._log(t,3,e)}publicLog2(t,e){this.publicLog(t,e)}publicLogError(t,e){this._sendErrorTelemetry&&this._log(t,2,e)}publicLogError2(t,e){this.publicLogError(t,e)}};ui=w([C(1,OS),C(2,Lt)],ui);function oR(){let r=g(2551,null,Ut.nameLong),t=Ut.privacyStatementUrl?g(2537,null,"https://aka.ms/vscode-telemetry",Ut.privacyStatementUrl):g(2538,null,"https://aka.ms/vscode-telemetry"),e=It?"":g(2543,null),n=g(2536,null),i=g(2541,null),o=g(2552,null),s=g(2550,null),a=`
|       | ${n} | ${i} | ${o} |
|:------|:-------------:|:---------------:|:----------:|
| all   |       \u2713       |        \u2713        |     \u2713      |
| error |       \u2713       |        \u2713        |     -      |
| crash |       \u2713       |        -        |     -      |
| off   |       -       |        -        |     -      |
`,l=g(2546,null);return`
${r} ${t} ${e}

&nbsp;

${s}
${a}

&nbsp;

${l}
`}var sR=lt.as(rn.Configuration);sR.registerConfiguration({id:Tb,order:1,type:"object",title:g(2553,null),properties:{[To]:{type:"string",enum:["all","error","crash","off"],enumDescriptions:[g(2545,null),g(2547,null),g(2544,null),g(2548,null)],markdownDescription:oR(),default:"all",restricted:!0,scope:1,tags:["usesOnlineServices","telemetry"],policy:{name:"TelemetryLevel",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.telemetryLevel.policyDescription",value:g(2549,null)},enumDescriptions:[{key:"telemetry.telemetryLevel.default",value:g(2545,null)},{key:"telemetry.telemetryLevel.error",value:g(2547,null)},{key:"telemetry.telemetryLevel.crash",value:g(2544,null)},{key:"telemetry.telemetryLevel.off",value:g(2548,null)}]}}},"telemetry.feedback.enabled":{type:"boolean",default:!0,description:g(2542,null),policy:{name:"EnableFeedback",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.feedback.enabled",value:g(2542,null)}}}},[wa]:{type:"boolean",markdownDescription:Ut.privacyStatementUrl?g(2540,null,Ut.nameLong,Ut.privacyStatementUrl):g(2539,null,Ut.nameLong),default:!0,restricted:!0,markdownDeprecationMessage:g(2535,null,`\`#${To}#\``),scope:1,tags:["usesOnlineServices","telemetry"]}}});var Od=class extends T{constructor(e){super();this._delegate=e;this._telemetryLevel=3;$r(e)&&this._register(e)}get telemetryLevel(){return Math.min(this._delegate.telemetryLevel,this._telemetryLevel)}get sendErrorTelemetry(){return this.telemetryLevel>=2&&this._delegate.sendErrorTelemetry}get sessionId(){return this._delegate.sessionId}get machineId(){return this._delegate.machineId}get sqmId(){return this._delegate.sqmId}get devDeviceId(){return this._delegate.devDeviceId}get firstSessionDate(){return this._delegate.firstSessionDate}get msftInternal(){return this._delegate.msftInternal}publicLog(e,n){this.telemetryLevel<3||this._delegate.publicLog(e,n)}publicLogError(e,n){this.telemetryLevel<2||this._delegate.publicLogError(e,n)}publicLog2(e,n){this.telemetryLevel<3||this._delegate.publicLog2(e,n)}publicLogError2(e,n){this.telemetryLevel<2||this._delegate.publicLogError2(e,n)}setExperimentProperty(e,n){this._delegate.setExperimentProperty(e,n)}setCommonProperty(e,n){this._delegate.setCommonProperty(e,n)}updateTelemetryLevel(e){this._telemetryLevel=Math.min(this._telemetryLevel,e)}};function Ld(r,t){let e=t?.[Ea],n=Pb(e);!cR(r)||n===void 0||r.updateTelemetryLevel(n)}function cR(r){return typeof r.updateTelemetryLevel=="function"}async function sI(r){let{environmentService:t,productService:e,fileService:n,loggerService:i,logService:o,disposables:s}=r;if(r.disableTelemetry||!i||!ZS(e,t))return s.add(new Od(Ed));let a=s.add(new Rd(ee(t.appSettingsHome,"settings.json"),n,new qo,o));await a.initialize();let l=[s.add(new jo("",!1,i,t,e))],c=nI(e,a);if(!Pd(e,t)&&e.aiConfig?.ariaKey){let h=new Dd(void 0,c,"monacoworkbench",null,e.aiConfig.ariaKey);s.add(A(()=>{h.flush()})),l.push(h)}let[u,d,f]=await Promise.all([ad(h=>o.error(h)),RS(h=>o.error(h)),ld(h=>o.error(h))]),m=new ui({appenders:l,sendErrorTelemetry:!0,commonProperties:QS(lR(),aR(),process.arch,e.commit,e.version,u,d,f,c,e.date),piiPaths:iI(t)},a,e);return s.add(new Od(m))}var Md=class{constructor(t){this._telemetryService=t}userMessageSent(t,e,n,i,o){let s=o?.length??0,a=n?.activeClient;this._telemetryService.publicLog2("agentHost.userMessageSent",{provider:t,agentSessionId:H.id(e),source:i,isSubagentSession:Lc(e),turnCount:n?.turns.length??0,...a?{activeClientId:a.clientId,activeClientToolCount:a.tools.length,activeClientCustomizationCount:a.customizations?.length??0}:{},attachmentCount:s})}};var Go=class extends T{constructor(e,n,i,o,s,a,l){super();this._stateManager=e;this._options=n;this._logService=o;this._changesets=s;this._telemetryService=a;this._checkpointService=l;this._toolCallAgents=new Map;this._lastAgentInfos=[];this._subagentSessions=new Map;this._pendingSubagentSignals=new Map;this._telemetryReporter=new Md(this._telemetryService),this._permissionManager=this._register(i.createInstance(Fo,this._stateManager)),this._register(_n(c=>{let u=this._options.agents.read(c);this._publishAgentInfos(u,c)})),this._register(this._stateManager.onDidEmitEnvelope(c=>{if(!c.origin&&c.action.type==="session/toolCallComplete"){let u=c.action;this._options.getAgent(c.channel)?.onClientToolCallComplete(y.parse(c.channel),u.toolCallId,u.result)}}))}_publishAgentInfos(e,n){let i=e.map(o=>{let s=o.getDescriptor(),a=o.getProtectedResources(),l=n?o.models.read(n):o.models.get(),c=o.getCustomizations?.();return{provider:s.provider,displayName:s.displayName,description:s.description,models:l.map(u=>({id:u.id,provider:u.provider,name:u.name,maxContextWindow:u.maxContextWindow,supportsVision:u.supportsVision,policyState:u.policyState,configSchema:u.configSchema,_meta:u._meta})),customizations:c?.length?[...c]:void 0,protectedResources:a.length>0?a:void 0}});Me(this._lastAgentInfos,i)||(this._lastAgentInfos=i,this._stateManager.dispatchServerAction(Ne,{type:"root/agentsChanged",agents:i}))}async _publishSessionCustomizations(e,n){if(!e.getSessionCustomizations)return;let i=await e.getSessionCustomizations(y.parse(n));this._stateManager.dispatchServerAction(n,{type:"session/customizationsChanged",customizations:[...i]})}_publishSessionCustomizationsSoon(e,n){this._publishSessionCustomizations(e,n).catch(i=>{this._logService.error("[AgentSideEffects] getSessionCustomizations failed",i)})}_publishSessionCustomizationsForAgent(e){for(let n of this._stateManager.getSessionUris())this._options.getAgent(n)===e&&this._publishSessionCustomizationsSoon(e,n)}_publishAllSessionCustomizations(){for(let e of this._stateManager.getSessionUris()){let n=this._options.getAgent(e);n&&this._publishSessionCustomizationsSoon(n,e)}}initialize(){return this._permissionManager.initialize()}registerProgressListener(e){let n=new z;return n.add(e.onDidSessionProgress(i=>{this._handleAgentSignal(e,i)})),e.onDidCustomizationsChange&&n.add(e.onDidCustomizationsChange(()=>{this._publishAgentInfos(this._options.agents.get()),this._publishSessionCustomizationsForAgent(e)})),n}_handleAgentSignal(e,n){let i=n.session.toString();if(n.kind==="action"&&n.action.type==="session/toolCallStart"&&!n.parentToolCallId&&this._toolCallAgents.set(`${i}:${n.action.toolCallId}`,e.id),n.kind==="subagent_started"){this._handleSubagentStarted(i,n.toolCallId,n.agentName,n.agentDisplayName,n.agentDescription),this._drainPendingSubagentSignals(i,n.toolCallId);return}if(n.kind==="subagent_completed"){this.completeSubagentSession(i,n.toolCallId);return}if(n.kind==="steering_consumed"){this._stateManager.dispatchServerAction(i,{type:"session/pendingMessageRemoved",kind:"steering",id:n.id});return}let o=n.kind==="action"||n.kind==="pending_confirmation"?n.parentToolCallId:void 0;if(o){let a=`${i}:${o}`,l=this._subagentSessions.get(a);if(l){n.kind==="action"&&n.action.type==="session/toolCallStart"&&this._toolCallAgents.set(`${l}:${n.action.toolCallId}`,e.id);let u=this._stateManager.getActiveTurnId(l);u&&this._dispatchActionForSession(n,l,u,e);return}this._logService.trace(`[AgentSideEffects] Buffering ${this._describeSignal(n)} for pending subagent ${a}`);let c=this._pendingSubagentSignals.get(a);c||(c=[],this._pendingSubagentSignals.set(a,c)),c.push({signal:n,agent:e});return}if(n.kind==="pending_confirmation"){let a=this._findSubagentSessionForToolCall(i,n.state.toolCallId);if(a){let l=this._stateManager.getActiveTurnId(a);l&&this._handleToolReady(n,a,l,e);return}}let s=this._stateManager.getActiveTurnId(i);if(s){this._dispatchActionForSession(n,i,s,e);return}n.kind==="action"&&(this._stateManager.dispatchServerAction(i,n.action),n.action.type==="session/turnComplete"&&this._runTurnCompleteSideEffects(i,void 0))}_dispatchActionForSession(e,n,i,o){if(e.kind==="pending_confirmation"){o&&this._handleToolReady(e,n,i,o);return}if(e.kind!=="action")return;let s=e.action;if(Le(s,{turnId:!0})&&s.turnId!==i&&(s={...s,turnId:i}),s.type==="session/toolCallComplete"){let a=`${n}:${s.toolCallId}`;if(this._subagentSessions.get(a)){let c=this._stateManager.getSessionState(n),d=this._getRunningToolCallContent(c,i,s.toolCallId).find(f=>Le(f,{type:!0})&&f.type==="subagent");if(d){let f=[...s.result.content??[],d];s={...s,result:{...s.result,content:f}}}}}this._stateManager.dispatchServerAction(n,s),s.type==="session/toolCallComplete"&&(this._pendingSubagentSignals.delete(`${n}:${s.toolCallId}`),vb(s.result).length>0&&this._changesets.onToolCallEditsApplied(n,i)),s.type==="session/turnComplete"&&this._runTurnCompleteSideEffects(n,i)}_runTurnCompleteSideEffects(e,n){n!==void 0?this._checkpointService.captureTurnCheckpoint(y.parse(e),n).then(()=>{this._changesets.onTurnComplete(e,n)},i=>{this._logService.warn(`[AgentSideEffects] Turn checkpoint capture failed for ${e}/${n}: ${i instanceof Error?i.message:String(i)}`),this._changesets.onTurnComplete(e,n)}):this._changesets.onTurnComplete(e,n),this._tryConsumeNextQueuedMessage(e),this._options.onTurnComplete(e)}_describeSignal(e){return e.kind==="action"?`action(${e.action.type})`:e.kind}_drainPendingSubagentSignals(e,n){let i=`${e}:${n}`,o=this._pendingSubagentSignals.get(i);if(o){this._pendingSubagentSignals.delete(i),this._logService.trace(`[AgentSideEffects] Draining ${o.length} buffered signal(s) for subagent ${i}`);for(let{signal:s,agent:a}of o)this._handleAgentSignal(a,s)}}_handleSubagentStarted(e,n,i,o,s){let a=Co(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 u=q();this._stateManager.dispatchServerAction(a,{type:"session/turnStarted",turnId:u,message:{text:"",origin:{kind:"user"}}}),this._subagentSessions.set(l,a);let d=this._stateManager.getActiveTurnId(e);if(d){let f=this._stateManager.getSessionState(e),h=[...this._getRunningToolCallContent(f,d,n),{type:"subagent",resource:a,title:o,agentName:i,description:s}];this._stateManager.dispatchServerAction(e,{type:"session/toolCallContentChanged",turnId:d,toolCallId:n,content:h})}}_getRunningToolCallContent(e,n,i){if(!e?.activeTurn||e.activeTurn.id!==n)return[];for(let o of e.activeTurn.responseParts)if(o.kind==="toolCall"&&o.toolCall.toolCallId===i&&o.toolCall.status==="running")return o.toolCall.content?[...o.toolCall.content]:[];return[]}cancelSubagentSessions(e){for(let[n,i]of this._subagentSessions)if(n.startsWith(`${e}:`)){let o=this._stateManager.getActiveTurnId(i);o&&this._stateManager.dispatchServerAction(i,{type:"session/turnCancelled",turnId:o}),this._subagentSessions.delete(n)}for(let n of[...this._pendingSubagentSignals.keys()])n.startsWith(`${e}:`)&&this._pendingSubagentSignals.delete(n)}completeSubagentSession(e,n){let i=`${e}:${n}`;this._pendingSubagentSignals.delete(i);let o=this._subagentSessions.get(i);if(!o)return;let s=this._stateManager.getActiveTurnId(o);s&&this._stateManager.dispatchServerAction(o,{type:"session/turnComplete",turnId:s}),this._subagentSessions.delete(i)}removeSubagentSessions(e){let n=[];for(let[o,s]of this._subagentSessions)o.startsWith(`${e}:`)&&(this._stateManager.disposeSessionChangesets(s),this._stateManager.removeSession(s),n.push(o));for(let o of n)this._subagentSessions.delete(o);let i=`${e}/subagent/`;for(let o of this._stateManager.getSessionUrisWithPrefix(i))this._stateManager.disposeSessionChangesets(o),this._stateManager.removeSession(o);for(let o of[...this._pendingSubagentSignals.keys()])o.startsWith(`${e}:`)&&this._pendingSubagentSignals.delete(o)}_findSubagentSessionForToolCall(e,n){let i=`${e}:`;for(let[o,s]of this._subagentSessions)if(o.startsWith(i)&&this._toolCallAgents.has(`${s}:${n}`))return s}_handleToolReady(e,n,i,o){let s={toolCallId:e.state.toolCallId,session:e.session,permissionKind:e.permissionKind,permissionPath:e.permissionPath,toolInput:e.state.toolInput},a=this._permissionManager.getAutoApproval(s,n),l=e;a!==void 0?(this._toolCallAgents.delete(`${n}:${e.state.toolCallId}`),o.respondToPermissionRequest(e.state.toolCallId,!0),l={...e,state:{...e.state,confirmationTitle:void 0}}):l.state.confirmationTitle&&this._toolCallAgents.set(`${n}:${e.state.toolCallId}`,o.id),this._stateManager.dispatchServerAction(n,this._permissionManager.createToolReadyAction(l,n,i))}handleAction(e,n){switch(n.type){case"session/turnStarted":{let i=this._stateManager.getSessionState(e),o=n.message.text.trim().replace(/\s+/g," ").slice(0,200);i&&i.turns.length===0&&!i.summary.title&&o.length>0&&this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:o});let s=this._options.getAgent(e);if(!s){this._stateManager.dispatchServerAction(e,{type:"session/error",turnId:n.turnId,error:{errorType:"noAgent",message:"No agent found for session"}});return}let a=n.message.attachments;this._telemetryReporter.userMessageSent(s.id,e,i,"direct",a),s.sendMessage(y.parse(e),n.message.text,a,n.turnId).catch(l=>{let c=l?.code;this._logService.error(`[AgentSideEffects] sendMessage failed for session=${e}: code=${c}, message=${l instanceof Error?l.message:String(l)}, type=${l?.constructor?.name}`,l),this._stateManager.dispatchServerAction(e,{type:"session/error",turnId:n.turnId,error:{errorType:"sendFailed",message:String(l)}})});break}case"session/toolCallConfirmed":{let i=`${e}:${n.toolCallId}`,o=this._toolCallAgents.get(i);o?(this._toolCallAgents.delete(i),this._options.agents.get().find(a=>a.id===o)?.respondToPermissionRequest(n.toolCallId,n.approved)):this._logService.warn(`[AgentSideEffects] No agent for tool call confirmation: ${n.toolCallId}`),n.approved&&this._permissionManager.handleToolCallConfirmed(e,n.toolCallId,n.selectedOptionId);break}case"session/inputCompleted":{this._options.getAgent(e)?.respondToUserInputRequest(n.requestId,n.response,n.answers);break}case"session/turnCancelled":{this.cancelSubagentSessions(e),this._options.getAgent(e)?.abortSession(y.parse(e)).catch(o=>{this._logService.error("[AgentSideEffects] abortSession failed",o)});break}case"session/modelChanged":{this._options.getAgent(e)?.changeModel?.(y.parse(e),n.model).catch(o=>{this._logService.error("[AgentSideEffects] changeModel failed",o)});break}case"session/agentChanged":{this._options.getAgent(e)?.changeAgent?.(y.parse(e),n.agent).catch(o=>{this._logService.error("[AgentSideEffects] changeAgent failed",o)});break}case"session/titleChanged":{this._persistSessionFlag(e,"customTitle",n.title);break}case"session/pendingMessageSet":case"session/pendingMessageRemoved":case"session/queuedMessagesReordered":{this._syncPendingMessages(e);break}case"session/truncated":{this._options.getAgent(e)?.truncateSession?.(y.parse(e),n.turnId).catch(o=>{this._logService.error("[AgentSideEffects] truncateSession failed",o)}),this._changesets.onSessionTruncated(e);break}case"session/activeClientChanged":{let i=this._options.getAgent(e);if(!i)break;let o=n.activeClient?.clientId??"";i.setClientTools(y.parse(e),o,n.activeClient?.tools??[]);let s=n.activeClient?.customizations??[];i.setClientCustomizations(y.parse(e),o,s).catch(a=>{this._logService.error("[AgentSideEffects] setClientCustomizations failed",a)});break}case"root/configChanged":{Ld(this._telemetryService,n.config),this._publishAgentInfos(this._options.agents.get()),this._publishAllSessionCustomizations();break}case"session/activeClientToolsChanged":{let i=this._options.getAgent(e);if(i){let s=this._stateManager.getSessionState(e)?.activeClient?.clientId;s&&i.setClientTools(y.parse(e),s,n.tools)}break}case"session/customizationToggled":{this._options.getAgent(e)?.setCustomizationEnabled?.(n.id,n.enabled);break}case"session/isReadChanged":{this._persistSessionFlag(e,"isRead",n.isRead?"true":"");break}case"session/isArchivedChanged":{this._persistSessionFlag(e,"isArchived",n.isArchived?"true":""),this._options.getAgent(e)?.onArchivedChanged?.(y.parse(e),n.isArchived).catch(o=>{this._logService.warn(`[AgentSideEffects] onArchivedChanged failed for ${e}`,o)});break}case"session/configChanged":{let o=this._stateManager.getSessionState(e)?.config?.values;o&&this._persistSessionFlag(e,"configValues",JSON.stringify(o));break}case"session/toolCallComplete":{this._options.getAgent(e)?.onClientToolCallComplete(y.parse(e),n.toolCallId,n.result);break}}}_persistSessionFlag(e,n,i){let o=this._options.sessionDataService.openDatabase(y.parse(e));o.object.setMetadata(n,i).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?.(y.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 i=n.queuedMessages[0],o=q();this._stateManager.dispatchServerAction(e,{type:"session/turnStarted",turnId:o,message:i.message,queuedMessageId:i.id});let s=this._options.getAgent(e);if(!s){this._stateManager.dispatchServerAction(e,{type:"session/error",turnId:o,error:{errorType:"noAgent",message:"No agent found for session"}});return}let a=i.message.attachments;this._telemetryReporter.userMessageSent(s.id,e,this._stateManager.getSessionState(e),"queued",a),s.sendMessage(y.parse(e),i.message.text,a,o).catch(l=>{this._logService.error("[AgentSideEffects] sendMessage failed (queued)",l),this._stateManager.dispatchServerAction(e,{type:"session/error",turnId:o,error:{errorType:"sendFailed",message:String(l)}})})}dispose(){this._toolCallAgents.clear(),super.dispose()}};Go=w([C(2,qe),C(3,L),C(4,No),C(5,Li),C(6,En)],Go);var Jo=V("agentHostFileMonitorService"),qg=Object.freeze(["**/.git/objects/**","**/.git/subtree-cache/**","**/.git/**/*.lock","**/.hg/store/**","**/*.watchman-cookie-*"]);function dR(r){return[...r].sort()}function uR(r){let t=Object.create(null);for(let e of r)t[e]=!0;return $a(t)}var An=class extends T{constructor(e,n){super();this._fileService=e;this._logService=n;this._entries=this._register(new We);this._register(this._fileService.onDidFilesChange(i=>this._onDidFilesChange(i))),this._register(this._fileService.onDidWatchError(i=>{this._logService.warn("[AgentHostFileMonitorService] File watcher error",i)}))}static{this._DEFAULT_DEBOUNCE_MS=750}acquire(e,n,i={}){let o=this._canonicalizeFolder(e),s=dR(i.excludes??qg),a=i.debounceMs??An._DEFAULT_DEBOUNCE_MS,l=this._key(o,s,a),c=this._entries.get(l);if(!c){try{c=this._createEntry(l,o,s,a)}catch(u){this._logService.warn(`[AgentHostFileMonitorService] Failed to watch ${o.toString()}`,u);return}this._entries.set(l,c)}return c.callbacks.add(n),A(()=>{let u=this._entries.get(l);u&&(u.callbacks.delete(n),u.callbacks.size===0&&this._entries.deleteAndDispose(l))})}_createEntry(e,n,i,o){let s=new z;try{let a=s.add(new Rt),l=new Set,c=uR(i);return s.add(this._fileService.watch(n,{recursive:!0,excludes:[...i]})),{folder:n,callbacks:l,debounce:a,debounceMs:o,excludeMatcher:c,dispose:()=>s.dispose()}}catch(a){throw s.dispose(),a}}_onDidFilesChange(e){for(let n of this._entries.keys())this._onDidFilesChangeEntry(n,e)}_onDidFilesChangeEntry(e,n){let i=this._entries.get(e);!i||i.callbacks.size===0||!n.affects(i.folder)||!this._hasRelevantRawChange(i,n)||(i.debounce.value=Ri(()=>{i.debounce.clear();for(let o of[...i.callbacks])try{o()}catch(s){this._logService.warn("[AgentHostFileMonitorService] Folder change callback failed",s)}},i.debounceMs))}_hasRelevantRawChange(e,n){return this._hasRelevantRawResources(e,n.rawAdded)||this._hasRelevantRawResources(e,n.rawUpdated)||this._hasRelevantRawResources(e,n.rawDeleted)}_hasRelevantRawResources(e,n){for(let i of n)if(Ve.isEqualOrParent(i,e.folder)&&!this._isExcluded(e,i))return!0;return!1}_isExcluded(e,n){let i=Ve.basename(n),o=Ve.relativePath(e.folder,n);return o!==void 0&&this._matchesExclude(e,o,i)?!0:this._matchesExclude(e,n.path,i)}_matchesExclude(e,n,i){return typeof e.excludeMatcher(n,i)=="string"}_canonicalizeFolder(e){return Ve.removeTrailingPathSeparator(Ve.normalizePath(e))}_key(e,n,i){return`${Ve.getComparisonKey(e)}\0${i}\0${n.join(`
`)}`}};An=w([C(0,Se),C(1,L)],An);var Kg=class extends Wr{constructor(e,n){super();this._create=e;this._destroy=n}createReferencedObject(e){return this._create(e),e}destroyReferencedObject(e){this._destroy(e)}},Nd=class extends T{constructor(e,n,i,o,s,a){super();this._stateManager=e;this._changesets=n;this._configurationService=i;this._fileMonitorService=o;this._gitService=s;this._logService=a;this._watchInterestReferences=this._register(new We);this._watchInterestCollection=new Kg(e=>this._attachWatcherIfPossible(e),e=>this._destroyWatchInterest(e));this._pendingWatchInterest=new Set;this._sessionWorkingDirectory=new Map;this._sessionRoot=new Map;this._rootSessions=new Map;this._rootWatchAcquisitions=this._register(new We);this._rootUris=new Map;this._activeSessionRoots=new Map;this._rootActiveSessions=new Map;this._unresolvedActiveSessions=new Set;this._watchAttachmentSequencer=new Ze;this._activeTurnSequencer=new Ze}trackSessionChanges(e,n){this._watchInterestReferences.has(e)||this._watchInterestReferences.set(e,this._watchInterestCollection.acquire(n))}untrackSessionChanges(e){this._watchInterestReferences.deleteAndDispose(e)}onSessionRestored(e){this._retryWatchAttachment(e)}onSessionMaterialized(e){this._retryWatchAttachment(e)}onSessionDisposed(e){this.untrackSessionChanges(Kt(e)),this.untrackSessionChanges(Ot(e)),this.untrackSessionChanges(e),this._removeActiveSession(e),this._destroyWatchInterest(e)}onSessionTurnActiveChanged(e,n){this._activeTurnSequencer.queue(e,async()=>{n?await this._markSessionActive(e):this._markSessionInactive(e)})}_destroyWatchInterest(e){this._pendingWatchInterest.delete(e),this._releaseSessionRoot(e)}_retryWatchAttachment(e){(this._shouldAttachSession(e)||this._pendingWatchInterest.has(e))&&this._attachWatcherIfPossible(e)}_hasWatchInterest(e){return this._watchInterestReferences.has(e)||this._watchInterestReferences.has(Kt(e))||this._watchInterestReferences.has(Ot(e))}_attachWatcherIfPossible(e){this._watchAttachmentSequencer.queue(e,async()=>{if(!this._shouldAttachSession(e))return;let n=this._configurationService.getEffectiveWorkingDirectory(e);if(!n){this._pendingWatchInterest.add(e),this._releaseSessionRoot(e);return}let i;try{i=y.parse(n)}catch(s){this._logService.warn(`[ChangesetFileMonitorCoordinator] Failed to parse working directory URI for ${e}: ${n}`,s),this._pendingWatchInterest.add(e),this._releaseSessionRoot(e);return}if(this._sessionRoot.has(e)&&this._sessionWorkingDirectory.get(e)===n){this._pendingWatchInterest.delete(e);return}let o=await this._gitService.getRepositoryRoot(i);if(this._shouldAttachSession(e)){if(!o){this._pendingWatchInterest.delete(e),this._releaseSessionRoot(e);return}this._pendingWatchInterest.delete(e),this._attachSessionToRoot(e,o,n)}})}_attachSessionToRoot(e,n,i){let o=n.toString();if(this._sessionRoot.get(e)===o){this._sessionWorkingDirectory.set(e,i),this._ensureRootWatcher(o,n);return}this._releaseSessionRoot(e);let s=this._rootSessions.get(o);s||(s=new Set,this._rootSessions.set(o,s),this._rootUris.set(o,n)),s.add(e),this._sessionRoot.set(e,o),this._sessionWorkingDirectory.set(e,i),this._ensureRootWatcher(o,n)}_releaseSessionRoot(e){let n=this._sessionRoot.get(e);if(!n){this._sessionWorkingDirectory.delete(e);return}this._sessionRoot.delete(e),this._sessionWorkingDirectory.delete(e);let i=this._rootSessions.get(n);i&&(i.delete(e),i.size===0&&(this._rootSessions.delete(n),this._rootUris.delete(n),this._rootWatchAcquisitions.deleteAndDispose(n)))}_onRootChanged(e){if(this._isRootActive(e))return;let n=this._rootSessions.get(e);if(!n||n.size===0)return;let i=[...n].filter(o=>this._hasWatchInterest(o)&&this._sessionRoot.get(o)===e&&!this._activeSessionRoots.has(o)&&!this._unresolvedActiveSessions.has(o)&&!!this._stateManager.getSessionState(o));if(i.length!==0)for(let o of i)this._changesets.refreshUncommittedChangeset(o),this._changesets.refreshSessionChangeset(o)}_shouldAttachSession(e){return this._hasWatchInterest(e)&&!this._activeSessionRoots.has(e)&&!this._unresolvedActiveSessions.has(e)}_isRootActive(e){return(this._rootActiveSessions.get(e)?.size??0)>0}_ensureRootWatcher(e,n){if(this._isRootActive(e)||this._rootWatchAcquisitions.has(e))return;let i=this._rootSessions.get(e);if(!i||i.size===0)return;let o=this._fileMonitorService.acquire(n,()=>this._onRootChanged(e),{excludes:qg,debounceMs:750});if(!o){for(let s of i)this._pendingWatchInterest.add(s);return}this._rootWatchAcquisitions.set(e,o)}_suspendRootWatcher(e){this._rootWatchAcquisitions.deleteAndDispose(e)}async _markSessionActive(e){this._removeActiveSession(e),this._pendingWatchInterest.delete(e);let n=await this._resolveActivityRepositoryRoot(e);if(!n){this._unresolvedActiveSessions.add(e),this._releaseSessionRoot(e);return}let i=n.toString(),o=this._rootActiveSessions.get(i);o||(o=new Set,this._rootActiveSessions.set(i,o)),o.add(e),this._activeSessionRoots.set(e,i),this._rootUris.set(i,n),this._suspendRootWatcher(i),this._sessionRoot.get(e)!==i&&this._releaseSessionRoot(e)}_markSessionInactive(e){let n=this._removeActiveSession(e);if(n){let i=this._rootUris.get(n);i&&this._ensureRootWatcher(n,i)}(this._hasWatchInterest(e)||this._pendingWatchInterest.has(e))&&this._attachWatcherIfPossible(e)}_removeActiveSession(e){this._unresolvedActiveSessions.delete(e);let n=this._activeSessionRoots.get(e);if(!n)return;this._activeSessionRoots.delete(e);let i=this._rootActiveSessions.get(n);return i&&(i.delete(e),i.size===0&&this._rootActiveSessions.delete(n)),n}async _resolveActivityRepositoryRoot(e){let n=this._getActivityWorkingDirectory(e);if(!n)return;let i;try{i=y.parse(n)}catch(o){this._logService.warn(`[ChangesetFileMonitorCoordinator] Failed to parse active working directory URI for ${e}: ${n}`,o);return}return this._gitService.getRepositoryRoot(i)}_getActivityWorkingDirectory(e){let n=this._configurationService.getEffectiveWorkingDirectory(e);if(n)return n;let i=Ge(e);if(i)return this._configurationService.getEffectiveWorkingDirectory(i.parentSession.toString())}};var jg={[Ua]:!0,[Fa]:!0,[Wa]:!0},Qo=class extends T{constructor(e,n,i,o,s,a){super();this._stateManager=e;this._changesets=n;this._configurationService=i;this._pendingUncommittedRefreshes=new Set;this._pendingSessionRefreshes=new Set;this._subscribedTurns=new Map;this._changesetFileMonitor=this._register(new Nd(this._stateManager,this._changesets,this._configurationService,o,s,a)),this._changesets.setTurnSubscriberProbe((l,c)=>this.hasTurnSubscribers(l,c))}hasTurnSubscribers(e,n){return this._subscribedTurns.get(e)?.has(n)??!1}onSessionCreated(e){this._changesets.registerStaticChangesets(e)}onSessionRestored(e,n){this._changesets.registerStaticChangesets(e),this._changesets.restorePersistedStaticChangesets(e,{uncommittedRaw:n[Ua],sessionRaw:n[Fa],legacyRaw:n[Wa]}),this._drainPendingRefresh(e),this._changesetFileMonitor.onSessionRestored(e)}onSessionMaterialized(e){this._drainPendingRefresh(e),this._changesetFileMonitor.onSessionMaterialized(e)}onSessionDisposed(e){this._pendingUncommittedRefreshes.delete(e),this._pendingSessionRefreshes.delete(e),this._subscribedTurns.delete(e),this._changesetFileMonitor.onSessionDisposed(e)}onSessionTurnActiveChanged(e,n){this._changesetFileMonitor.onSessionTurnActiveChanged(e,n)}onFirstSubscriber(e){let n=e.toString(),i=Tn(n);if(i?.kind==="uncommitted"){this._triggerUncommittedRefresh(i.sessionUri),this._changesetFileMonitor.trackSessionChanges(n,i.sessionUri);return}if(i?.kind==="session"){this._triggerSessionRefresh(i.sessionUri),this._changesetFileMonitor.trackSessionChanges(n,i.sessionUri);return}if(i?.kind==="turn"&&i.turnId!==void 0){let o=this._subscribedTurns.get(i.sessionUri);o||(o=new Set,this._subscribedTurns.set(i.sessionUri,o)),o.add(i.turnId);return}!i&&this._stateManager.getSessionState(n)&&(this._triggerUncommittedRefresh(n),this._triggerSessionRefresh(n),this._changesetFileMonitor.trackSessionChanges(n,n))}onLastSubscriber(e){let n=e.toString(),i=Tn(n);if(i?.kind==="uncommitted"){this._pendingUncommittedRefreshes.delete(i.sessionUri),this._changesetFileMonitor.untrackSessionChanges(n);return}if(i?.kind==="session"){this._pendingSessionRefreshes.delete(i.sessionUri),this._changesetFileMonitor.untrackSessionChanges(n);return}if(i?.kind==="turn"&&i.turnId!==void 0){let o=this._subscribedTurns.get(i.sessionUri);o&&(o.delete(i.turnId),o.size===0&&this._subscribedTurns.delete(i.sessionUri))}i||this._changesetFileMonitor.untrackSessionChanges(n)}async restoreSessionIfChangesetSubscription(e,n){let i=e.toString(),o=Tn(i);if(o){if(o.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${i}`);this._stateManager.getSessionState(o.sessionUri)||await n(y.parse(o.sessionUri))}}async tryHandleSubscribe(e,n){let i=e.toString(),o=Tn(i);if(!o)return!1;if(o.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${i}`);return await this.restoreSessionIfChangesetSubscription(e,n),o.kind==="turn"&&o.turnId?await this._changesets.computeTurnChangeset(o.sessionUri,o.turnId):o.kind==="compare"&&o.originalTurnId&&o.modifiedTurnId?await this._changesets.computeCompareTurnsChangeset(o.sessionUri,o.originalTurnId,o.modifiedTurnId):this._changesets.registerStaticChangesets(o.sessionUri),!0}getListMetadataKeys(e){if(!(this._readyLiveCatalogueExists(e)||this._stateManager.getSessionState(e)?.summary.changesets))return jg}decorateListEntry(e,n){let i=e.session.toString(),o=this._stateManager.getSessionState(i),s=this._stateManager.getChangesetState(Kt(i)),a=this._stateManager.getChangesetState(Ot(i)),l=s?.status==="ready"||a?.status==="ready";if(!o&&l){let m=pS(i,s,a);return m?{...e,changesets:m}:e}let c=n[Ua],u=n[Fa],d=n[Wa];if(c===void 0&&u===void 0&&d===void 0)return e;let f=this._changesets.parsePersistedStaticChangesets(i,{uncommittedRaw:c,sessionRaw:u,legacyRaw:d});if(!o){let m=fS(i,f.uncommitted,f.session);if(m)return{...e,changesets:m}}return e}_readyLiveCatalogueExists(e){return this._stateManager.getChangesetState(Kt(e))?.status==="ready"?!0:this._stateManager.getChangesetState(Ot(e))?.status==="ready"}_triggerUncommittedRefresh(e){if(!this._configurationService.getEffectiveWorkingDirectory(e)){this._pendingUncommittedRefreshes.add(e);return}this._changesets.refreshUncommittedChangeset(e)}_triggerSessionRefresh(e){if(!this._configurationService.getEffectiveWorkingDirectory(e)){this._pendingSessionRefreshes.add(e);return}this._changesets.refreshSessionChangeset(e)}_drainPendingRefresh(e){this._pendingUncommittedRefreshes.delete(e)&&this._triggerUncommittedRefresh(e),this._pendingSessionRefreshes.delete(e)&&this._triggerSessionRefresh(e)}};Qo=w([C(1,No),C(2,Je),C(3,Jo),C(4,Nt),C(5,L)],Qo);var Ud=V("agentHostCompletions");var Yo=class extends T{constructor(e){super();this._logService=e;this._providers=new Set}get triggerCharacters(){let e=new Set;for(let n of this._providers)if(n.triggerCharacters)for(let i of n.triggerCharacters)e.add(i);return[...e]}registerProvider(e){return this._providers.add(e),A(()=>this._providers.delete(e))}async completions(e,n=ze.None){let i=[...this._providers].filter(a=>a.kinds.has(e.kind));if(i.length===0)return{items:[]};let o=await Promise.allSettled(i.map(a=>a.provideCompletionItems(e,n))),s=[];for(let a=0;a<o.length;a++){let l=o[a];l.status==="fulfilled"?s.push(...l.value):this._logService.error(l.reason,`[AgentHostCompletions] Provider failed for kind=${e.kind}`)}return{items:s}}};Yo=w([C(0,L)],Yo);var pR=60,fR=pR*60,Gg=fR*24,LK=Gg*7,MK=Gg*30,NK=Gg*365;function aI(r){return r.getFullYear()+"-"+String(r.getMonth()+1).padStart(2,"0")+"-"+String(r.getDate()).padStart(2,"0")+"T"+String(r.getHours()).padStart(2,"0")+":"+String(r.getMinutes()).padStart(2,"0")+":"+String(r.getSeconds()).padStart(2,"0")+"."+(r.getMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"}var Fd={DateTimeFormat(r,t){return new Ee(()=>{try{return new Intl.DateTimeFormat(r,t)}catch{return new Intl.DateTimeFormat(void 0,t)}})},Collator(r,t){return new Ee(()=>{try{return new Intl.Collator(r,t)}catch{return new Intl.Collator(void 0,t)}})},Segmenter(r,t){return new Ee(()=>{try{return new Intl.Segmenter(r,t)}catch{return new Intl.Segmenter(void 0,t)}})},Locale(r,t){return new Ee(()=>{try{return new Intl.Locale(r,t)}catch{return new Intl.Locale(Ii,t)}})},NumberFormat(r,t){return new Ee(()=>{try{return new Intl.NumberFormat(r,t)}catch{return new Intl.NumberFormat(void 0,t)}})}};var lI=new Ee(()=>{let r=Fd.Collator(void 0,{numeric:!0,sensitivity:"base"}).value;return{collator:r,collatorIsNumeric:r.resolvedOptions().numeric}}),VK=new Ee(()=>({collator:Fd.Collator(void 0,{numeric:!0}).value})),BK=new Ee(()=>({collator:Fd.Collator(void 0,{numeric:!0,sensitivity:"accent"}).value}));function gR(r,t,e=!1){let n=r||"",i=t||"",o=lI.value.collator.compare(n,i);return lI.value.collatorIsNumeric&&o===0&&n!==i?n<i?-1:1:o}function Wd(r,t,e){let n=r.toLowerCase(),i=t.toLowerCase(),o=mR(r,t,e);if(o)return o;let s=n.endsWith(e),a=i.endsWith(e);if(s!==a)return s?-1:1;let l=gR(n,i);return l!==0?l:n.localeCompare(i)}function mR(r,t,e){let n=r.toLowerCase(),i=t.toLowerCase(),o=n.startsWith(e),s=i.startsWith(e);if(o!==s)return o?-1:1;if(o&&s){if(n.length<i.length)return-1;if(n.length>i.length)return 1}return 0}var zK=new Uint32Array(10);var qK=new Uint8Array([114,82,115,101,69,102,97,113,81,116,84,100,119,87,99,122,120,118,103]),KK=new Uint16Array([107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]),jK=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]),GK=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 dI(...r){return function(t,e){for(let n=0,i=r.length;n<i;n++){let o=r[n](t,e);if(o)return o}return null}}var ij=uI.bind(void 0,!1),Vd=uI.bind(void 0,!0);function uI(r,t,e){if(!e||e.length<t.length)return null;let n;return r?n=_i(e,t):n=e.indexOf(t)===0,n?t.length>0?[{start:0,end:t.length}]:[]:null}function hR(r,t){if(r.length>t.length)return null;let e=t.toLowerCase().indexOf(r.toLowerCase());return e===-1?null:[{start:e,end:e+r.length}]}function yR(r,t){return r.length>t.length?null:Jg(r.toLowerCase(),t.toLowerCase(),0,0)}function Jg(r,t,e,n){if(e===r.length)return[];if(n===t.length)return null;if(r[e]===t[n]){let i=null;return(i=Jg(r,t,e+1,n+1))?fI({start:n,end:n+1},i):null}return Jg(r,t,e,n+1)}function Yg(r){return 97<=r&&r<=122}function Xo(r){return 65<=r&&r<=90}function Xg(r){return 48<=r&&r<=57}function vR(r){return r===32||r===9||r===10||r===13}var bR=new Set;"()[]{}<>`'\"-/;:,.?!".split("").forEach(r=>bR.add(r.charCodeAt(0)));function pI(r){return Yg(r)||Xo(r)||Xg(r)}function fI(r,t){return t.length===0?t=[r]:r.end===t[0].start?t[0].start=r.start:t.unshift(r),t}function gI(r,t){for(let e=t;e<r.length;e++){let n=r.charCodeAt(e);if(Xo(n)||Xg(n)||e>0&&!pI(r.charCodeAt(e-1)))return e}return r.length}function Qg(r,t,e,n){if(e===r.length)return[];if(n===t.length)return null;if(r[e]!==t[n].toLowerCase())return null;{let i=null,o=n+1;for(i=Qg(r,t,e+1,n+1);!i&&(o=gI(t,o))<t.length;)i=Qg(r,t,e+1,o),o++;return i===null?null:fI({start:n,end:n+1},i)}}function SR(r){let t=0,e=0,n=0,i=0,o=0;for(let u=0;u<r.length;u++)o=r.charCodeAt(u),Xo(o)&&t++,Yg(o)&&e++,pI(o)&&n++,Xg(o)&&i++;let s=t/r.length,a=e/r.length,l=n/r.length,c=i/r.length;return{upperPercent:s,lowerPercent:a,alphaPercent:l,numericPercent:c}}function IR(r){let{upperPercent:t,lowerPercent:e}=r;return e===0&&t>.6}function _R(r){let{upperPercent:t,lowerPercent:e,alphaPercent:n,numericPercent:i}=r;return e>.2&&t<.8&&n>.6&&i<.2}function CR(r){let t=0,e=0,n=0,i=0;for(let o=0;o<r.length;o++)n=r.charCodeAt(o),Xo(n)&&t++,Yg(n)&&e++,vR(n)&&i++;return(t===0||e===0)&&i===0?r.length<=30:t<=5}function mI(r,t){if(!t||(t=t.trim(),t.length===0)||!CR(r))return null;t.length>60&&(t=t.substring(0,60));let e=SR(t);if(!_R(e)){if(!IR(e))return null;t=t.toLowerCase()}let n=null,i=0;for(r=r.toLowerCase();i<t.length&&(n=Qg(r,t,0,i))===null;)i=gI(t,i+1);return n}var rj=dI(Vd,mI,hR),oj=dI(Vd,mI,yR),sj=new hn(1e4);var $d=128;function Zg(){let r=[],t=[];for(let e=0;e<=$d;e++)t[e]=0;for(let e=0;e<=$d;e++)r.push(t.slice(0));return r}function hI(r){let t=[];for(let e=0;e<=r;e++)t[e]=0;return t}var aj=hI(2*$d),lj=hI(2*$d),cj=Zg(),dj=Zg(),uj=Zg();var TR;(e=>{e.Default=[-100,0];function t(n){return!n||n.length===2&&n[0]===-100&&n[1]===0}e.isDefault=t})(TR||={});var cI=class{constructor(t,e){this.firstMatchCanBeWeak=t;this.boostFullMatch=e}static{this.default={boostFullMatch:!0,firstMatchCanBeWeak:!1}}};var Hd=0,yI=[Hd,[]];function vI(r,t,e,n){if(!r||!t)return yI;let i=r.length,o=t.length;if(i<o)return yI;let s=r.toLowerCase();return xR(t,e,o,r,s,i,n)}function xR(r,t,e,n,i,o,s){let a=[],l=[];for(let f=0;f<e;f++){let m=f*o,h=m-o,v=f>0,S=r[f],_=t[f];for(let b=0;b<o;b++){let I=b>0,R=m+b,P=R-1,j=h+b-1,E=I?a[P]:0,M=v&&I?a[j]:0,O=v&&I?l[j]:0,G;!M&&v?G=0:G=wR(S,_,n,i,b,O),G&&M+G>=E&&(s||v||i.startsWith(t,b))?(l[R]=O+1,a[R]=M+G):(l[R]=Hd,a[R]=E)}}let c=[],u=e-1,d=o-1;for(;u>=0&&d>=0;){let f=u*o+d;l[f]===Hd||(c.push(d),u--),d--}return[a[e*o-1],c.reverse()]}function wR(r,t,e,n,i,o){let s=0;if(!RR(t,n[i]))return s;if(s+=1,o>0&&(s+=Math.min(o,3)*6+Math.max(0,o-3)*3),r===e[i]&&(s+=1),i===0)s+=8;else{let a=ER(e.charCodeAt(i-1));a?s+=a:Xo(e.charCodeAt(i))&&o===0&&(s+=2)}return s}function RR(r,t){return r===t?!0:r==="/"||r==="\\"?t==="/"||t==="\\":!1}function ER(r){switch(r){case 47:case 92:return 5;case 95:case 45:case 46:case 32:case 39:case 34:case 58:return 4;default:return 0}}var zd=Object.freeze({score:0}),Bd=1<<18,em=1<<17,tm=65536;function PR(r,t,e,n){let i=n.values?n.values:[n];return ht({[n.normalized]:{values:i.map(s=>({value:s.normalized,expectContiguousMatch:s.expectContiguousMatch})),label:r,description:t,allowNonContiguousMatches:e}})}function qd(r,t,e,n,i){if(!r||!t.normalized)return zd;let o=n.getItemLabel(r);if(!o)return zd;let s=n.getItemDescription(r),a=PR(o,s,e,t),l=i[a];if(l)return l;let c=kR(o,s,n.getItemPath(r),t,e);return i[a]=c,c}function kR(r,t,e,n,i){let o=!e||!n.containsPathSeparator;return e&&(ve?n.pathNormalized===e:Jn(n.pathNormalized,e))?{score:Bd,labelMatch:[{start:0,end:r.length}],descriptionMatch:t?[{start:0,end:t.length}]:void 0}:n.values&&n.values.length>1?AR(r,t,e,n.values,o,i):TI(r,t,e,n,o,i)}function AR(r,t,e,n,i,o){let s=0,a=[],l=[];for(let c of n){let{score:u,labelMatch:d,descriptionMatch:f}=TI(r,t,e,c,i,o);if(u===Hd)return zd;s+=u,d&&a.push(...d),f&&l.push(...f)}return{score:s,labelMatch:SI(a),descriptionMatch:SI(l)}}function TI(r,t,e,n,i,o){if(i||!t){let[s,a]=vI(r,n.normalized,n.normalizedLowercase,o&&!n.expectContiguousMatch);if(s){let l=Vd(n.normalized,r),c;if(l){c=em;let u=Math.round(n.normalized.length/r.length*100);c+=u}else c=tm;return{score:c+s,labelMatch:l||bI(a)}}}if(t){let s=t;e&&(s=`${t}${Ce}`);let a=s.length,l=`${s}${r}`,[c,u]=vI(l,n.normalized,n.normalizedLowercase,o&&!n.expectContiguousMatch);if(c){let d=bI(u),f=[],m=[];return d.forEach(h=>{h.start<a&&h.end>a?(f.push({start:0,end:h.end-a}),m.push({start:h.start,end:a})):h.start>=a?f.push({start:h.start-a,end:h.end-a}):m.push(h)}),{score:c,labelMatch:f,descriptionMatch:m}}}return zd}function bI(r){let t=[];if(!r)return t;let e;for(let n of r)e&&e.end===n?e.end+=1:(e={start:n,end:n+1},t.push(e));return t}function SI(r){let t=r.sort((i,o)=>i.start-o.start),e=[],n;for(let i of t)!n||!DR(n,i)?(n=i,e.push(i)):(n.start=Math.min(n.start,i.start),n.end=Math.max(n.end,i.end));return e}function DR(r,t){return!(r.end<t.start||t.end<r.start)}function xI(r,t,e,n,i,o){let s=qd(r,e,n,i,o),a=qd(t,e,n,i,o),l=s.score,c=a.score;if((l===Bd||c===Bd)&&l!==c)return l===Bd?-1:1;if(l>tm||c>tm){if(l!==c)return l>c?-1:1;if(l<em&&c<em){let S=OR(s.labelMatch,a.labelMatch);if(S!==0)return S}let h=i.getItemLabel(r)||"",v=i.getItemLabel(t)||"";if(h.length!==v.length)return h.length-v.length}if(l!==c)return l>c?-1:1;let u=Array.isArray(s.labelMatch)&&s.labelMatch.length>0,d=Array.isArray(a.labelMatch)&&a.labelMatch.length>0;if(u&&!d)return-1;if(d&&!u)return 1;let f=II(r,s,i),m=II(t,a,i);return f&&m&&f!==m?m>f?-1:1:LR(r,t,e,i)}function II(r,t,e){let n=-1,i=-1;if(t.descriptionMatch?.length?n=t.descriptionMatch[0].start:t.labelMatch?.length&&(n=t.labelMatch[0].start),t.labelMatch?.length){if(i=t.labelMatch[t.labelMatch.length-1].end,t.descriptionMatch?.length){let o=e.getItemDescription(r);o&&(i+=o.length)}}else t.descriptionMatch?.length&&(i=t.descriptionMatch[t.descriptionMatch.length-1].end);return i-n}function OR(r,t){if(!r&&!t||!r?.length&&!t?.length)return 0;if(!t?.length)return-1;if(!r?.length)return 1;let e=r[0].start,i=r[r.length-1].end-e,o=t[0].start,a=t[t.length-1].end-o;return i===a?0:a<i?1:-1}function LR(r,t,e,n){let i=n.getItemLabel(r)||"",o=n.getItemLabel(t)||"",s=n.getItemDescription(r),a=n.getItemDescription(t),l=i.length+(s?s.length:0),c=o.length+(a?a.length:0);if(l!==c)return l-c;let u=n.getItemPath(r),d=n.getItemPath(t);return u&&d&&u.length!==d.length?u.length-d.length:i!==o?Wd(i,o,e.normalized):s&&a&&s!==a?Wd(s,a,e.normalized):u&&d&&u!==d?Wd(u,d,e.normalized):0}function _I(r){return r.startsWith('"')&&r.endsWith('"')}var MR=" ";function wI(r){typeof r!="string"&&(r="");let t=r.toLowerCase(),{pathNormalized:e,normalized:n,normalizedLowercase:i}=CI(r),o=e.indexOf(Ce)>=0,s=_I(r),a,l=r.split(MR);if(l.length>1)for(let c of l){let u=_I(c),{pathNormalized:d,normalized:f,normalizedLowercase:m}=CI(c);f&&(a||(a=[]),a.push({original:c,originalLowercase:c.toLowerCase(),pathNormalized:d,normalized:f,normalizedLowercase:m,expectContiguousMatch:u}))}return{original:r,originalLowercase:t,pathNormalized:e,normalized:n,normalizedLowercase:i,values:a,containsPathSeparator:o,expectContiguousMatch:s}}function CI(r){let t;K?t=r.replace(/\//g,Ce):t=r.replace(/\\/g,Ce);let e=t.replace(/[\*\u2026\s"]/g,"").replace(/(?<=.)#$/,"");return{pathNormalized:t,normalized:e,normalizedLowercase:e.toLowerCase()}}var RI=50;function NR(r,t){if(!(t<0||t>r.length))for(let e=t-1;e>=0;e--){let n=r.charCodeAt(e);if(n===32||n===9||n===10||n===13)return;if(r[e]==="@"){if(e>0){let i=r.charCodeAt(e-1);if(!(i===32||i===9||i===10||i===13))return}return{token:r.slice(e+1,t),rangeStart:e,rangeEnd:t}}}}var nm=class{constructor(t){this._workingDirectory=t}getItemLabel(t){return pe(t)}getItemDescription(t){let e=tf(this._workingDirectory,t);if(!e)return;let n=e.lastIndexOf("/");return n>0?e.slice(0,n):void 0}getItemPath(t){return tf(this._workingDirectory,t)??t.fsPath}},Kd=class{constructor(t,e){this._stateManager=t;this._workspaceFiles=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["@"]}async provideCompletionItems(t,e){let n=this._stateManager.getSessionState(t.channel)?.summary.workingDirectory;if(!n)return[];let i=y.parse(n);if(i.scheme!==oe.file)return[];let o=NR(t.text,t.offset);if(!o)return[];let s;try{s=await this._workspaceFiles.getFiles(i,e)}catch(d){if(Xi(d))return[];throw d}if(e.isCancellationRequested||s.length===0)return[];let a=new nm(i),l=wI(o.token),c=Object.create(null),u;if(!l.normalized)u=s.slice(0,RI);else{let d=s.filter(f=>qd(f,l,!0,a,c).score>0);d.sort((f,m)=>xI(f,m,l,!0,a,c)),u=d.slice(0,RI)}return u.map(d=>{let f=pe(d);return{insertText:"@"+f,rangeStart:o.rangeStart,rangeEnd:o.rangeEnd,attachment:{type:"resource",uri:d.toString(),label:f,displayKind:"document"}}})}};function UR(r,t=[],e={}){let i=new jd(r).scan();return new Gd(i,r,t,e).parse()}function Zo(r,t=[],e={}){let n=new jd(r).scan();if(n.length===0||n[0].type!==11)return new Ka(void 0,r);if(!n.slice(1).some(l=>l.type===11))return new Ka(void 0,r);let o=new Gd(n,r,t,e).parse(),s=n[n.length-1],a=s.type===13?r.substring(s.startOffset):"";return new Ka(o,a)}var Ka=class{constructor(t,e){this.header=t;this.body=e}getStringValue(t){if(this.header&&this.header.type==="map"){let e=this.header.properties.find(n=>n.key.value===t);if(e&&e.value.type==="scalar")return e.value.value}}getStringArrayValue(t){if(this.header&&this.header.type==="map"){let e=this.header.properties.find(n=>n.key.value===t);if(e&&e.value.type==="sequence")return e.value.items.filter(n=>n.type==="scalar").map(n=>n.value);if(e&&e.value.type==="scalar"&&e.value.format==="none")return FR(e.value.value,0).map(n=>n.value)}}};function FR(r,t=0){let e=UR(`[${r}]`),n=t-1,i=[];if(e&&e.type==="sequence")for(let o of e.items)o.type==="scalar"&&i.push({...o,startOffset:o.startOffset+n,endOffset:o.endOffset+n});else i.push({type:"scalar",value:r,rawValue:r,startOffset:t,endOffset:r.length+t,format:"none"});return i}function Qe(r,t,e,n){return{type:r,startOffset:t,endOffset:e,rawValue:n?.rawValue??"",value:n?.value??"",format:n?.format??"none",indent:n?.indent??0}}var jd=class{constructor(t){this.input=t;this.pos=0;this.tokens=[];this.flowDepth=0;this.seenBlockColon=!1;this.seenDocumentStart=0}scan(t=1){for(;this.pos<this.input.length&&(this.scanLine(),!(this.seenDocumentStart>t)););return this.tokens.push(Qe(13,this.pos,this.pos)),this.tokens}scanLine(){if(this.seenBlockColon=!1,this.peekChar()===`
`){this.tokens.push(Qe(8,this.pos,this.pos+1)),this.pos++;return}if(this.peekChar()==="\r"){let n=this.pos+(this.input[this.pos+1]===`
`?2:1);this.tokens.push(Qe(8,this.pos,n)),this.pos=n;return}let t=this.pos,e=0;for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]==="	");)e++,this.pos++;if(e>0&&this.tokens.push(Qe(9,t,this.pos,{indent:e})),this.pos>=this.input.length||this.peekChar()===`
`||this.peekChar()==="\r"){if(this.pos<this.input.length){let n=this.pos,i=this.peekChar()==="\r"&&this.input[this.pos+1]===`
`?this.pos+2:this.pos+1;this.tokens.push(Qe(8,n,i)),this.pos=i}return}if(e===0&&this.input.length-this.pos>=3){let n=this.input[this.pos],i=this.input[this.pos+1],o=this.input[this.pos+2],s=this.input[this.pos+3],a=s===void 0||s===" "||s==="	"||s===`
`||s==="\r";if(n==="-"&&i==="-"&&o==="-"&&a){this.tokens.push(Qe(11,this.pos,this.pos+3)),this.pos+=3,this.scanLineContent(),this.scanNewline(),this.seenDocumentStart++;return}if(n==="."&&i==="."&&o==="."&&a){this.tokens.push(Qe(12,this.pos,this.pos+3)),this.pos+=3,this.scanLineContent(),this.scanNewline();return}}if(this.peekChar()==="#"){this.scanComment(),this.scanNewline();return}if(this.peekChar()==="%"){for(;this.pos<this.input.length&&this.input[this.pos]!==`
`&&this.input[this.pos]!=="\r";)this.pos++;this.scanNewline();return}this.scanLineContent(),this.scanNewline()}scanLineContent(){for(;this.pos<this.input.length&&this.peekChar()!==`
`&&this.peekChar()!=="\r"&&(this.skipInlineWhitespace(),!(this.pos>=this.input.length||this.peekChar()===`
`||this.peekChar()==="\r"));){let t=this.peekChar();if(t==="#"){this.scanComment();break}else if(t==="{")this.flowDepth++,this.tokens.push(Qe(4,this.pos,this.pos+1)),this.pos++;else if(t==="}"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Qe(5,this.pos,this.pos+1)),this.pos++;else if(t==="[")this.flowDepth++,this.tokens.push(Qe(6,this.pos,this.pos+1)),this.pos++;else if(t==="]"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Qe(7,this.pos,this.pos+1)),this.pos++;else if(t===","&&this.flowDepth>0)this.tokens.push(Qe(3,this.pos,this.pos+1)),this.pos++;else if(t==="-"&&this.isBlockDash())this.tokens.push(Qe(2,this.pos,this.pos+1)),this.pos++;else if(t===":"&&this.isBlockColon())this.tokens.push(Qe(1,this.pos,this.pos+1)),this.pos++,this.flowDepth===0&&(this.seenBlockColon=!0);else if(t===":"&&this.flowDepth>0&&this.lastTokenIsJsonLike())this.tokens.push(Qe(1,this.pos,this.pos+1)),this.pos++;else if(t==="'"||t==='"')this.scanQuotedScalar(t);else if((t==="|"||t===">")&&this.flowDepth===0&&this.isBlockScalarStart()){this.scanBlockScalar(t);break}else this.scanUnquotedScalar()}}isBlockDash(){let t=this.input[this.pos+1];return t===void 0||t===" "||t==="	"||t===`
`||t==="\r"}isBlockColon(){if(this.seenBlockColon&&this.flowDepth===0)return!1;let t=this.input[this.pos+1];return t===void 0||t===" "||t==="	"||t===`
`||t==="\r"||this.flowDepth>0&&(t===","||t==="}"||t==="]")}lastTokenIsJsonLike(){for(let t=this.tokens.length-1;t>=0;t--){let e=this.tokens[t];if(!(e.type===8||e.type===9||e.type===10))return e.type===0&&e.format!=="none"||e.type===5||e.type===7}return!1}scanQuotedScalar(t){let e=this.pos;this.pos++;let n="",i=0;for(;this.pos<this.input.length;){let s=this.input[this.pos];if(s===t){if(t==="'"&&this.input[this.pos+1]==="'"){n+="'",this.pos+=2,i=0;continue}this.pos++;let a=this.input.substring(e,this.pos);this.tokens.push(Qe(0,e,this.pos,{rawValue:a,value:n,format:t==="'"?"single":"double"}));return}if(t==='"'&&s==="\\"){let a=this.input[this.pos+1];if(a===`
`||a==="\r"){this.pos++,this.consumeNewline(),this.skipInlineWhitespace(),i=0;continue}switch(a){case"n":n+=`
`;break;case"t":n+="	";break;case"\\":n+="\\";break;case'"':n+='"';break;case"/":n+="/";break;case"r":n+="\r";break;case"0":n+="\0";break;case"a":n+="\x07";break;case"b":n+="\b";break;case"e":n+="\x1B";break;case"v":n+="\v";break;case"f":n+="\f";break;case" ":n+=" ";break;case"_":n+="\xA0";break;case"x":{let l=this.input.substring(this.pos+2,this.pos+4),c=parseInt(l,16);l.length===2&&!isNaN(c)?(n+=String.fromCharCode(c),this.pos+=4):(n+="\\x",this.pos+=2),i=0;continue}case"u":{let l=this.input.substring(this.pos+2,this.pos+6),c=parseInt(l,16);l.length===4&&!isNaN(c)?(n+=String.fromCodePoint(c),this.pos+=6):(n+="\\u",this.pos+=2),i=0;continue}case"U":{let l=this.input.substring(this.pos+2,this.pos+10),c=parseInt(l,16);l.length===8&&!isNaN(c)?(n+=String.fromCodePoint(c),this.pos+=10):(n+="\\U",this.pos+=2),i=0;continue}default:n+="\\"+(a??"");break}this.pos+=2,i=0;continue}if(s===`
`||s==="\r"){i>0&&(n=n.substring(0,n.length-i)),i=0,this.consumeNewline();let a=0;for(;this.pos<this.input.length;){this.skipInlineWhitespace();let l=this.input[this.pos];if(l===`
`||l==="\r")a++,this.consumeNewline();else break}a>0?n+=`
`.repeat(a):n+=" ";continue}s===" "||s==="	"?i++:i=0,n+=s,this.pos++}let o=this.input.substring(e,this.pos);this.tokens.push(Qe(0,e,this.pos,{rawValue:o,value:n,format:t==="'"?"single":"double"}))}scanUnquotedScalar(){let t=this.pos,e=this.pos;for(;this.pos<this.input.length;){let i=this.input[this.pos];if(i===`
`||i==="\r"||this.flowDepth>0&&(i===","||i==="}"||i==="]")||this.flowDepth>0&&(i==="{"||i==="[")||i===":"&&this.isBlockColon()||i==="#"&&this.pos>t&&(this.input[this.pos-1]===" "||this.input[this.pos-1]==="	"))break;this.pos++,i!==" "&&i!=="	"&&(e=this.pos)}let n=this.input.substring(t,e);this.tokens.push(Qe(0,t,e,{rawValue:n,value:n,format:"none"}))}isBlockScalarStart(){let t=this.pos+1;for(;t<this.input.length;){let n=this.input[t];if(n>="1"&&n<="9"){t++;continue}if(n==="+"||n==="-"){t++;continue}break}for(;t<this.input.length&&(this.input[t]===" "||this.input[t]==="	");)t++;if(t>=this.input.length)return!0;let e=this.input[t];return e===`
`||e==="\r"||e==="#"}scanBlockScalar(t){let e=this.pos;this.pos++;let n=0,i="clip";for(let f=0;f<2;f++)if(this.pos<this.input.length){let m=this.input[this.pos];m>="1"&&m<="9"&&n===0?(n=parseInt(m,10),this.pos++):m==="-"&&i==="clip"?(i="strip",this.pos++):m==="+"&&i==="clip"&&(i="keep",this.pos++)}for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]==="	");)this.pos++;if(this.pos<this.input.length&&this.input[this.pos]==="#")for(;this.pos<this.input.length&&this.input[this.pos]!==`
`&&this.input[this.pos]!=="\r";)this.pos++;this.consumeNewline();let o=this.getParentBlockIndent(e),s=n>0?o+n:0,a=[],l=0;for(;this.pos<this.input.length;){let f=this.pos,m=0;for(;this.pos<this.input.length&&this.input[this.pos]===" ";)m++,this.pos++;if(this.pos>=this.input.length||this.input[this.pos]===`
`||this.input[this.pos]==="\r"){if(s>0&&m>=s){let S=this.input.substring(f+s,this.pos);a.push(S),S===""?l++:l=0}else a.push(""),l++;this.consumeNewline();continue}if(m===0&&this.input.length-this.pos>=3){let S=this.input[this.pos],_=this.input[this.pos+1],b=this.input[this.pos+2],I=this.input[this.pos+3],R=I===void 0||I===" "||I==="	"||I===`
`||I==="\r";if(S==="-"&&_==="-"&&b==="-"&&R||S==="."&&_==="."&&b==="."&&R){this.pos=f;break}}if(s===0){if(m<=o){this.pos=f;break}s=m}if(m<s){this.pos=f;break}let h=f+s;for(;this.pos<this.input.length&&this.input[this.pos]!==`
`&&this.input[this.pos]!=="\r";)this.pos++;let v=this.input.substring(h,this.pos);a.push(v),l=0,this.consumeNewline()}let c;if(t==="|")c=a.join(`
`);else{c="";let f=!1,m=!1,h=!1;for(let v=0;v<a.length;v++){let S=a[v],_=S.length>0&&(S[0]===" "||S[0]==="	");S===""?(c+=`
`,m=!0):v===0?(c=S,f=_,h=!0):m?((f||_)&&h?c+=`
`+S:c+=S,f=_,m=!1,h=!0):_||f?(c+=`
`+S,f=_,h=!0):(c+=" "+S,f=!1,h=!0)}}if(l>0){let f=c.length;for(;f>0&&c[f-1]===`
`;)f--;c=c.substring(0,f)}let u=a.some(f=>f!=="");switch(i){case"clip":u&&(c+=`
`);break;case"keep":u?c+=`
`.repeat(l+1):c=`
`.repeat(l);break;case"strip":break}let d=this.input.substring(e,this.pos);this.tokens.push(Qe(0,e,this.pos,{rawValue:d,value:c,format:t==="|"?"literal":"folded"}))}getParentBlockIndent(t){for(let e=this.tokens.length-1;e>=0;e--){let n=this.tokens[e];if(!(n.type===8||n.type===10||n.type===9)){if(n.type===1){for(let i=e-1;i>=0;i--){let o=this.tokens[i];if(!(o.type===8||o.type===10||o.type===9))return this.getColumnAt(o.startOffset)}return 0}if(n.type===2)return this.getColumnAt(n.startOffset);if(n.type===11)return-1;break}}return 0}getColumnAt(t){let e=0,n=t-1;for(;n>=0&&this.input[n]!==`
`&&this.input[n]!=="\r";)e++,n--;return e}scanComment(){let t=this.pos;for(;this.pos<this.input.length&&this.input[this.pos]!==`
`&&this.input[this.pos]!=="\r";)this.pos++;this.tokens.push(Qe(10,t,this.pos,{rawValue:this.input.substring(t,this.pos),value:this.input.substring(t,this.pos)}))}scanNewline(){let t=this.pos;this.consumeNewline()&&this.tokens.push(Qe(8,t,this.pos))}skipInlineWhitespace(){for(;this.pos<this.input.length;){let t=this.input[this.pos];if(t===" "||t==="	")this.pos++;else break}}consumeNewline(){return this.pos>=this.input.length?!1:this.input[this.pos]==="\r"&&this.input[this.pos+1]===`
`?(this.pos+=2,!0):this.input[this.pos]===`
`||this.input[this.pos]==="\r"?(this.pos++,!0):!1}peekChar(){return this.input[this.pos]}},Gd=class{constructor(t,e,n,i){this.tokens=t;this.input=e;this.errors=n;this.options=i;this.pos=0}parse(){return this.skipNewlinesAndComments(),this.currentToken().type===11&&(this.advance(),this.skipNewlinesAndComments()),this.currentToken().type===13||this.currentToken().type===12?void 0:this.parseValue(-1)}currentToken(){return this.tokens[this.pos]}peek(t=0){return this.tokens[Math.min(this.pos+t,this.tokens.length-1)]}advance(){let t=this.tokens[this.pos];return t.type!==13&&this.pos++,t}expect(t){let e=this.currentToken();return e.type===t?this.advance():e}emitError(t,e,n,i){this.errors.push({message:t,startOffset:e,endOffset:n,code:i})}skipNewlinesAndComments(){for(;this.currentToken().type===8||this.currentToken().type===10||this.currentToken().type===9&&this.isFollowedByNewlineOrComment();)this.advance()}isFollowedByNewlineOrComment(){let t=this.peek(1);return t.type===8||t.type===10||t.type===13}currentIndent(){return this.currentToken().type===9?this.currentToken().indent:0}parseValue(t){this.skipNewlinesAndComments();let e=this.currentToken(),n=e.type===9?this.peek(1):e;if(n.type===4||n.type===6)return e.type===9&&this.advance(),n.type===4?this.parseFlowMap():this.parseFlowSeq();let i=this.currentIndent();if(this.peekPastIndent().type===2)return this.parseBlockSequence(i);if(this.looksLikeMapping())return this.parseBlockMapping(i);if(e.type===0||e.type===9)return this.parseScalar(t)}peekPastIndent(){return this.currentToken().type===9?this.peek(1):this.currentToken()}looksLikeMapping(){let t=0;return this.peek(t).type===9&&t++,this.peek(t).type===0&&(t++,this.peek(t).type===1)}parseScalar(t=-1){this.currentToken().type===9&&this.advance();let e=this.expect(0);return e.format!=="none"?this.scalarFromToken(e):this.parsePlainMultiline(e,t)}parsePlainMultiline(t,e){let n=t.value,i=t.endOffset;for(;;){let o=this.pos,s=0,a=!1;for(;this.pos<this.tokens.length;){let c=this.currentToken();if(c.type===10)break;if(c.type===8){this.advance();let u=this.currentToken();if(u.type===8){s++;continue}if(u.type===9){let d=this.peek(1);if(d.type===8||d.type===13){s++,this.advance();continue}if(d.type===10)break;if(u.indent>e){a=!0;break}else break}if(u.type===13||u.type===11||u.type===12)break;if(e<0){a=!0;break}break}if(c.type===9)break;break}if(!a){this.pos=o;break}if(this.currentToken().type===9&&this.advance(),this.currentToken().type!==0){if(this.currentToken().type===2){let c=this.advance(),u="-";if(this.currentToken().type===0){let d=this.advance();u="- "+d.value,i=d.endOffset}else i=c.endOffset;s>0?n+=`
`.repeat(s):n+=" ",n+=u;continue}this.pos=o;break}if(this.peek(1).type===1){this.pos=o;break}let l=this.advance();s>0?n+=`
`.repeat(s):n+=" ",n+=l.value,i=l.endOffset}return{type:"scalar",value:n,rawValue:this.input.substring(t.startOffset,i),startOffset:t.startOffset,endOffset:i,format:"none"}}parseBlockMapping(t,e=!1){let n=this.currentToken().startOffset,i=[],o=new Set;if(e){let a=this.parseMappingEntry(t);a&&(o.add(a.key.value),i.push(a))}for(;this.currentToken().type!==13&&(this.skipNewlinesAndComments(),this.currentToken().type!==13);){let a=this.currentIndent();if(a<t)break;if(a!==t)if(a>t)this.emitError(g(150,null,t,a),this.currentToken().startOffset,this.currentToken().endOffset,"unexpected-indentation");else break;if(!this.looksLikeMapping())break;let l=this.parseMappingEntry(t);if(!l)break;!this.options.allowDuplicateKeys&&o.has(l.key.value)&&this.emitError(g(143,null,l.key.value),l.key.startOffset,l.key.endOffset,"duplicate-key"),o.add(l.key.value),i.push(l)}let s=i.length>0?i[i.length-1].value.endOffset:n;return{type:"map",properties:i,style:"block",startOffset:n,endOffset:s}}parseMappingEntry(t){this.currentToken().type===9&&this.advance();let e=this.expect(0),n=this.scalarFromToken(e),i=this.expect(1);if(i.type!==1){this.emitError(g(144,null),i.startOffset,i.endOffset,"expected-colon");return}let o=this.parseMappingValue(t,i);return{key:n,value:o}}parseMappingValue(t,e){let n=this.currentToken();if(n.type===4)return this.parseFlowMap();if(n.type===6)return this.parseFlowSeq();if(n.type===0){this.currentToken().type===9&&this.advance();let s=this.advance();return s.format!=="none"?this.scalarFromToken(s):this.parsePlainMultiline(s,t)}if(this.skipNewlinesAndComments(),this.currentToken().type===13)return this.emitError(g(149,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset);let o=this.currentIndent();return o===t&&this.peekPastIndent().type===2?this.parseValue(t)??this.makeEmptyScalar(e.endOffset):o<=t?(this.emitError(g(149,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset)):this.parseValue(t)??this.makeEmptyScalar(e.endOffset)}parseBlockSequence(t){let e=[],n=this.currentToken().startOffset,i=n,o=!0;for(;this.currentToken().type!==13&&(this.skipNewlinesAndComments(),this.currentToken().type!==13);){let s;if(o&&this.currentToken().type===2?s=this.currentToken().startOffset-this.getLineStart(this.currentToken().startOffset):s=this.currentIndent(),o=!1,s<t)break;if(s!==t)if(s>t)this.emitError(g(150,null,t,s),this.currentToken().startOffset,this.currentToken().endOffset,"unexpected-indentation");else break;if(this.peekPastIndent().type!==2)break;this.currentToken().type===9&&this.advance();let l=this.advance(),c=this.parseSequenceItemValue(t,l);e.push(c),i=c.endOffset}return{type:"sequence",items:e,style:"block",startOffset:n,endOffset:i}}parseSequenceItemValue(t,e){let n=this.currentToken();if(n.type===10&&this.advance(),n.type===4)return this.parseFlowMap();if(n.type===6)return this.parseFlowSeq();if(n.type===2){let o=n.startOffset-this.getLineStart(n.startOffset);return this.parseBlockSequence(o)}if(n.type===0){if(this.peek(1).type===1){let o=n.startOffset-this.getLineStart(n.startOffset);return this.parseBlockMapping(o,!0)}return this.parseScalar(t)}return this.skipNewlinesAndComments(),this.currentToken().type===13?(this.emitError(g(148,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset)):this.currentIndent()<=t?(this.emitError(g(148,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset)):this.parseValue(t)??this.makeEmptyScalar(e.endOffset)}getLineStart(t){let e=t-1;for(;e>=0&&this.input[e]!==`
`&&this.input[e]!=="\r";)e--;return e+1}parseFlowMap(){let t=this.advance(),e=[];for(this.skipFlowWhitespace();this.currentToken().type!==5&&this.currentToken().type!==13;){let i;if(this.currentToken().type===0)i=this.parseFlowScalar();else{this.emitError(g(147,null),this.currentToken().startOffset,this.currentToken().endOffset,"expected-key");break}this.skipFlowWhitespace();let o;this.currentToken().type===1?(this.advance(),this.skipFlowWhitespace(),o=this.parseFlowValue()):o=this.makeEmptyScalar(i.endOffset),e.push({key:i,value:o}),this.skipFlowWhitespace(),this.currentToken().type===3&&(this.advance(),this.skipFlowWhitespace())}let n=this.currentToken();return n.type===5?this.advance():this.emitError(g(145,null),n.startOffset,n.endOffset,"expected-flow-map-end"),{type:"map",properties:e,style:"flow",startOffset:t.startOffset,endOffset:n.type===5?n.endOffset:n.startOffset}}parseFlowSeq(){let t=this.advance(),e=[];for(this.skipFlowWhitespace();this.currentToken().type!==7&&this.currentToken().type!==13;){let i;if(this.currentToken().type===4)i=this.parseFlowMap();else if(this.currentToken().type===6)i=this.parseFlowSeq();else if(this.currentToken().type===0)i=this.parseFlowScalar();else{this.emitError(g(151,null),this.currentToken().startOffset,this.currentToken().endOffset,"unexpected-token"),this.advance();continue}e.push(i),this.skipFlowWhitespace(),this.currentToken().type===3&&(this.advance(),this.skipFlowWhitespace())}let n=this.currentToken();return n.type===7?this.advance():this.emitError(g(146,null),n.startOffset,n.endOffset,"expected-flow-seq-end"),{type:"sequence",items:e,style:"flow",startOffset:t.startOffset,endOffset:n.type===7?n.endOffset:n.startOffset}}parseFlowScalar(){let t=this.advance();if(t.format!=="none")return this.scalarFromToken(t);let e=t.value,n=t.endOffset;for(;;){let i=!1,o=this.pos;for(;o<this.tokens.length;){let a=this.tokens[o];if(a.type===8)i=!0,o++;else if(a.type===9||a.type===10)o++;else break}if(!i||o>=this.tokens.length)break;let s=this.tokens[o];if(s.type===0&&s.format==="none")this.pos=o+1,e+=" "+s.value,n=s.endOffset;else break}return{type:"scalar",value:e,rawValue:this.input.substring(t.startOffset,n),startOffset:t.startOffset,endOffset:n,format:"none"}}parseFlowValue(){return this.currentToken().type===4?this.parseFlowMap():this.currentToken().type===6?this.parseFlowSeq():this.currentToken().type===0?this.parseFlowScalar():this.makeEmptyScalar(this.currentToken().startOffset)}skipFlowWhitespace(){for(;;){let t=this.currentToken().type;if(t===8||t===9||t===10)this.advance();else break}}scalarFromToken(t){return{type:"scalar",value:t.value,rawValue:t.rawValue,startOffset:t.startOffset,endOffset:t.endOffset,format:t.format}}makeEmptyScalar(t){return{type:"scalar",value:"",rawValue:"",startOffset:t,endOffset:t,format:"none"}}};var im="vscode-agent-client";function Vi(r,t){let e=r.authority||"-";return y.from({scheme:im,authority:t,path:`/${r.scheme}/${e}${r.path}`})}function kI(r){let t=r.path,e=t.indexOf("/",1);if(e===-1)return y.from({scheme:"file",path:t});let n=t.substring(1,e),i=t.indexOf("/",e+1);if(i===-1){let a=t.substring(e+1);return y.from({scheme:n,authority:a==="-"?"":a,path:"/"})}let o=t.substring(e+1,i);o==="-"&&(o="");let s=t.substring(i);return y.from({scheme:n,authority:o||void 0,path:s})}var $R={format:0,manifestPath:"plugin.json",hookConfigPath:"hooks.json",pluginRootToken:void 0,pluginRootEnvVar:void 0,parseHooks(r,t,e,n,i){return MI(r,t,n,i)}},VR={format:1,manifestPath:".claude-plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${CLAUDE_PLUGIN_ROOT}",pluginRootEnvVar:"CLAUDE_PLUGIN_ROOT",parseHooks(r,t,e,n,i){return NI(r,t,e,n,i,"${CLAUDE_PLUGIN_ROOT}","CLAUDE_PLUGIN_ROOT")}},BR={format:2,manifestPath:".plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${PLUGIN_ROOT}",pluginRootEnvVar:"PLUGIN_ROOT",parseHooks(r,t,e,n,i){return NI(r,t,e,n,i,"${PLUGIN_ROOT}","PLUGIN_ROOT")}};async function HR(r,t){return await Ja(ee(r,".plugin","plugin.json"),t)?BR:r.path.split("/").includes(".claude")||await Ja(ee(r,".claude-plugin","plugin.json"),t)?VR:$R}function Qa(r,t){let e=Gt(r.toString());return t?`${e.replace(/#/g,"%23")}#${t}`:e}function zR(r){let t=r.uri.toString();return{type:"agent",id:Qa(r.uri),uri:t,name:r.name,...r.description?{description:r.description}:{}}}function qR(r){let t=r.uri.toString();return{type:"skill",id:Qa(r.uri),uri:t,name:r.name,...r.description?{description:r.description}:{}}}function KR(r){let t=r.uri.toString();return{type:"rule",id:Qa(r.uri),uri:t,name:r.name,...r.description?{description:r.description}:{}}}function jR(r){return{type:"hook",id:Qa(r),uri:r.toString(),name:pe(r)}}function GR(r,t){return{type:"mcpServer",id:Qa(r,`mcp=${encodeURIComponent(t)}`),uri:r.toString(),name:t}}var rm={paths:[],exclusive:!1};function ja(r){if(r==null)return rm;if(typeof r=="string"){let t=r.trim();return t?{paths:[t],exclusive:!1}:rm}if(Array.isArray(r))return{paths:r.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0),exclusive:!1};if(typeof r=="object"){let t=r;if(Array.isArray(t.paths)){let e=t.paths.filter(i=>typeof i=="string").map(i=>i.trim()).filter(i=>i.length>0),n=t.exclusive===!0;return{paths:e,exclusive:n}}}return rm}function Ga(r,t,e,n){let i=n&&js(r,n)?n:r,o=[];e.exclusive||o.push(ee(r,t));for(let s of e.paths){let a=Ht(ee(r,s));js(a,i)&&o.push(a)}return o}function JR(r){if(!r||typeof r!="object"||Array.isArray(r))return;let t=r;return Object.hasOwn(t,"mcpServers")?t.mcpServers:t}function QR(r){if(!r||typeof r!="object")return;let t=r,e=typeof t.type=="string"?t.type:void 0,n=typeof t.command=="string"?t.command:void 0,i=typeof t.url=="string"?t.url:void 0,o=Array.isArray(t.args)?t.args.filter(d=>typeof d=="string"):void 0,s=t.env&&typeof t.env=="object"?Object.fromEntries(Object.entries(t.env).filter(([,d])=>typeof d=="string"||typeof d=="number"||d===null).map(([d,f])=>[d,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(([,d])=>typeof d=="string").map(([d,f])=>[d,f])):void 0,u=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:u}:void 0;if(e==="http"||e==="sse"||!e&&i)return i?{type:"http",url:i,headers:c,dev:u}:void 0}}var YR=/[\s&|<>()^;!`"']/;function XR(r,t,e){if(!r.includes(e))return r;if(!YR.test(t))return r.replaceAll(e,t);let n=Bt(e),i=new RegExp(`(["']?)`+n+"([\\w./\\\\~:-]*)","g");return r.replace(i,(o,s,a)=>{let l=t+a;return s?s+l:'"'+l.replace(/"/g,'\\"')+'"'})}function ZR(r,t,e,n){let i=a=>a.replaceAll(e,t),o=r.configuration,s;if(o.type==="stdio"){let a={...o};a.command=i(a.command),a.args&&(a.args=a.args.map(i)),a.cwd&&(a.cwd=i(a.cwd)),a.env={...a.env};for(let[l,c]of Object.entries(a.env))typeof c=="string"&&(a.env[l]=i(c));a.env[n]=t,a.envFile&&(a.envFile=i(a.envFile)),s=a}else{let a={...o};a.url=i(a.url),a.headers&&(a.headers=Object.fromEntries(Object.entries(a.headers).map(([l,c])=>[l,i(c)]))),s=a}return{name:r.name,configuration:s,uri:r.uri,customization:r.customization}}var eE=/\$\{(?![A-Za-z]+:)([A-Z_][A-Z0-9_]*)\}/g;function tE(r){return ta(r,t=>{if(y.isUri(t))return t;if(typeof t=="string"){let e=t.replace(eE,"${env:$1}");return e!==t?e:void 0}})}var nE={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 iE(r){if(r.type!==void 0&&r.type!=="command")return;let t=typeof r.command=="string"&&r.command.length>0,e=typeof r.bash=="string"&&r.bash.length>0,n=typeof r.powershell=="string"&&r.powershell.length>0,i=typeof r.windows=="string"&&r.windows.length>0,o=typeof r.linux=="string"&&r.linux.length>0,s=typeof r.osx=="string"&&r.osx.length>0;if(!t&&!e&&!n&&!i&&!o&&!s)return;let a=i?r.windows:n?r.powershell:void 0,l=o?r.linux:e?r.bash:void 0,c=s?r.osx:e?r.bash:void 0,u=typeof r.timeout=="number"?r.timeout:typeof r.timeoutSec=="number"?r.timeoutSec:void 0;return{...t&&{command:r.command},...a&&{windows:a},...l&&{linux:l},...c&&{osx:c},...typeof r.env=="object"&&r.env!==null&&{env:r.env},...u!==void 0&&{timeout:u}}}function AI(r,t,e){let n=iE(r);if(!n)return;let i,o=typeof r.cwd=="string"?r.cwd:void 0;if(o){let s=od(o,e);Yt(s)?i=y.file(s):t&&(i=ee(t,s))}else i=t;return{...n,cwd:i}}function rE(r,t,e){if(!r||typeof r!="object")return[];let n=r,i=[],o=n.hooks;if(o!==void 0&&Array.isArray(o))for(let s of o){if(!s||typeof s!="object")continue;let a=AI(s,t,e);a&&i.push(a)}else{let s=AI(n,t,e);s&&i.push(s)}return i}function MI(r,t,e,n){if(!t||typeof t!="object")return[];let i=t;if(i.disableAllHooks===!0)return[];let o=i.hooks;if(!o||typeof o!="object")return[];let s=o,a=[],l=jR(r);for(let c of Object.keys(s)){let u=nE[c];if(!u)continue;let d=s[c];if(!Array.isArray(d))continue;let f=[];for(let m of d)f.push(...rE(m,e,n));f.length>0&&a.push({type:u,commands:f,uri:r,originalId:c,customization:l})}return a}function NI(r,t,e,n,i,o,s){let a=e.fsPath,l=t,c=d=>{for(let f of["command","windows","linux","osx"])typeof d[f]=="string"&&(d[f]=XR(d[f],a,o));(!d.env||typeof d.env!="object")&&(d.env={}),d.env[s]=a};for(let d of Object.values(l.hooks??{}))if(Array.isArray(d))for(let f of d){if(!f||typeof f!="object")continue;let m=f;if(Array.isArray(m.hooks))for(let h of m.hooks)c(h);else c(m)}return MI(r,ta(t,d=>typeof d=="string"?d.replaceAll(o,e.fsPath):void 0),n,i)}async function om(r,t){try{let e=await t.readFile(r);return ud(e.value.toString())}catch{return}}async function Ja(r,t){try{return await t.resolve(r),!0}catch{return!1}}var Jd=".md",DI=".mdc",OI=".instructions.md";async function oE(r,t,e){let n=new Set,i=[],o=(s,a)=>{n.has(s)||(n.add(s),i.push({uri:a,name:s}))};for(let s of t){let a=y.joinPath(s,"SKILL.md");if(await Ja(a,e)){o(pe(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 u=y.joinPath(c.resource,"SKILL.md");await Ja(u,e)&&o(pe(c.resource),u)}}if(i.length===0){let s=y.joinPath(r,"SKILL.md");await Ja(s,e)&&o(pe(r),s)}return i.sort((s,a)=>s.name.localeCompare(a.name)),i}async function sE(r,t){let e=new Set,n=[],i=(o,s)=>{e.has(o)||(e.add(o),n.push({uri:s,name:o}))};for(let o of r){let s;try{s=await t.resolve(o)}catch{continue}if(s.isFile&&Gs(o).toLowerCase()===Jd){i(pe(o).slice(0,-Jd.length),o);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children)!a.isFile||Gs(a.resource).toLowerCase()!==Jd||i(pe(a.resource).slice(0,-Jd.length),a.resource)}return n.sort((o,s)=>o.name.localeCompare(s.name)),n}function LI(r){let t=pe(r),e=t.toLowerCase();if(e.endsWith(DI))return t.slice(0,-DI.length);if(e.endsWith(OI))return t.slice(0,-OI.length)}async function aE(r,t){let e=new Set,n=[],i=(o,s)=>{e.has(o)||(e.add(o),n.push({uri:s,name:o}))};for(let o of r){let s;try{s=await t.resolve(o)}catch{continue}if(s.isFile){let a=LI(o);a&&i(a,o);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children){if(!a.isFile)continue;let l=LI(a.resource);l&&i(l,a.resource)}}return n.sort((o,s)=>o.name.localeCompare(s.name)),n}async function lE(r,t){let e=await sE(r,t);if(e.length===0)return e;let n=await Promise.all(e.map(async s=>{try{let{name:a,description:l}=await sm(s.uri,t);return{uri:s.uri,name:a||s.name,...l?{description:l}:{}}}catch{return s}})),i=new Set,o=[];for(let s of n)i.has(s.name)||(i.add(s.name),o.push(s));return o.sort((s,a)=>s.name.localeCompare(a.name)),o}async function sm(r,t){let e=pe(r).replace(/\.agent\.md$/i,"");try{let n=await t.readFile(r),i=Zo(n.value.toString()),o=i?.getStringValue("name")?.trim()||e,s=i?.getStringValue("description")?.trim();return{name:o,...s?{description:s}:{}}}catch{return{name:e}}}async function cE(r,t,e,n,i,o){for(let s of t){let a=await om(s,n);if(a)return e.parseHooks(s,a,r,i,o)}return[]}async function dE(r,t,e,n){let i=new Map;for(let o of r){let s=await om(o,n);for(let a of UI(o,s,t,e))i.has(a.name)||i.set(a.name,a)}return[...i.values()].sort((o,s)=>o.name.localeCompare(s.name))}function UI(r,t,e,n){let i=JR(t);if(!i)return[];let o=[];for(let[s,a]of Object.entries(i)){let l=QR(a);if(!l)continue;let c={name:s,configuration:l,uri:r,customization:GR(r,s)};n.pluginRootToken&&n.pluginRootEnvVar&&(c=ZR(c,e,n.pluginRootToken,n.pluginRootEnvVar)),c=tE(c),o.push(c)}return o}async function Qd(r,t,e,n,i){let o=await HR(r,t),s=await om(ee(r,o.manifestPath),t),a=s&&typeof s=="object"?s:void 0,l=Ga(r,o.hookConfigPath,ja(a?.hooks),i),c=Ga(r,".mcp.json",ja(a?.mcpServers),i),u=Ga(r,"skills",ja(a?.skills),i),d=Ga(r,"agents",ja(a?.agents),i),f=Ga(r,"rules",ja(a?.rules),i),m=[],h=a?.mcpServers;h&&typeof h=="object"&&!Array.isArray(h)&&!Le(h,{paths:!0})&&(m=UI(ee(r,o.manifestPath),{mcpServers:h},r.fsPath,o));let v=[],S=a?.hooks;if(S&&typeof S=="object"&&!Array.isArray(S)&&!Le(S,{paths:!0})){let j=ee(r,o.manifestPath);v=o.parseHooks(j,{hooks:S},r,e,n)}let[_,b,I,R,P]=await Promise.all([v.length>0?Promise.resolve(v):cE(r,l,o,t,e,n),m.length>0?Promise.resolve(m):dE(c,r.fsPath,o,t),oE(r,u,t),lE(d,t),aE(f,t)]);return{hooks:_,mcpServers:b,skills:I.map(pE),agents:R.map(uE),instructions:P.map(fE)}}function uE(r){return{...r,customization:zR(r)}}function pE(r){return{...r,customization:qR(r)}}function fE(r){return{...r,customization:KR(r)}}function Yd(r,t){if(r.length===0||r.charCodeAt(0)!==47)return;let e=1;for(;e<r.length;){let i=r.charCodeAt(e);if(i===32||i===9||i===10||i===13)break;e++}if(t<0||t>e)return;let n=r.slice(0,e);return{token:n,typed:n.slice(1),rangeStart:0,rangeEnd:e}}var Xd=class extends T{constructor(e,n,i,o=gE()){super();this._getAgent=e;this._fileService=n;this._logService=i;this._userHome=o;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"];this._skillCache=new Map;this._watchedAgents=new Set}async provideCompletionItems(e,n){let i=Yd(e.text,e.offset);if(!i)return[];let o=this._getAgent(e.channel);if(!o)return[];this._watchAgent(o);let s=await this._getCandidates(o,typeof e.channel=="string"?y.parse(e.channel):e.channel);if(n.isCancellationRequested||s.length===0)return[];let a=new Set,l=new Map;for(let c of s){let u=this._resolvePluginRoot(c),d=this._cacheKey(o.id,u,c.nonce);a.add(d);let f=await this._getCachedSkills(o.id,d,u);if(n.isCancellationRequested)return[];for(let m of f)i.typed.length>0&&!m.slashName.startsWith(i.typed)||l.has(m.slashName)||l.set(m.slashName,m)}return this._pruneUnreachableCacheEntries(o.id,a),[...l.values()].map(c=>({insertText:"/"+c.slashName+" ",rangeStart:i.rangeStart,rangeEnd:i.rangeEnd,attachment:{type:"simple",label:"/"+c.slashName,_meta:{uri:c.uri.toString(),name:c.slashName,displayName:c.displayName,...c.description!==void 0?{description:c.description}:{}}}}))}async _getCandidates(e,n){let i=[];if(e.getSessionCustomizations)try{i=await e.getSessionCustomizations(n)}catch(l){this._logService.warn(`[AgentHostSkillCompletionProvider] Error reading session customizations for '${n.toString()}': ${Ct(l)}`)}let o=new Set,s=[];for(let l of i){o.add(l.uri);let c=l.nonce;s.push({customization:l,...c!==void 0?{nonce:c}:{},...l.clientId!==void 0?{clientId:l.clientId}:{},...l.load!==void 0?{load:l.load}:{}})}let a=e.getCustomizations?.()??[];for(let l of a)o.has(l.uri)||s.push({customization:l});return s.filter(l=>l.customization.enabled&&l.load?.kind!=="loading"&&l.load?.kind!=="error")}_watchAgent(e){!e.onDidCustomizationsChange||this._watchedAgents.has(e.id)||(this._watchedAgents.add(e.id),this._register(e.onDidCustomizationsChange(()=>this._clearCache(e.id))))}_resolvePluginRoot(e){let n=y.parse(e.customization.uri);return e.clientId?Vi(n,e.clientId):n}_cacheKey(e,n,i){return i?`${e}::${n.toString()}::${i}`:`${e}::${n.toString()}`}_getCachedSkills(e,n,i){let o=this._skillCache.get(n);return o||(o={agentId:e,value:this._readSkills(i)},this._skillCache.set(n,o)),o.value}async _readSkills(e){try{let n=await Qd(e,this._fileService,void 0,this._userHome);return await Promise.all(n.skills.map(i=>this._readSkillMetadata(i)))}catch(n){return this._logService.warn(`[AgentHostSkillCompletionProvider] Error parsing customization '${e.toString()}': ${Ct(n)}`),[]}}async _readSkillMetadata(e){let n=e.name,i;try{let o=await this._fileService.readFile(e.uri),s=Zo(o.value.toString());n=s?.getStringValue("name")?.trim()||e.name,i=s?.getStringValue("description")?.trim()||void 0}catch(o){this._logService.trace(`[AgentHostSkillCompletionProvider] Error reading skill metadata '${e.uri.toString()}': ${Ct(o)}`)}return{uri:e.uri,slashName:e.name,displayName:n,...i!==void 0?{description:i}:{}}}_clearCache(e){for(let[n,i]of this._skillCache)i.agentId===e&&this._skillCache.delete(n)}_pruneUnreachableCacheEntries(e,n){for(let[i,o]of this._skillCache)o.agentId===e&&!n.has(i)&&this._skillCache.delete(i)}};function gE(){return process.env.HOME??process.env.USERPROFILE??""}import*as FI from"child_process";var mE=new Ee(async()=>(await import("@vscode/ripgrep-universal")).rgPath.replace(/\bnode_modules\.asar\b/,"node_modules.asar.unpacked"));function es(){return mE.value}var hE=5e4,yE=3e4,ts=class extends T{constructor(e){super();this._logService=e;this._cache=new Map;this._activeChildren=new Set}dispose(){for(let e of this._activeChildren)try{e.kill()}catch{}this._activeChildren.clear(),this._cache.clear(),super.dispose()}async getFiles(e,n){if(e.scheme!==oe.file)return[];let i=e.toString(),o=Date.now(),s=this._cache.get(i),a;if(s&&s.expiresAt>o)a=s.promise;else{a=this._enumerate(e);let l={promise:a,expiresAt:o+yE};this._cache.set(i,l),a.catch(()=>{this._cache.get(i)===l&&this._cache.delete(i)})}if(n.isCancellationRequested)throw new re;return n===ze.None?a:new Promise((l,c)=>{let u=n.onCancellationRequested(()=>{u.dispose(),c(new re)});a.then(d=>{u.dispose(),l(d)},d=>{u.dispose(),c(d)})})}async _enumerate(e){let n=await es();return new Promise(i=>{let o=e.fsPath,s=["--files","--hidden","--no-require-git","--follow","--no-config","--glob","!.git"],a;try{a=FI.spawn(n,s,{cwd:o})}catch(h){this._logService.warn(`[AgentHostWorkspaceFiles] Failed to spawn ripgrep: ${h}`),i([]);return}this._activeChildren.add(a);let l=[],c="",u=!1,d=!1,f=h=>{d||(d=!0,this._activeChildren.delete(a),i(h))};a.stdout.setEncoding("utf8"),a.stdout.on("data",h=>{if(u)return;c+=h;let v;for(;(v=c.indexOf(`
`))>=0;){let S=c.slice(0,v).replace(/\r$/,"");if(c=c.slice(v+1),!!S&&(l.push(y.joinPath(e,S)),l.length>=hE)){u=!0;try{a.kill()}catch{}break}}}),a.stderr.setEncoding("utf8");let m="";a.stderr.on("data",h=>{m+=h}),a.on("error",h=>{this._logService.warn(`[AgentHostWorkspaceFiles] ripgrep error: ${h}`),f([])}),a.on("close",()=>{if(!u&&c.length>0){let h=c.replace(/\r$/,"");h&&l.push(y.joinPath(e,h)),c=""}m&&this._logService.trace(`[AgentHostWorkspaceFiles] ripgrep stderr: ${m}`),f(l)})})}};ts=w([C(0,L)],ts);var vE=3e4,bE=3e4,Zd=class extends T{constructor(e,n,i,o,s,a=oS,l,c=Ed,u){super();this._logService=e;this._fileService=n;this._sessionDataService=i;this._productService=o;this._gitService=s;this._checkpointService=a;this._rootConfigResource=l;this._telemetryService=c;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 z);this._agents=In("agents",[]);this._skillCompletionProviderRegistered=!1;this._resourceSubscribers=new Fe;this._pendingSessionGc=this._register(new wl);this._resourceWatches=this._register(new We);this._clientDispatchQueues=new Map;this._logService.info("AgentService initialized"),this._stateManager=this._register(new Do(e,{changesetStateRetention:{canEvict:S=>this._changesets?this._isChangesetEvictable(S):!1}})),this._register(this._stateManager.onDidEmitEnvelope(S=>this._onDidAction.fire(S))),this._register(this._stateManager.onDidEmitNotification(S=>this._onDidNotification.fire(S)));let d=this._register(new xo(this._stateManager,this._logService,this._rootConfigResource));this._configurationService=d;let f=u??this._register(new An(this._fileService,this._logService));Ld(this._telemetryService,this._stateManager.rootState.config?.values);let m=new Ai([L,this._logService],[Lt,this._productService],[Je,d],[Jo,f],[Nt,this._gitService],[Li,this._telemetryService],[vt,this._sessionDataService]),h=this._register(new yo(m,!0));m.set(En,this._checkpointService),this._changesets=this._register(h.createInstance(di,this._stateManager)),m.set(No,this._changesets),this._changesetCoordinator=this._register(h.createInstance(Qo,this._stateManager)),this._register(this._stateManager.onDidChangeSessionActiveTurn(S=>this._changesetCoordinator.onSessionTurnActiveChanged(S.session,S.active))),this._completions=this._register(h.createInstance(Yo));let v=this._register(h.createInstance(ts));this._register(this._completions.registerProvider(new Kd(this._stateManager,v))),this._sideEffects=this._register(h.createInstance(Go,this._stateManager,{getAgent:S=>this._findProviderForSession(S),sessionDataService:this._sessionDataService,agents:this._agents,onTurnComplete:S=>{let _=this._stateManager.getSessionState(S)?.summary.workingDirectory;this._attachGitState(y.parse(S),_?y.parse(_):void 0)}})),this._terminalManager=this._register(h.createInstance(Eo,this._stateManager))}get stateManager(){return this._stateManager}get configurationService(){return this._configurationService}get terminalManager(){return this._terminalManager}get completionsService(){return this._completions}get completionTriggerCharacters(){return this._completions.triggerCharacters}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)),e.onDidMaterializeSession&&this._providerSubscriptions.add(e.onDidMaterializeSession(n=>this._onDidMaterializeSession(n))),this._registerSkillCompletionProvider(),this._defaultProvider||(this._defaultProvider=e.id),this._updateAgents()}_registerSkillCompletionProvider(){if(this._skillCompletionProviderRegistered)return;this._skillCompletionProviderRegistered=!0;let e=this._register(new Xd(n=>this._findProviderForSession(n),this._fileService,this._logService));this._register(this._completions.registerProvider(e))}async authenticate(e){this._logService.trace(`[AgentService] authenticate called: resource=${e.resource}`);let n=[...this._providers.values()].filter(s=>s.getProtectedResources().some(a=>a.resource===e.resource)),i=await Promise.allSettled(n.map(s=>s.authenticate(e.resource,e.token))),o=!1;for(let s=0;s<i.length;s++){let a=i[s];a.status==="fulfilled"?o||=a.value:this._logService.error(a.reason,`[AgentService] Provider '${n[s].id}' authenticate threw for resource=${e.resource}`)}return{authenticated:o}}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=s.session.toString(),c=this._changesetCoordinator.getListMetadataKeys(l),u=c?{customTitle:!0,isRead:!0,isArchived:!0,isDone:!0,...c}:{customTitle:!0,isRead:!0,isArchived:!0,isDone:!0},d=await a.object.getMetadataObject(u),f=s;return d.customTitle&&(f={...f,summary:d.customTitle}),d.isRead!==void 0&&(f={...f,isRead:d.isRead==="true"}),d.isArchived!==void 0?f={...f,isArchived:d.isArchived==="true"}:d.isDone!==void 0&&(f={...f,isArchived:d.isDone==="true"}),this._changesetCoordinator.decorateListEntry(f,d)}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,activity:a.summary.activity,model:a.summary.model??s.model,agent:a.summary.agent??s.agent,changesets:a.summary.changesets??s.changesets}:s});return this._logService.trace(`[AgentService] listSessions returned ${o.length} sessions`),o}async createSession(e){let n=e?.provider??this._defaultProvider,i=n?this._providers.get(n):void 0;if(!i)throw new Error(`No agent provider registered for: ${n??"(none)"}`);if(e?.fork){let u=this._stateManager.getSessionState(e.fork.session.toString())?.turns.slice(0,e.fork.turnIndex+1)??[];if(u.length===0)e={...e,fork:void 0};else{let d=new Map;for(let f of u)d.set(f.id,q());e={...e,fork:{...e.fork,turnIdMapping:d}}}}this._logService.trace("[AgentService] createSession: initializing auto-approver and creating session...");let[,o]=await Promise.all([this._sideEffects.initialize(),i.createSession(e)]),s=o.session;this._logService.trace("[AgentService] createSession: initialization complete"),this._cancelPendingSessionGc(s),this._logService.trace(`[AgentService] createSession: provider=${i.id} model=${e?.model?.id??"(default)"}`),this._sessionToProvider.set(s.toString(),i.id),this._logService.trace(`[AgentService] createSession returned: ${s.toString()}`);let[a,l]=await Promise.all([this._resolveCreatedSessionConfig(i,e),i.getSessionCustomizations?i.getSessionCustomizations(s).catch(c=>{this._logService.error("[AgentService] createSession: failed to resolve initial customizations",c)}):Promise.resolve(void 0)]);if(e?.fork){let c=this._stateManager.getSessionState(e.fork.session.toString()),u=[];c&&e.fork.turnIdMapping&&(u=c.turns.slice(0,e.fork.turnIndex+1).map(S=>({...S,id:e.fork.turnIdMapping.get(S.id)??q()})));let d=g(1901,null),f=c?.summary.title,m=f?f.startsWith(d)?f:`${d}${f}`:g(1900,null),h=this._buildInitialSummary(i,s,e,o,m),v=this._stateManager.createSession(h);v.config=a,v.turns=u,v.activeClient=e.activeClient,l&&l.length>0&&(v.customizations=[...l])}else{let c=this._buildInitialSummary(i,s,e,o,""),u=this._stateManager.createSession(c,{emitNotification:!o.provisional});u.config=a,u.activeClient=e?.activeClient,l&&l.length>0&&(u.customizations=[...l])}return a?.values&&Object.keys(a.values).length>0&&!o.provisional&&this._persistConfigValues(s,a.values),this._changesetCoordinator.onSessionCreated(s.toString()),o.provisional||(this._stateManager.dispatchServerAction(s.toString(),{type:"session/ready"}),this._attachGitState(s,o.workingDirectory??e?.workingDirectory)),s}_buildInitialSummary(e,n,i,o,s){let a=Date.now();return{resource:n.toString(),provider:e.id,title:s,status:1,createdAt:a,modifiedAt:a,...o.project?{project:{uri:o.project.uri.toString(),displayName:o.project.displayName}}:{},model:i?.model,agent:i?.agent,workingDirectory:(o.workingDirectory??i?.workingDirectory)?.toString(),changesets:jf(n.toString())}}_onDidMaterializeSession(e){let n=e.session.toString(),i=this._stateManager.getSessionState(n);if(!i){this._logService.warn(`[AgentService] onDidMaterializeSession for unknown session: ${n}`);return}let o={...i.summary,...e.project?{project:{uri:e.project.uri.toString(),displayName:e.project.displayName}}:{},workingDirectory:e.workingDirectory?.toString()??i.summary.workingDirectory,modifiedAt:Date.now()},s=i.config?.values;s&&Object.keys(s).length>0&&this._persistConfigValues(e.session,s),this._stateManager.markSessionPersisted(n,o),this._stateManager.dispatchServerAction(n,{type:"session/ready"}),this._attachGitState(e.session,e.workingDirectory),this._changesetCoordinator.onSessionMaterialized(n)}_attachGitState(e,n){if(!n)return;let i=e.toString();this._gitService.getSessionGitState(n).then(o=>{if(!o){this._stripGitOnlyChangesetEntries(i);return}let s=this._stateManager.getSessionState(i)?._meta;if(Me(tg(s),o))return;let a=Cb(s,o);this._stateManager.setSessionMeta(i,a),this._updateBranchChangesetDescription(i,o)},o=>{this._logService.warn(`[AgentService] Failed to compute git state for ${e}`,o)})}_stripGitOnlyChangesetEntries(e){let i=this._stateManager.getSessionState(e)?.summary.changesets;if(!i||i.length===0)return;let o=Ot(e),s=Kt(e),a=i.filter(l=>l.uriTemplate!==o&&l.uriTemplate!==s);a.length!==i.length&&this._stateManager.setSessionChangesets(e,a)}_updateBranchChangesetDescription(e,n){let i=Zv(n.branchName,n.baseBranchName),s=this._stateManager.getSessionState(e)?.summary.changesets;if(!s||s.length===0)return;let a=Ot(e),l=!1,c=s.map(u=>{if(u.uriTemplate!==a||u.description===i)return u;if(l=!0,i===void 0){let{description:d,...f}=u;return f}return{...u,description:i}});l&&this._stateManager.setSessionChangesets(e,c)}_persistConfigValues(e,n){let i;try{i=this._sessionDataService.openDatabase(e)}catch(o){this._logService.warn(`[AgentService] Failed to open session database to persist configValues for ${e.toString()}: ${Ct(o)}`);return}i.object.setMetadata("configValues",JSON.stringify(n)).catch(o=>{this._logService.warn(`[AgentService] Failed to persist configValues for ${e.toString()}: ${Ct(o)}`)}).finally(()=>{i.dispose()})}async _resolveCreatedSessionConfig(e,n){if(!(!n?.config&&!n?.workingDirectory))try{let i=await e.resolveSessionConfig({provider:e.id,workingDirectory:n.workingDirectory,config:n.config});return{schema:i.schema,values:i.values}}catch(i){return this._logService.error(`[AgentService] Failed to resolve created session config for provider ${e.id}`,i),n.config?{schema:{type:"object",properties:{}},values:n.config}:void 0}}async resolveSessionConfig(e){let n=e.provider??this._defaultProvider,i=n?this._providers.get(n):void 0;if(!i)throw new Error(`No agent provider registered for: ${n??"(none)"}`);return i.resolveSessionConfig(e)}async sessionConfigCompletions(e){let n=e.provider??this._defaultProvider,i=n?this._providers.get(n):void 0;if(!i)throw new Error(`No agent provider registered for: ${n??"(none)"}`);return i.sessionConfigCompletions(e)}async completions(e){return this._completions.completions(e)}async getCompletionTriggerCharacters(){return this._completions.triggerCharacters}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._changesetCoordinator.onSessionDisposed(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,n){this._logService.trace(`[AgentService] subscribe: ${e.toString()}`);let i=e.toString();this.addSubscriber(e,n);try{let o=this._terminalManager.getTerminalState(i);if(o)return{resource:i,state:o,fromSeq:this._stateManager.serverSeq};let s=this._stateManager.getSnapshot(i),a=Tn(i);if(s&&a&&!this._stateManager.getSessionState(a.sessionUri)&&(await this._changesetCoordinator.restoreSessionIfChangesetSubscription(e,c=>this.restoreSession(c)),s=this._stateManager.getSnapshot(i)),!s)if(await this._changesetCoordinator.tryHandleSubscribe(e,u=>this.restoreSession(u)))s=this._stateManager.getSnapshot(i);else{let u=Ge(e);u?await this._restoreSubagentSession(i,u.parentSession):await this.restoreSession(e),s=this._stateManager.getSnapshot(i)}if(!s)throw new Error(`Cannot subscribe to unknown resource: ${i}`);let l=this._stateManager.getSessionState(i);if(l&&tg(l._meta)===void 0){let c=l.summary?.workingDirectory;this._attachGitState(e,c?y.parse(c):void 0)}return s}catch(o){throw this.unsubscribe(e,n),o}}addSubscriber(e,n){let i=this._resourceSubscribers.get(e),o=!i||i.size===0;i||(i=new Set,this._resourceSubscribers.set(e,i)),i.add(n),this._cancelPendingSessionGc(e),o&&this._changesetCoordinator.onFirstSubscriber(e)}unsubscribe(e,n){let i=this._resourceSubscribers.get(e);i&&(i.delete(n),!(i.size>0)&&(this._resourceSubscribers.delete(e),this._changesetCoordinator.onLastSubscriber(e),this._stateManager.onChangesetLivenessChanged(),!this._maybeScheduleSessionGc(e)&&this._maybeEvictIdleSession(e)))}_maybeScheduleSessionGc(e){if(Ge(e))return!1;let n=e.toString(),i=this._stateManager.getSessionState(n);return!i||i.turns.length>0||i.activeTurn!==void 0?!1:(this._pendingSessionGc.set(e,Ri(()=>{this._pendingSessionGc.deleteAndDispose(e),this._runSessionGc(e).catch(o=>{this._logService.error(o,`[AgentService] GC failed for ${n}`)})},vE)),!0)}_cancelPendingSessionGc(e){this._pendingSessionGc.deleteAndDispose(e)}async _runSessionGc(e){let n=e.toString();if(this._resourceSubscribers.has(e))return;let i=this._stateManager.getSessionState(n);i&&(i.turns.length>0||i.activeTurn!==void 0)||(this._logService.info(`[AgentService] GC: disposing empty unsubscribed session ${n}`),await this.disposeSession(e))}_maybeEvictIdleSession(e){let n=e.toString();if(this._resourceSubscribers.has(e))return;let i=e;{let l;for(;l=Ge(i);)i=l.parentSession}if(this._resourceSubscribers.has(i))return;for(let l of this._resourceSubscribers.keys())if(this._isSubagentDescendantOf(l,i))return;let o=i.toString(),s=this._stateManager.getSessionState(o);if(!s||s.activeTurn!==void 0)return;this._logService.trace(`[AgentService] Evicting idle session: ${o} (triggered by unsubscribe of ${n})`);let a=Ib(i);for(let l of this._stateManager.getSessionUrisWithPrefix(a))this._stateManager.removeSession(l);this._stateManager.removeSession(o)}_isChangesetEvictable(e){let n=y.parse(e);if(this._resourceSubscribers.has(n))return!1;let i=Tn(e);if(!i)return!1;let o=y.parse(i.sessionUri);if(this._resourceSubscribers.has(o))return!1;for(let s of this._resourceSubscribers.keys())if(this._isSubagentDescendantOf(s,o))return!1;return!this._changesets.isStaticChangesetComputeActive(e)}_isSubagentDescendantOf(e,n){let i=Ge(e);for(;i;){if(ef(i.parentSession,n))return!0;i=Ge(i.parentSession)}return!1}dispatchAction(e,n,i,o){this._logService.trace(`[AgentService] dispatchAction: type=${n.type}, clientId=${i}, clientSeq=${o}`,n);let s=this._clientDispatchQueues.get(i);if(!s&&!this._needsAsyncRewrite(e,n)){this._dispatchActionNow(e,n,i,o);return}let a=(s??Promise.resolve()).then(async()=>{let l=this._needsAsyncRewrite(e,n)?await this._rewriteUserMessageAttachments(e,n,i):n;this._dispatchActionNow(e,l,i,o)}).catch(l=>{this._logService.error(`[AgentService] async dispatchAction failed: ${Ct(l)}`)});this._clientDispatchQueues.set(i,a.finally(()=>{this._clientDispatchQueues.get(i)===a&&this._clientDispatchQueues.delete(i)}))}_dispatchActionNow(e,n,i,o){let s={clientId:i,clientSeq:o};this._stateManager.dispatchClientAction(e,n,s),n.type==="root/configChanged"&&this._configurationService.persistRootConfig(),this._sideEffects.handleAction(e,n)}_needsAsyncRewrite(e,n){if(n.type!=="session/turnStarted"&&n.type!=="session/pendingMessageSet")return!1;let i=this._attachmentsRoot(e).toString();return!!n.message.attachments?.some(o=>this._isRewritableAttachment(o,i))}_isRewritableAttachment(e,n){return e.type==="embeddedResource"?!0:e.type==="resource"?!(e.displayKind==="directory"||e.uri.startsWith(n)):!1}_attachmentsRoot(e){return ee(this._sessionDataService.getSessionDataDir(y.parse(e)),Ec)}async _rewriteUserMessageAttachments(e,n,i){let o=n.message.attachments;if(!o?.length)return n;let s=this._attachmentsRoot(e),a=s.toString(),l=await Promise.all(o.map(c=>this._rewriteSingleAttachment(c,s,a,i)));return{...n,message:{...n.message,attachments:l}}}async _rewriteSingleAttachment(e,n,i,o){try{if(e.type==="embeddedResource"){let s=bn(e.data).buffer,a=this._attachmentBasename(e.label,e.contentType);return this._writeAndRewrite(e,s,a,n)}if(e.type==="resource"&&this._isRewritableAttachment(e,i)){let s=y.parse(e.uri),a=await this._readClientResource(s,o),l=this._attachmentBasename(e.label,ic(s.path));return this._writeAndRewrite(e,a,l,n)}}catch(s){this._logService.warn(`[AgentService] Failed to rewrite attachment '${e.label}': ${Ct(s)}`)}return e}async _readClientResource(e,n){let i=n?Vi(e,n):e;try{return(await this._fileService.readFile(i)).value.buffer}catch(o){if(i!==e)return(await this._fileService.readFile(e)).value.buffer;throw o}}async _writeAndRewrite(e,n,i,o){let s=q(),a=ee(o,s,i);await this._fileService.writeFile(a,k.wrap(n));let l={type:"resource",uri:a.toString(),label:e.label,displayKind:e.displayKind,range:e.range,_meta:e._meta};return e.type==="resource"&&e.selection&&(l.selection=e.selection),l}_attachmentBasename(e,n){let i=(e||"attachment").replace(/[\\/:*?"<>|\u0000-\u001f]/g,"_");if(Gs(y.file(i)))return i;let o=n?fv(n):void 0;return o?`${i}${o}`:i}async resourceList(e){let n;try{n=await this._fileService.resolve(e)}catch{throw new N(ge.NotFound,`Directory not found: ${e.toString()}`)}if(!n.isDirectory)throw new N(ge.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 i=this._findProviderForSession(e);if(!i)throw new N(xn,`No agent for session: ${n}`);let o=await this._getSessionMetadataForRestore(i,e);if(!o)throw new N(xn,`Session not found on backend: ${n}`);let s;try{s=await i.getSessionMessages(e)}catch(S){if(S instanceof N)throw S;let _=S instanceof Error?S.message:String(S);throw new N(So,`Failed to restore session ${n}: ${_}`)}let a=o.summary??"Session",l,c,u,d,f=this._sessionDataService.tryOpenDatabase?.(e);if(f)try{let S=await f;if(S)try{let _=await S.object.getMetadataObject({customTitle:!0,isRead:!0,isArchived:!0,isDone:!0,configValues:!0,...jg});if(_.customTitle&&(a=_.customTitle),_.isRead!==void 0&&(l=_.isRead==="true"),_.isArchived!==void 0?c=_.isArchived==="true":_.isDone!==void 0&&(c=_.isDone==="true"),d=_,_.configValues)try{u=JSON.parse(_.configValues)}catch(b){this._logService.warn(`[AgentService] Failed to parse persisted configValues for ${n}: ${Ct(b)}`)}}finally{S.dispose()}}catch{}let m=1;l&&(m|=32),c&&(m|=64);let h={resource:n,provider:i.id,title:a,status:m,createdAt:o.startTime,modifiedAt:o.modifiedTime,...o.project?{project:{uri:o.project.uri.toString(),displayName:o.project.displayName}}:{},model:o.model,agent:o.agent,workingDirectory:o.workingDirectory?.toString(),changesets:jf(n)};this._stateManager.restoreSession(h,[...s]),this._changesetCoordinator.onSessionRestored(n,d??{}),o._meta&&this._stateManager.setSessionMeta(n,o._meta);let v=await this._resolveCreatedSessionConfig(i,{workingDirectory:o.workingDirectory,config:u});if(v){let S=this._stateManager.getSessionState(n);S&&(S.config=v)}this._logService.info(`[AgentService] Restored session ${n} with ${s.length} turns`),this._attachGitState(e,o.workingDirectory)}async _getSessionMetadataForRestore(e,n){let i=n.toString();if(e.getSessionMetadata)try{return await e.getSessionMetadata(n)}catch(o){if(o instanceof N)throw o;try{return await this._getSessionMetadataFromCatalog(e,n)}catch(s){if(s instanceof N){let a=o instanceof Error?o.message:String(o);throw new N(s.code,`Failed to get session metadata for ${i}: ${a}; ${s.message}`,s.data)}throw s}}return this._getSessionMetadataFromCatalog(e,n)}async _getSessionMetadataFromCatalog(e,n){let i=n.toString(),o;try{o=await e.listSessions()}catch(s){if(s instanceof N)throw s;let a=s instanceof Error?s.message:String(s);throw new N(So,`Failed to list sessions for ${i}: ${a}`)}return o.find(s=>s.session.toString()===i)}async resourceRead(e){let n=Zb(e.toString());if(n)return this._fetchSessionDbContent(n);let i=tS(e.toString());if(i)return this._fetchGitBlobContent(i);try{return{data:(await this._fileService.readFile(e)).value.toString(),encoding:"utf-8",contentType:"text/plain"}}catch{throw new N(ge.NotFound,`Content not found: ${e.toString()}`)}}async resourceWrite(e){let n=typeof e.uri=="string"?y.parse(e.uri):y.revive(e.uri),i;e.encoding==="base64"?i=bn(e.data):i=k.fromString(e.data);let o=e.mode??"truncate",s=e.position??0;try{return e.ifMatch!==void 0||o!=="truncate"||s!==0?await this._resourceWriteWithMode(n,i,o,s,e):e.createOnly?await this._fileService.createFile(n,i,{overwrite:!1}):await this._fileService.writeFile(n,i),{}}catch(a){if(a instanceof N)throw a;if(a instanceof je&&a.fileOperationResult===3)throw new N(ge.Conflict,`ifMatch precondition failed for: ${n.toString()}`);let l=Dt(a);throw l==="EntryExists"?new N(ge.AlreadyExists,`File already exists: ${n.toString()}`):l==="NoPermissions"?new N(ge.PermissionDenied,`Permission denied: ${n.toString()}`):new N(ge.NotFound,`Failed to write file: ${n.toString()}`)}}async _resourceWriteWithMode(e,n,i,o,s){let a,l;try{let d=await this._fileService.readFile(e);a=d.value,l=d.etag}catch(d){if(Dt(d)!=="EntryNotFound")throw d}if(s.ifMatch!==void 0&&(a===void 0||l!==s.ifMatch))throw new N(ge.Conflict,`ifMatch precondition failed for: ${e.toString()}`);let c=a??k.alloc(0),u;switch(i){case"append":{let d=c.byteLength,f=Math.max(0,d-o);u=k.concat([c.slice(0,f),n,c.slice(f,d)]);break}case"insert":{let d=Math.min(o,c.byteLength);u=k.concat([c.slice(0,d),n,c.slice(d,c.byteLength)]);break}case"truncate":default:{let d=Math.min(o,c.byteLength);u=k.concat([c.slice(0,d),n]);break}}await this._fileService.writeFile(e,u,{etag:l})}async resourceCopy(e){let n=y.parse(e.source),i=y.parse(e.destination);try{return await this._fileService.copy(n,i,!e.failIfExists),{}}catch(o){let s=Dt(o);throw s==="EntryExists"?new N(ge.AlreadyExists,`Destination already exists: ${i.toString()}`):s==="NoPermissions"?new N(ge.PermissionDenied,`Permission denied: ${n.toString()}`):new N(ge.NotFound,`Source not found: ${n.toString()}`)}}async resourceDelete(e){let n=y.parse(e.uri);try{return await this._fileService.del(n,{recursive:e.recursive}),{}}catch(i){throw Dt(i)==="NoPermissions"?new N(ge.PermissionDenied,`Permission denied: ${n.toString()}`):new N(ge.NotFound,`Resource not found: ${n.toString()}`)}}async resourceMove(e){let n=y.parse(e.source),i=y.parse(e.destination);try{return await this._fileService.move(n,i,!e.failIfExists),{}}catch(o){let s=Dt(o);throw s==="EntryExists"?new N(ge.AlreadyExists,`Destination already exists: ${i.toString()}`):s==="NoPermissions"?new N(ge.PermissionDenied,`Permission denied: ${n.toString()}`):new N(ge.NotFound,`Source not found: ${n.toString()}`)}}async resourceResolve(e){let n=typeof e.uri=="string"?y.parse(e.uri):y.revive(e.uri);try{let i=await this._fileService.stat(n),o;return i.isSymbolicLink&&e.followSymlinks===!1?o="symlink":i.isDirectory?o="directory":o="file",{uri:n.toString(),type:o,...i.size!==void 0?{size:i.size}:{},...i.mtime!==void 0?{mtime:new Date(i.mtime).toISOString()}:{},...i.ctime!==void 0?{ctime:new Date(i.ctime).toISOString()}:{},...i.etag?{etag:i.etag}:{}}}catch(i){throw Dt(i)==="NoPermissions"?new N(ge.PermissionDenied,`Permission denied: ${n.toString()}`):new N(ge.NotFound,`Resource not found: ${n.toString()}`)}}async resourceMkdir(e){let n=typeof e.uri=="string"?y.parse(e.uri):y.revive(e.uri);try{let i=await this._fileService.stat(n).catch(()=>{});if(i&&!i.isDirectory)throw new N(ge.AlreadyExists,`Path exists and is not a directory: ${n.toString()}`);return await this._fileService.createFolder(n),{}}catch(i){throw i instanceof N?i:Dt(i)==="NoPermissions"?new N(ge.PermissionDenied,`Permission denied: ${n.toString()}`):new N(ge.NotFound,`Failed to create directory: ${n.toString()}`)}}async createResourceWatch(e){let n=typeof e.uri=="string"?y.parse(e.uri):y.revive(e.uri);try{await this._fileService.stat(n)}catch(o){throw Dt(o)==="NoPermissions"?new N(ge.PermissionDenied,`Permission denied: ${n.toString()}`):new N(ge.NotFound,`Resource not found: ${n.toString()}`)}return{channel:mb({root:n.toString(),recursive:e.recursive===!0,excludes:e.excludes,includes:e.includes})}}onResourceWatchSubscribed(e){let n=hb(e);if(!n)return;let i=this._resourceWatches.get(e);if(i)return i.subscribers++,i.pendingGc&&i.pendingGc.clear(),i.descriptor;let o=new z;try{let s=y.parse(n.root),a={recursive:n.recursive,excludes:n.excludes?.items??[],includes:n.includes?.items};if(n.recursive)o.add(this._fileService.watch(s,a)),o.add(this._fileService.onDidFilesChange(l=>{let c=IE(l,s);c.length>0&&this._dispatchResourceWatchChanges(e,c)}));else{let l=this._fileService.createWatcher(s,{...a,recursive:!1});o.add(l),o.add(l.onDidChange(c=>{this._dispatchResourceWatchChanges(e,SE(c))}))}}catch(s){o.dispose(),this._logService.warn(`[AgentService] Failed to start IFileService watcher for ${e}: ${s instanceof Error?s.message:String(s)}`);return}return this._resourceWatches.set(e,{channel:e,descriptor:n,subscribers:1,disposables:o,pendingGc:o.add(new Rt),dispose:()=>o.dispose()}),n}onResourceWatchUnsubscribed(e){let n=this._resourceWatches.get(e);return n?(n.subscribers=Math.max(0,n.subscribers-1),n.subscribers>0||(n.pendingGc.value=Ri(()=>{let i=this._resourceWatches.get(e);!i||i.subscribers>0||this._resourceWatches.deleteAndDispose(e)},bE)),!0):!1}_dispatchResourceWatchChanges(e,n){if(n.length===0)return;let i=n.map(o=>({uri:o.resource.toString(),type:o.type===1?"added":o.type===2?"deleted":"updated"}));this._stateManager.dispatchServerAction(e,{type:"resourceWatch/changed",changes:{items:i}})}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()}async _fetchSessionDbContent(e){let n=y.parse(e.sessionUri),i=this._sessionDataService.openDatabase(n);try{let o=await i.object.readFileEditContent(e.toolCallId,e.filePath);if(!o)throw new N(ge.NotFound,`File edit not found: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);let s=e.part==="before"?o.beforeContent:o.afterContent;if(!s)throw new N(ge.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{i.dispose()}}async _fetchGitBlobContent(e){if(!this._gitService)throw new N(ge.NotFound,`git service unavailable for: ${e.repoRelativePath}`);let n=this._stateManager.getSessionState(e.sessionUri)?.summary.workingDirectory;if(!n)throw new N(ge.NotFound,`Session has no working directory for git-blob URI: ${e.sessionUri}`);let i=await this._gitService.showBlob(y.parse(n),e.sha,e.repoRelativePath);if(!i)throw new N(ge.NotFound,`git blob not found: ${e.sha}:${e.repoRelativePath}`);return{data:i.toString(),encoding:"utf-8",contentType:"text/plain"}}async _restoreSubagentSession(e,n){let i=n.toString();if(!this._stateManager.getSessionState(i))try{await this.restoreSession(n)}catch{this._logService.warn(`[AgentService] Cannot restore parent session for subagent: ${i}`);return}let o=this._stateManager.getSessionState(i);if(!o)return;let s=[...o.turns];o.activeTurn&&s.push(o.activeTurn);let a;for(let d of s){for(let f of d.responseParts)if(f.kind==="toolCall"){let m=f.toolCall,h=m.status==="completed"||m.status==="running"?m.content:void 0;if(h){for(let v of h)if(v.type==="subagent"&&v.resource===e){a=v;break}}}if(a)break}let l=[],c=this._findProviderForSession(n);if(c)try{l=await c.getSessionMessages(y.parse(e))}catch(d){this._logService.warn(`[AgentService] Failed to load subagent turns for ${e}`,d)}let u=a?.title??"Subagent";this._stateManager.restoreSession({resource:e,provider:"subagent",title:u,status:1,createdAt:Date.now(),modifiedAt:Date.now(),...o?.summary.project?{project:o.summary.project}:{}},[...l]),this._logService.info(`[AgentService] Restored subagent session: ${e} with ${l.length} turn(s)`)}_findProviderForSession(e){let n=typeof e=="string"?e:e.toString(),i=this._sessionToProvider.get(n);if(i)return this._providers.get(i);let o=H.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()}};function SE(r){let t=[];for(let e of r.rawAdded)t.push({resource:e,type:1});for(let e of r.rawUpdated)t.push({resource:e,type:0});for(let e of r.rawDeleted)t.push({resource:e,type:2});return t}function IE(r,t){let e=[],n=(i,o)=>{js(i,t)&&e.push({resource:i,type:o})};for(let i of r.rawAdded)n(i,1);for(let i of r.rawUpdated)n(i,0);for(let i of r.rawDeleted)n(i,2);return e}import{CopilotClient as UP,RuntimeConnection as FP}from"@github/copilot-sdk";import*as Pr from"fs/promises";var WI=Object.create(null);function p(r,t){if(Pe(t)){let e=WI[t];if(e===void 0)throw new Error(`${r} references an unknown codicon: ${t}`);t=e}return WI[r]=t,{id:r}}var $I={add:p("add",6e4),plus:p("plus",6e4),gistNew:p("gist-new",6e4),repoCreate:p("repo-create",6e4),lightbulb:p("lightbulb",60001),lightBulb:p("light-bulb",60001),repo:p("repo",60002),repoDelete:p("repo-delete",60002),gistFork:p("gist-fork",60003),repoForked:p("repo-forked",60003),gitPullRequest:p("git-pull-request",60004),gitPullRequestAbandoned:p("git-pull-request-abandoned",60004),recordKeys:p("record-keys",60005),keyboard:p("keyboard",60005),tag:p("tag",60006),gitPullRequestLabel:p("git-pull-request-label",60006),tagAdd:p("tag-add",60006),tagRemove:p("tag-remove",60006),person:p("person",60007),personFollow:p("person-follow",60007),personOutline:p("person-outline",60007),personFilled:p("person-filled",60007),sourceControl:p("source-control",60008),mirror:p("mirror",60009),mirrorPublic:p("mirror-public",60009),star:p("star",60010),starAdd:p("star-add",60010),starDelete:p("star-delete",60010),starEmpty:p("star-empty",60010),comment:p("comment",60011),commentAdd:p("comment-add",60011),alert:p("alert",60012),warning:p("warning",60012),search:p("search",60013),searchSave:p("search-save",60013),logOut:p("log-out",60014),signOut:p("sign-out",60014),logIn:p("log-in",60015),signIn:p("sign-in",60015),eye:p("eye",60016),eyeUnwatch:p("eye-unwatch",60016),eyeWatch:p("eye-watch",60016),circleFilled:p("circle-filled",60017),primitiveDot:p("primitive-dot",60017),closeDirty:p("close-dirty",60017),debugBreakpoint:p("debug-breakpoint",60017),debugBreakpointDisabled:p("debug-breakpoint-disabled",60017),debugHint:p("debug-hint",60017),terminalDecorationSuccess:p("terminal-decoration-success",60017),primitiveSquare:p("primitive-square",60018),edit:p("edit",60019),pencil:p("pencil",60019),info:p("info",60020),issueOpened:p("issue-opened",60020),gistPrivate:p("gist-private",60021),gitForkPrivate:p("git-fork-private",60021),lock:p("lock",60021),mirrorPrivate:p("mirror-private",60021),close:p("close",60022),removeClose:p("remove-close",60022),x:p("x",60022),repoSync:p("repo-sync",60023),sync:p("sync",60023),clone:p("clone",60024),desktopDownload:p("desktop-download",60024),beaker:p("beaker",60025),microscope:p("microscope",60025),vm:p("vm",60026),deviceDesktop:p("device-desktop",60026),file:p("file",60027),more:p("more",60028),ellipsis:p("ellipsis",60028),kebabHorizontal:p("kebab-horizontal",60028),mailReply:p("mail-reply",60029),reply:p("reply",60029),organization:p("organization",60030),organizationFilled:p("organization-filled",60030),organizationOutline:p("organization-outline",60030),newFile:p("new-file",60031),fileAdd:p("file-add",60031),newFolder:p("new-folder",60032),fileDirectoryCreate:p("file-directory-create",60032),trash:p("trash",60033),trashcan:p("trashcan",60033),history:p("history",60034),clock:p("clock",60034),folder:p("folder",60035),fileDirectory:p("file-directory",60035),symbolFolder:p("symbol-folder",60035),logoGithub:p("logo-github",60036),markGithub:p("mark-github",60036),github:p("github",60036),terminal:p("terminal",60037),console:p("console",60037),repl:p("repl",60037),zap:p("zap",60038),symbolEvent:p("symbol-event",60038),error:p("error",60039),stop:p("stop",60039),variable:p("variable",60040),symbolVariable:p("symbol-variable",60040),array:p("array",60042),symbolArray:p("symbol-array",60042),symbolModule:p("symbol-module",60043),symbolPackage:p("symbol-package",60043),symbolNamespace:p("symbol-namespace",60043),symbolObject:p("symbol-object",60043),symbolMethod:p("symbol-method",60044),symbolFunction:p("symbol-function",60044),symbolConstructor:p("symbol-constructor",60044),symbolBoolean:p("symbol-boolean",60047),symbolNull:p("symbol-null",60047),symbolNumeric:p("symbol-numeric",60048),symbolNumber:p("symbol-number",60048),symbolStructure:p("symbol-structure",60049),symbolStruct:p("symbol-struct",60049),symbolParameter:p("symbol-parameter",60050),symbolTypeParameter:p("symbol-type-parameter",60050),symbolKey:p("symbol-key",60051),symbolText:p("symbol-text",60051),symbolReference:p("symbol-reference",60052),goToFile:p("go-to-file",60052),symbolEnum:p("symbol-enum",60053),symbolValue:p("symbol-value",60053),symbolRuler:p("symbol-ruler",60054),symbolUnit:p("symbol-unit",60054),activateBreakpoints:p("activate-breakpoints",60055),archive:p("archive",60056),arrowBoth:p("arrow-both",60057),arrowDown:p("arrow-down",60058),arrowLeft:p("arrow-left",60059),arrowRight:p("arrow-right",60060),arrowSmallDown:p("arrow-small-down",60061),arrowSmallLeft:p("arrow-small-left",60062),arrowSmallRight:p("arrow-small-right",60063),arrowSmallUp:p("arrow-small-up",60064),arrowUp:p("arrow-up",60065),bell:p("bell",60066),bold:p("bold",60067),book:p("book",60068),bookmark:p("bookmark",60069),debugBreakpointConditionalUnverified:p("debug-breakpoint-conditional-unverified",60070),debugBreakpointConditional:p("debug-breakpoint-conditional",60071),debugBreakpointConditionalDisabled:p("debug-breakpoint-conditional-disabled",60071),debugBreakpointDataUnverified:p("debug-breakpoint-data-unverified",60072),debugBreakpointData:p("debug-breakpoint-data",60073),debugBreakpointDataDisabled:p("debug-breakpoint-data-disabled",60073),debugBreakpointLogUnverified:p("debug-breakpoint-log-unverified",60074),debugBreakpointLog:p("debug-breakpoint-log",60075),debugBreakpointLogDisabled:p("debug-breakpoint-log-disabled",60075),briefcase:p("briefcase",60076),broadcast:p("broadcast",60077),browser:p("browser",60078),bug:p("bug",60079),calendar:p("calendar",60080),caseSensitive:p("case-sensitive",60081),check:p("check",60082),checklist:p("checklist",60083),chevronDown:p("chevron-down",60084),chevronLeft:p("chevron-left",60085),chevronRight:p("chevron-right",60086),chevronUp:p("chevron-up",60087),chromeClose:p("chrome-close",60088),chromeMaximize:p("chrome-maximize",60089),chromeMinimize:p("chrome-minimize",60090),chromeRestore:p("chrome-restore",60091),circleOutline:p("circle-outline",60092),circle:p("circle",60092),debugBreakpointUnverified:p("debug-breakpoint-unverified",60092),terminalDecorationIncomplete:p("terminal-decoration-incomplete",60092),circleSlash:p("circle-slash",60093),circuitBoard:p("circuit-board",60094),clearAll:p("clear-all",60095),clippy:p("clippy",60096),closeAll:p("close-all",60097),cloudDownload:p("cloud-download",60098),cloudUpload:p("cloud-upload",60099),code:p("code",60100),collapseAll:p("collapse-all",60101),colorMode:p("color-mode",60102),commentDiscussion:p("comment-discussion",60103),creditCard:p("credit-card",60105),dash:p("dash",60108),dashboard:p("dashboard",60109),database:p("database",60110),debugContinue:p("debug-continue",60111),debugDisconnect:p("debug-disconnect",60112),debugPause:p("debug-pause",60113),debugRestart:p("debug-restart",60114),debugStart:p("debug-start",60115),debugStepInto:p("debug-step-into",60116),debugStepOut:p("debug-step-out",60117),debugStepOver:p("debug-step-over",60118),debugStop:p("debug-stop",60119),debug:p("debug",60120),deviceCameraVideo:p("device-camera-video",60121),deviceCamera:p("device-camera",60122),deviceMobile:p("device-mobile",60123),diffAdded:p("diff-added",60124),diffIgnored:p("diff-ignored",60125),diffModified:p("diff-modified",60126),diffRemoved:p("diff-removed",60127),diffRenamed:p("diff-renamed",60128),diff:p("diff",60129),diffSidebyside:p("diff-sidebyside",60129),discard:p("discard",60130),editorLayout:p("editor-layout",60131),emptyWindow:p("empty-window",60132),exclude:p("exclude",60133),extensions:p("extensions",60134),eyeClosed:p("eye-closed",60135),fileBinary:p("file-binary",60136),fileCode:p("file-code",60137),fileMedia:p("file-media",60138),filePdf:p("file-pdf",60139),fileSubmodule:p("file-submodule",60140),fileSymlinkDirectory:p("file-symlink-directory",60141),fileSymlinkFile:p("file-symlink-file",60142),fileZip:p("file-zip",60143),files:p("files",60144),filter:p("filter",60145),flame:p("flame",60146),foldDown:p("fold-down",60147),foldUp:p("fold-up",60148),fold:p("fold",60149),folderActive:p("folder-active",60150),folderOpened:p("folder-opened",60151),gear:p("gear",60152),gift:p("gift",60153),gistSecret:p("gist-secret",60154),gist:p("gist",60155),gitCommit:p("git-commit",60156),gitCompare:p("git-compare",60157),compareChanges:p("compare-changes",60157),gitMerge:p("git-merge",60158),githubAction:p("github-action",60159),githubAlt:p("github-alt",60160),globe:p("globe",60161),grabber:p("grabber",60162),graph:p("graph",60163),gripper:p("gripper",60164),heart:p("heart",60165),home:p("home",60166),horizontalRule:p("horizontal-rule",60167),hubot:p("hubot",60168),inbox:p("inbox",60169),issueReopened:p("issue-reopened",60171),issues:p("issues",60172),italic:p("italic",60173),jersey:p("jersey",60174),json:p("json",60175),bracket:p("bracket",60175),kebabVertical:p("kebab-vertical",60176),key:p("key",60177),law:p("law",60178),lightbulbAutofix:p("lightbulb-autofix",60179),linkExternal:p("link-external",60180),link:p("link",60181),listOrdered:p("list-ordered",60182),listUnordered:p("list-unordered",60183),liveShare:p("live-share",60184),loading:p("loading",60185),location:p("location",60186),mailRead:p("mail-read",60187),mail:p("mail",60188),markdown:p("markdown",60189),megaphone:p("megaphone",60190),mention:p("mention",60191),milestone:p("milestone",60192),gitPullRequestMilestone:p("git-pull-request-milestone",60192),mortarBoard:p("mortar-board",60193),move:p("move",60194),multipleWindows:p("multiple-windows",60195),mute:p("mute",60196),noNewline:p("no-newline",60197),note:p("note",60198),octoface:p("octoface",60199),openPreview:p("open-preview",60200),package:p("package",60201),paintcan:p("paintcan",60202),pin:p("pin",60203),play:p("play",60204),run:p("run",60204),plug:p("plug",60205),preserveCase:p("preserve-case",60206),preview:p("preview",60207),project:p("project",60208),pulse:p("pulse",60209),question:p("question",60210),quote:p("quote",60211),radioTower:p("radio-tower",60212),reactions:p("reactions",60213),references:p("references",60214),refresh:p("refresh",60215),regex:p("regex",60216),remoteExplorer:p("remote-explorer",60217),remote:p("remote",60218),remove:p("remove",60219),replaceAll:p("replace-all",60220),replace:p("replace",60221),repoClone:p("repo-clone",60222),repoForcePush:p("repo-force-push",60223),repoPull:p("repo-pull",60224),repoPush:p("repo-push",60225),report:p("report",60226),requestChanges:p("request-changes",60227),rocket:p("rocket",60228),rootFolderOpened:p("root-folder-opened",60229),rootFolder:p("root-folder",60230),rss:p("rss",60231),ruby:p("ruby",60232),saveAll:p("save-all",60233),saveAs:p("save-as",60234),save:p("save",60235),screenFull:p("screen-full",60236),screenNormal:p("screen-normal",60237),searchStop:p("search-stop",60238),server:p("server",60240),settingsGear:p("settings-gear",60241),settings:p("settings",60242),shield:p("shield",60243),smiley:p("smiley",60244),sortPrecedence:p("sort-precedence",60245),splitHorizontal:p("split-horizontal",60246),splitVertical:p("split-vertical",60247),squirrel:p("squirrel",60248),starFull:p("star-full",60249),starHalf:p("star-half",60250),symbolClass:p("symbol-class",60251),symbolColor:p("symbol-color",60252),symbolConstant:p("symbol-constant",60253),symbolEnumMember:p("symbol-enum-member",60254),symbolField:p("symbol-field",60255),symbolFile:p("symbol-file",60256),symbolInterface:p("symbol-interface",60257),symbolKeyword:p("symbol-keyword",60258),symbolMisc:p("symbol-misc",60259),symbolOperator:p("symbol-operator",60260),symbolProperty:p("symbol-property",60261),wrench:p("wrench",60261),wrenchSubaction:p("wrench-subaction",60261),symbolSnippet:p("symbol-snippet",60262),tasklist:p("tasklist",60263),telescope:p("telescope",60264),textSize:p("text-size",60265),threeBars:p("three-bars",60266),thumbsdown:p("thumbsdown",60267),thumbsup:p("thumbsup",60268),tools:p("tools",60269),triangleDown:p("triangle-down",60270),triangleLeft:p("triangle-left",60271),triangleRight:p("triangle-right",60272),triangleUp:p("triangle-up",60273),twitter:p("twitter",60274),unfold:p("unfold",60275),unlock:p("unlock",60276),unmute:p("unmute",60277),unverified:p("unverified",60278),verified:p("verified",60279),versions:p("versions",60280),vmActive:p("vm-active",60281),vmOutline:p("vm-outline",60282),vmRunning:p("vm-running",60283),watch:p("watch",60284),whitespace:p("whitespace",60285),wholeWord:p("whole-word",60286),window:p("window",60287),wordWrap:p("word-wrap",60288),zoomIn:p("zoom-in",60289),zoomOut:p("zoom-out",60290),listFilter:p("list-filter",60291),listFlat:p("list-flat",60292),listSelection:p("list-selection",60293),selection:p("selection",60293),listTree:p("list-tree",60294),debugBreakpointFunctionUnverified:p("debug-breakpoint-function-unverified",60295),debugBreakpointFunction:p("debug-breakpoint-function",60296),debugBreakpointFunctionDisabled:p("debug-breakpoint-function-disabled",60296),debugStackframeActive:p("debug-stackframe-active",60297),circleSmallFilled:p("circle-small-filled",60298),debugStackframeDot:p("debug-stackframe-dot",60298),terminalDecorationMark:p("terminal-decoration-mark",60298),debugStackframe:p("debug-stackframe",60299),debugStackframeFocused:p("debug-stackframe-focused",60299),debugBreakpointUnsupported:p("debug-breakpoint-unsupported",60300),symbolString:p("symbol-string",60301),debugReverseContinue:p("debug-reverse-continue",60302),debugStepBack:p("debug-step-back",60303),debugRestartFrame:p("debug-restart-frame",60304),debugAlt:p("debug-alt",60305),callIncoming:p("call-incoming",60306),callOutgoing:p("call-outgoing",60307),menu:p("menu",60308),expandAll:p("expand-all",60309),feedback:p("feedback",60310),gitPullRequestReviewer:p("git-pull-request-reviewer",60310),groupByRefType:p("group-by-ref-type",60311),ungroupByRefType:p("ungroup-by-ref-type",60312),account:p("account",60313),gitPullRequestAssignee:p("git-pull-request-assignee",60313),bellDot:p("bell-dot",60314),debugConsole:p("debug-console",60315),library:p("library",60316),output:p("output",60317),runAll:p("run-all",60318),syncIgnored:p("sync-ignored",60319),pinned:p("pinned",60320),githubInverted:p("github-inverted",60321),serverProcess:p("server-process",60322),serverEnvironment:p("server-environment",60323),pass:p("pass",60324),issueClosed:p("issue-closed",60324),stopCircle:p("stop-circle",60325),playCircle:p("play-circle",60326),record:p("record",60327),debugAltSmall:p("debug-alt-small",60328),vmConnect:p("vm-connect",60329),cloud:p("cloud",60330),merge:p("merge",60331),export:p("export",60332),graphLeft:p("graph-left",60333),magnet:p("magnet",60334),notebook:p("notebook",60335),redo:p("redo",60336),checkAll:p("check-all",60337),pinnedDirty:p("pinned-dirty",60338),passFilled:p("pass-filled",60339),circleLargeFilled:p("circle-large-filled",60340),circleLarge:p("circle-large",60341),circleLargeOutline:p("circle-large-outline",60341),combine:p("combine",60342),gather:p("gather",60342),table:p("table",60343),variableGroup:p("variable-group",60344),typeHierarchy:p("type-hierarchy",60345),typeHierarchySub:p("type-hierarchy-sub",60346),typeHierarchySuper:p("type-hierarchy-super",60347),gitPullRequestCreate:p("git-pull-request-create",60348),runAbove:p("run-above",60349),runBelow:p("run-below",60350),notebookTemplate:p("notebook-template",60351),debugRerun:p("debug-rerun",60352),workspaceTrusted:p("workspace-trusted",60353),workspaceUntrusted:p("workspace-untrusted",60354),workspaceUnknown:p("workspace-unknown",60355),terminalCmd:p("terminal-cmd",60356),terminalDebian:p("terminal-debian",60357),terminalLinux:p("terminal-linux",60358),terminalPowershell:p("terminal-powershell",60359),terminalTmux:p("terminal-tmux",60360),terminalUbuntu:p("terminal-ubuntu",60361),terminalBash:p("terminal-bash",60362),arrowSwap:p("arrow-swap",60363),copy:p("copy",60364),personAdd:p("person-add",60365),filterFilled:p("filter-filled",60366),wand:p("wand",60367),debugLineByLine:p("debug-line-by-line",60368),inspect:p("inspect",60369),layers:p("layers",60370),layersDot:p("layers-dot",60371),layersActive:p("layers-active",60372),compass:p("compass",60373),compassDot:p("compass-dot",60374),compassActive:p("compass-active",60375),azure:p("azure",60376),issueDraft:p("issue-draft",60377),gitPullRequestClosed:p("git-pull-request-closed",60378),gitPullRequestDraft:p("git-pull-request-draft",60379),debugAll:p("debug-all",60380),debugCoverage:p("debug-coverage",60381),runErrors:p("run-errors",60382),folderLibrary:p("folder-library",60383),debugContinueSmall:p("debug-continue-small",60384),beakerStop:p("beaker-stop",60385),graphLine:p("graph-line",60386),graphScatter:p("graph-scatter",60387),pieChart:p("pie-chart",60388),bracketDot:p("bracket-dot",60389),bracketError:p("bracket-error",60390),lockSmall:p("lock-small",60391),azureDevops:p("azure-devops",60392),verifiedFilled:p("verified-filled",60393),newline:p("newline",60394),layout:p("layout",60395),layoutActivitybarLeft:p("layout-activitybar-left",60396),layoutActivitybarRight:p("layout-activitybar-right",60397),layoutPanelLeft:p("layout-panel-left",60398),layoutPanelCenter:p("layout-panel-center",60399),layoutPanelJustify:p("layout-panel-justify",60400),layoutPanelRight:p("layout-panel-right",60401),layoutPanel:p("layout-panel",60402),layoutSidebarLeft:p("layout-sidebar-left",60403),layoutSidebarRight:p("layout-sidebar-right",60404),layoutStatusbar:p("layout-statusbar",60405),layoutMenubar:p("layout-menubar",60406),layoutCentered:p("layout-centered",60407),target:p("target",60408),indent:p("indent",60409),recordSmall:p("record-small",60410),errorSmall:p("error-small",60411),terminalDecorationError:p("terminal-decoration-error",60411),arrowCircleDown:p("arrow-circle-down",60412),arrowCircleLeft:p("arrow-circle-left",60413),arrowCircleRight:p("arrow-circle-right",60414),arrowCircleUp:p("arrow-circle-up",60415),layoutSidebarRightOff:p("layout-sidebar-right-off",60416),layoutPanelOff:p("layout-panel-off",60417),layoutSidebarLeftOff:p("layout-sidebar-left-off",60418),blank:p("blank",60419),heartFilled:p("heart-filled",60420),map:p("map",60421),mapHorizontal:p("map-horizontal",60421),foldHorizontal:p("fold-horizontal",60421),mapFilled:p("map-filled",60422),mapHorizontalFilled:p("map-horizontal-filled",60422),foldHorizontalFilled:p("fold-horizontal-filled",60422),circleSmall:p("circle-small",60423),bellSlash:p("bell-slash",60424),bellSlashDot:p("bell-slash-dot",60425),commentUnresolved:p("comment-unresolved",60426),gitPullRequestGoToChanges:p("git-pull-request-go-to-changes",60427),gitPullRequestNewChanges:p("git-pull-request-new-changes",60428),searchFuzzy:p("search-fuzzy",60429),commentDraft:p("comment-draft",60430),send:p("send",60431),sparkle:p("sparkle",60432),insert:p("insert",60433),mic:p("mic",60434),thumbsdownFilled:p("thumbsdown-filled",60435),thumbsupFilled:p("thumbsup-filled",60436),coffee:p("coffee",60437),snake:p("snake",60438),game:p("game",60439),vr:p("vr",60440),chip:p("chip",60441),piano:p("piano",60442),music:p("music",60443),micFilled:p("mic-filled",60444),repoFetch:p("repo-fetch",60445),copilot:p("copilot",60446),lightbulbSparkle:p("lightbulb-sparkle",60447),robot:p("robot",60448),sparkleFilled:p("sparkle-filled",60449),diffSingle:p("diff-single",60450),diffMultiple:p("diff-multiple",60451),surroundWith:p("surround-with",60452),share:p("share",60453),gitStash:p("git-stash",60454),gitStashApply:p("git-stash-apply",60455),gitStashPop:p("git-stash-pop",60456),vscode:p("vscode",60457),vscodeInsiders:p("vscode-insiders",60458),codeOss:p("code-oss",60459),runCoverage:p("run-coverage",60460),runAllCoverage:p("run-all-coverage",60461),coverage:p("coverage",60462),githubProject:p("github-project",60463),mapVertical:p("map-vertical",60464),foldVertical:p("fold-vertical",60464),mapVerticalFilled:p("map-vertical-filled",60465),foldVerticalFilled:p("fold-vertical-filled",60465),goToSearch:p("go-to-search",60466),percentage:p("percentage",60467),sortPercentage:p("sort-percentage",60467),attach:p("attach",60468),goToEditingSession:p("go-to-editing-session",60469),editSession:p("edit-session",60470),codeReview:p("code-review",60471),copilotWarning:p("copilot-warning",60472),python:p("python",60473),copilotLarge:p("copilot-large",60474),copilotWarningLarge:p("copilot-warning-large",60475),keyboardTab:p("keyboard-tab",60476),copilotBlocked:p("copilot-blocked",60477),copilotNotConnected:p("copilot-not-connected",60478),flag:p("flag",60479),lightbulbEmpty:p("lightbulb-empty",60480),symbolMethodArrow:p("symbol-method-arrow",60481),copilotUnavailable:p("copilot-unavailable",60482),repoPinned:p("repo-pinned",60483),keyboardTabAbove:p("keyboard-tab-above",60484),keyboardTabBelow:p("keyboard-tab-below",60485),gitPullRequestDone:p("git-pull-request-done",60486),mcp:p("mcp",60487),extensionsLarge:p("extensions-large",60488),layoutPanelDock:p("layout-panel-dock",60489),layoutSidebarLeftDock:p("layout-sidebar-left-dock",60490),layoutSidebarRightDock:p("layout-sidebar-right-dock",60491),copilotInProgress:p("copilot-in-progress",60492),copilotError:p("copilot-error",60493),copilotSuccess:p("copilot-success",60494),chatSparkle:p("chat-sparkle",60495),searchSparkle:p("search-sparkle",60496),editSparkle:p("edit-sparkle",60497),copilotSnooze:p("copilot-snooze",60498),sendToRemoteAgent:p("send-to-remote-agent",60499),commentDiscussionSparkle:p("comment-discussion-sparkle",60500),chatSparkleWarning:p("chat-sparkle-warning",60501),chatSparkleError:p("chat-sparkle-error",60502),collection:p("collection",60503),newCollection:p("new-collection",60504),thinking:p("thinking",60505),build:p("build",60506),commentDiscussionQuote:p("comment-discussion-quote",60507),cursor:p("cursor",60508),eraser:p("eraser",60509),fileText:p("file-text",60510),quotes:p("quotes",60512),rename:p("rename",60513),runWithDeps:p("run-with-deps",60514),debugConnected:p("debug-connected",60515),strikethrough:p("strikethrough",60516),openInProduct:p("open-in-product",60517),indexZero:p("index-zero",60518),agent:p("agent",60519),editCode:p("edit-code",60520),repoSelected:p("repo-selected",60521),skip:p("skip",60522),mergeInto:p("merge-into",60523),gitBranchChanges:p("git-branch-changes",60524),gitBranchStagedChanges:p("git-branch-staged-changes",60525),gitBranchConflicts:p("git-branch-conflicts",60526),gitBranch:p("git-branch",60527),gitBranchCreate:p("git-branch-create",60527),gitBranchDelete:p("git-branch-delete",60527),searchLarge:p("search-large",60528),terminalGitBash:p("terminal-git-bash",60529),windowActive:p("window-active",60530),forward:p("forward",60531),download:p("download",60532),clockface:p("clockface",60533),unarchive:p("unarchive",60534),sessionInProgress:p("session-in-progress",60535),collectionSmall:p("collection-small",60536),vmSmall:p("vm-small",60537),cloudSmall:p("cloud-small",60538),addSmall:p("add-small",60539),removeSmall:p("remove-small",60540),worktreeSmall:p("worktree-small",60541),worktree:p("worktree",60542),screenCut:p("screen-cut",60543),ask:p("ask",60544),openai:p("openai",60545),claude:p("claude",60546),openInWindow:p("open-in-window",60547),newSession:p("new-session",60548),terminalSecure:p("terminal-secure",60549),chatImport:p("chat-import",60550),chatExport:p("chat-export",60551),shareWindow:p("share-window",60552),circleSlashCompact:p("circle-slash-compact",60553),copilotCompact:p("copilot-compact",60554),folderOpenedCompact:p("folder-opened-compact",60555),folderCompact:p("folder-compact",60556),gearCompact:p("gear-compact",60557),gitBranchCompact:p("git-branch-compact",60558),libraryCompact:p("library-compact",60559),recordKeysCompact:p("record-keys-compact",60560),remoteCompact:p("remote-compact",60561),repoForkedCompact:p("repo-forked-compact",60562),repoCompact:p("repo-compact",60563),shieldCompact:p("shield-compact",60564),sparkleCompact:p("sparkle-compact",60565),symbolColorCompact:p("symbol-color-compact",60566),windowCompact:p("window-compact",60567),errorCompact:p("error-compact",60568),warningCompact:p("warning-compact",60569),passCompact:p("pass-compact",60570),important:p("important",60571),importantCompact:p("important-compact",60572),rocketCompact:p("rocket-compact",60573),unpin:p("unpin",60574),addCompact:p("add-compact",60575),attachCompact:p("attach-compact",60576),beakerCompact:p("beaker-compact",60577),checkCompact:p("check-compact",60578),checklistCompact:p("checklist-compact",60579),chevronDownCompact:p("chevron-down-compact",60580),chevronLeftCompact:p("chevron-left-compact",60581),chevronRightCompact:p("chevron-right-compact",60582),chevronUpCompact:p("chevron-up-compact",60583),circleFilledCompact:p("circle-filled-compact",60584),circleSmallFilledCompact:p("circle-small-filled-compact",60585),closeCompact:p("close-compact",60586),collapseAllCompact:p("collapse-all-compact",60587),commentCompact:p("comment-compact",60588),commentUnresolvedCompact:p("comment-unresolved-compact",60589),debugConnectedCompact:p("debug-connected-compact",60590),debugDisconnectCompact:p("debug-disconnect-compact",60591),editCompact:p("edit-compact",60592),fileMediaCompact:p("file-media-compact",60593),gitFetch:p("git-fetch",60594),lightbulbCompact:p("lightbulb-compact",60595),loadingCompact:p("loading-compact",60596),passFilledCompact:p("pass-filled-compact",60597),projectCompact:p("project-compact",60598),refreshCompact:p("refresh-compact",60599),searchCompact:p("search-compact",60600),sessionInProgressCompact:p("session-in-progress-compact",60601),syncCompact:p("sync-compact",60602),terminalCompact:p("terminal-compact",60603),vmPending:p("vm-pending",60604),worktreeCompact:p("worktree-compact",60605),developerTools:p("developer-tools",60606),cloudCompact:p("cloud-compact",60607)};var _E={dialogError:p("dialog-error","error"),dialogWarning:p("dialog-warning","warning"),dialogInfo:p("dialog-info","info"),dialogClose:p("dialog-close","close"),treeItemExpanded:p("tree-item-expanded","chevron-down"),treeFilterOnTypeOn:p("tree-filter-on-type-on","list-filter"),treeFilterOnTypeOff:p("tree-filter-on-type-off","list-selection"),treeFilterClear:p("tree-filter-clear","close"),treeItemLoading:p("tree-item-loading","loading"),menuSelection:p("menu-selection","check"),menuSubmenu:p("menu-submenu","chevron-right"),menuBarMore:p("menubar-more","more"),scrollbarButtonLeft:p("scrollbar-button-left","triangle-left"),scrollbarButtonRight:p("scrollbar-button-right","triangle-right"),scrollbarButtonUp:p("scrollbar-button-up","triangle-up"),scrollbarButtonDown:p("scrollbar-button-down","triangle-down"),toolBarMore:p("toolbar-more","more"),quickInputBack:p("quick-input-back","arrow-left"),dropDownButton:p("drop-down-button",60084),symbolCustomColor:p("symbol-customcolor",60252),exportIcon:p("export",60332),workspaceUnspecified:p("workspace-unspecified",60355),newLine:p("newline",60394),thumbsDownFilled:p("thumbsdown-filled",60435),thumbsUpFilled:p("thumbsup-filled",60436),gitFetch:p("git-fetch",60445),lightbulbSparkleAutofix:p("lightbulb-sparkle-autofix",60447),debugBreakpointPending:p("debug-breakpoint-pending",60377),chatImport:p("chat-import",60550),chatExport:p("chat-export",60551)},eu={...$I,..._E};var VI;(t=>{function r(e){return!!e&&typeof e=="object"&&typeof e.id=="string"}t.isThemeColor=r})(VI||={});var Za;(_=>{_.iconNameSegment="[A-Za-z0-9]+",_.iconNameExpression="[A-Za-z0-9-]+",_.iconModifierExpression="~[A-Za-z]+",_.iconNameCharacter="[A-Za-z0-9~-]";let i=new RegExp(`^(${_.iconNameExpression})(${_.iconModifierExpression})?$`);function o(b){let I=i.exec(b.id);if(!I)return o(eu.error);let[,R,P]=I,j=["codicon","codicon-"+R];return P&&j.push("codicon-modifier-"+P.substring(1)),j}_.asClassNameArray=o;function s(b){return o(b).join(" ")}_.asClassName=s;function a(b){return"."+o(b).join(".")}_.asCSSSelector=a;function l(b){return!!b&&typeof b=="object"&&typeof b.id=="string"&&(typeof b.color>"u"||VI.isThemeColor(b.color))}_.isThemeIcon=l;let c=new RegExp(`^\\$\\((${_.iconNameExpression}(?:${_.iconModifierExpression})?)\\)$`);function u(b){let I=c.exec(b);if(!I)return;let[,R]=I;return{id:R}}_.fromString=u;function d(b){return{id:b}}_.fromId=d;function f(b,I){let R=b.id,P=R.lastIndexOf("~");return P!==-1&&(R=R.substring(0,P)),I&&(R=`${R}~${I}`),{id:R}}_.modify=f;function m(b){let I=b.id.lastIndexOf("~");if(I!==-1)return b.id.substring(I+1)}_.getModifier=m;function h(b,I){return b.id===I.id&&b.color?.id===I.color?.id}_.isEqual=h;function v(b){return b?.id===eu.file.id}_.isFile=v;function S(b){return b?.id===eu.folder.id}_.isFolder=S})(Za||={});var am=new RegExp(`\\$\\(${Za.iconNameExpression}(?:${Za.iconModifierExpression})?\\)`,"g"),CE=new RegExp(`(\\\\)?${am.source}`,"g");function BI(r){return r.replace(CE,(t,e)=>e?t:`\\${t}`)}var nQ=new RegExp(`\\\\${am.source}`,"g");var iQ=new RegExp(`(\\s)?(\\\\)?${am.source}(\\s)?`,"g");var rQ=new RegExp(`\\$\\(${Za.iconNameCharacter}+\\)`,"g");var tu=class r{static lift(t){let e=new r(t.value,t);return e.uris=t.uris,e.baseUri=t.baseUri?y.revive(t.baseUri):void 0,e}constructor(t="",e=!1){if(this.value=t,typeof this.value!="string")throw Ip("value");typeof e=="boolean"?(this.isTrusted=e,this.supportThemeIcons=!1,this.supportHtml=!1,this.supportAlertSyntax=!1):(this.isTrusted=e.isTrusted??void 0,this.supportThemeIcons=e.supportThemeIcons??!1,this.supportHtml=e.supportHtml??!1,this.supportAlertSyntax=e.supportAlertSyntax??!1)}appendText(t,e=0){return this.value+=TE(this.supportThemeIcons?BI(t):t).replace(/([ \t]+)/g,(n,i)=>"&nbsp;".repeat(i.length)).replace(/\>/gm,"\\>").replace(/\n/g,e===1?`\\
`:`

`),this}appendMarkdown(t){return this.value+=t,this}appendCodeblock(t,e){return this.value+=`
${xE(e,t)}
`,this}appendLink(t,e,n){return this.value+="[",this.value+=this._escape(e,"]"),this.value+="](",this.value+=this._escape(String(t),")"),n&&(this.value+=` "${this._escape(this._escape(n,'"'),")")}"`),this.value+=")",this}_escape(t,e){let n=new RegExp(Bt(e),"g");return t.replace(n,(i,o)=>t.charAt(o-1)!=="\\"?`\\${i}`:i)}};function TE(r){return r.replace(/[\\`*_{}[\]()#+\-!~]/g,"\\$&")}function ns(r){return r.replace(/[\\\]]/g,"\\$&")}function xE(r,t){let e=r.match(/^`+/gm)?.reduce((i,o)=>i.length>o.length?i:o).length??0,n=e>=3?e+1:3;return[`${"`".repeat(n)}${t}`,r,`${"`".repeat(n)}`].join(`
`)}function He(r){let t=Math.max(0,...(r.match(/`+/g)??[]).map(o=>o.length)),e="`".repeat(t+1),i=r.startsWith("`")||r.endsWith("`")?` ${r} `:r;return`${e}${i}${e}`}var Dn=V("agentPluginManager");var nu=V("agentHostOTelService");function wE(r,t){let e=r.match(t?/^(?:cd(?: \/d)?|Set-Location(?: -Path)?) (?<dir>"[^"]*"|[^\s]+) ?(?:&&|;)\s+(?<suffix>.+)$/i:/^cd (?<dir>"[^"]*"|[^\s]+) &&\s+(?<suffix>.+)$/),n=e?.groups?.dir,i=e?.groups?.suffix;if(n&&i){let o=n;return o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1)),{directory:o,command:i}}}function wr(r,t,e){if(!e||!t)return!1;let n=r==="bash",i=r==="powershell";if(!n&&!i)return!1;let o=t.command;if(typeof o!="string")return!1;let s=wE(o,i);return!s||!RE(s.directory,e)?!1:(t.command=s.command,!0)}function RE(r,t){if(!r)return!1;let e=a=>a.replace(/[\\/]+$/,""),n=e(r),i=e(t.fsPath);if(!n||!i)return!1;let o,s;try{o=y.file(n),s=y.file(i)}catch{return!1}return Ve.isEqual(o,s)}function HI(r){let t=r.data,e=t.kind,n=EE(t.content);if(n)switch(e.type){case"shell_completed":case"shell_detached_completed":{let i=e.description,o=e.shellId;return{content:n,messageText:i?g(2022,null,i):o?g(2023,null,o):g(2021,null)}}case"agent_completed":return{content:n,messageText:g(2020,null)};default:return}}function EE(r){let t=r.trim();return(/^<system_notification>\s*([\s\S]*?)\s*<\/system_notification>$/.exec(t)?.[1]??t).trim()}var PE=["plan","compact","research","rubber-duck"];function kE(r){switch(r){case"plan":return g(2017,null);case"compact":return g(2016,null);case"research":return g(2018,null);case"rubber-duck":return g(2019,null)}}function zI(r){let t=/^\/(plan|compact|research|rubber-duck)(?:$|\s+([\s\S]*))/.exec(r);if(t)return{command:t[1],rest:(t[2]??"").trim()}}var iu=class{constructor(t,e){this.copilotcliId=t;this._sessionInfo=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(t,e){if(H.provider(t.channel)!==this.copilotcliId)return[];let n=Yd(t.text,t.offset);if(!n)return[];let i=H.id(t.channel),o=this._sessionInfo?.hasHistory(i)??!0,s=n.typed,a=[];for(let l of PE)s.length>0&&!l.startsWith(s)||l==="compact"&&!o||l==="rubber-duck"&&!process.env.RUBBER_DUCK_AGENT||a.push({insertText:l==="compact"?"/"+l:"/"+l+" ",rangeStart:0,rangeEnd:n.rangeEnd,attachment:{type:"simple",label:"/"+l,_meta:{command:l,description:kE(l)}}});return a}};function qI(r){if(!Array.isArray(r)||r.length!==2)return;let[t,e]=r;if(!(!Number.isInteger(t)||!Number.isInteger(e))&&!(t<0)&&!(e!==-1&&e<t))return{startLine:t,endLine:e}}var AE=[/^\s*\*\*\*\s+Update File:\s*(.+?)\s*$/,/^\s*\*\*\*\s+Add File:\s*(.+?)\s*$/,/^\s*\*\*\*\s+Delete File:\s*(.+?)\s*$/,/^\s*\*\*\*\s+Move to:\s*(.+?)\s*$/];function lm(r){let t=typeof r=="string"?r:r?.input??r?.patch;if(typeof t!="string"||t.length===0)return[];let e=new Set,n=[];for(let i of t.split(`
`))for(let o of AE){let s=o.exec(i);if(s){let a=s[1];a&&!e.has(a)&&(e.add(a),n.push(a));break}}return n}var DE=new Set(["edit","str_replace","insert","create","apply_patch","git_apply_patch"]),OE=new Set(["edit","str_replace","insert","create"]);function is(r,t){return DE.has(r)?!0:r==="str_replace_editor"?t!==void 0&&OE.has(t):!1}function ru(r){if(typeof r=="string"){try{r=JSON.parse(r)}catch{return lm(r)}if(typeof r=="string")return lm(r)}if(!r||typeof r!="object")return[];let t=r;if(typeof t.input=="string"||typeof t.patch=="string")return lm(t);let e=r;return typeof e.path=="string"?[e.path]:[]}var el=new Set(["bash","powershell"]),cm=new Set(["write_bash","write_powershell"]),KI=new Set(["read_bash","read_powershell"]),LE=new Set(["task"]),ME=new Set(["grep","rg","glob"]),NE=new Set(["report_intent","skill"]);function ou(r){return NE.has(r)}function su(r){return el.has(r)}function fn(r,t){return r.length>t?r.substring(0,t-3)+"...":r}function On(r){let t=y.file(r);return`[${pe(t)}](${t})`}function jI(r){return new tu().appendLink(r,fn(r,80)).value}function ue(r){return{markdown:r}}function Ln(r){switch(r){case"str_replace_editor":case"edit":case"str_replace":case"insert":return g(2096,null);case"create":return g(2094,null);case"view":return g(2110,null);case"bash":case"powershell":return g(2118,null);case"read_bash":case"read_powershell":return g(2112,null);case"write_bash":return g(2131,null);case"write_powershell":return g(2132,null);case"stop_bash":case"stop_powershell":case"bash_shutdown":case"powershell_shutdown":return g(2122,null);case"list_bash":case"list_powershell":return g(2103,null);case"grep":case"rg":case"glob":return g(2116,null);case"search_code_subagent":return g(2117,null);case"apply_patch":return g(2090,null);case"git_apply_patch":return g(2108,null);case"codeql_checker":return g(2092,null);case"code_review":return g(2093,null);case"reply_to_comment":return g(2113,null);case"think":return g(2126,null);case"report_intent":return g(2114,null);case"report_progress":return g(2115,null);case"web_search":return g(2129,null);case"web_fetch":return g(2099,null);case"update_todo":return g(2128,null);case"show_file":return g(2119,null);case"fetch_copilot_cli_documentation":return g(2098,null);case"propose_work":return g(2109,null);case"task_complete":return g(2125,null);case"ask_user":return g(2091,null);case"skill":return g(2101,null);case"task":return g(2124,null);case"list_agents":return g(2102,null);case"read_agent":return g(2111,null);case"exit_plan_mode":return g(2097,null);case"sql":return g(2121,null);case"lsp":return g(2104,null);case"create_pull_request":return g(2095,null);case"gh-advisory-database":return g(2100,null);case"store_memory":return g(2123,null);case"parallel_validation":return g(2107,null);case"write_agent":return g(2130,null);case"mcp_reload":return g(2105,null);case"mcp_validate":return g(2106,null);case"tool_search_tool_regex":return g(2127,null);default:return r}}function Hi(r,t,e){if(el.has(r)){let n=e;if(n?.command){let i=n.command.split(`
`)[0];return ue(g(2077,null,He(fn(i,80))))}return g(2076,null,t)}if(cm.has(r)){let n=e;if(n?.command){let i=n.command.split(`
`)[0];return ue(g(2089,null,He(fn(i,80))))}return g(2088,null)}if(KI.has(r))return g(2075,null);switch(r){case"view":{let n=e;if(n?.path){let i=On(n.path),o=qI(n.view_range);return o?o.endLine===-1?ue(g(2083,null,i,o.startLine)):o.endLine!==o.startLine?ue(g(2085,null,i,o.startLine,o.endLine)):ue(g(2084,null,i,o.startLine)):ue(g(2082,null,i))}return g(2081,null)}case"edit":{let n=e;return n?.path?ue(g(2065,null,On(n.path))):g(2064,null)}case"create":{let n=e;return n?.path?ue(g(2063,null,On(n.path))):g(2062,null)}case"grep":{let n=e;return n?.pattern?ue(g(2071,null,He(fn(n.pattern,80)))):g(2070,null)}case"rg":{let n=e;return n?.pattern?ue(g(2071,null,He(fn(n.pattern,80)))):g(2070,null)}case"glob":{let n=e;return n?.pattern?ue(g(2069,null,He(fn(n.pattern,80)))):g(2068,null)}case"apply_patch":case"git_apply_patch":{let n=ru(e);return n.length===1?ue(g(2073,null,On(n[0]))):n.length>1?ue(g(2074,null,n.map(On).join(", "))):g(2072,null)}case"sql":return e?.description||g(2080,null);case"web_fetch":{let n=e;return n?.url?ue(g(2086,null,jI(n.url))):g(2087,null)}case"exit_plan_mode":return g(2066,null);default:return g(2067,null,t)}}function au(r,t,e,n){if(!n)return g(2038,null,t);if(el.has(r)){let i=e;if(i?.command){let o=i.command.split(`
`)[0];return ue(g(2049,null,He(fn(o,80))))}return g(2048,null,t)}if(cm.has(r)){let i=e;if(i?.command){let o=i.command.split(`
`)[0];return ue(g(2061,null,He(fn(o,80))))}return g(2060,null)}if(KI.has(r))return g(2047,null);switch(r){case"view":{let i=e;if(i?.path){let o=On(i.path),s=qI(i.view_range);return s?s.endLine===-1?ue(g(2055,null,o,s.startLine)):s.endLine!==s.startLine?ue(g(2057,null,o,s.startLine,s.endLine)):ue(g(2056,null,o,s.startLine)):ue(g(2054,null,o))}return g(2053,null)}case"edit":{let i=e;return i?.path?ue(g(2036,null,On(i.path))):g(2035,null)}case"create":{let i=e;return i?.path?ue(g(2034,null,On(i.path))):g(2033,null)}case"grep":{let i=e;return i?.pattern?ue(g(2043,null,He(fn(i.pattern,80)))):g(2042,null)}case"rg":{let i=e;return i?.pattern?ue(g(2043,null,He(fn(i.pattern,80)))):g(2042,null)}case"glob":{let i=e;return i?.pattern?ue(g(2041,null,He(fn(i.pattern,80)))):g(2040,null)}case"apply_patch":case"git_apply_patch":{let i=ru(e);return i.length===1?ue(g(2045,null,On(i[0]))):i.length>1?ue(g(2046,null,i.map(On).join(", "))):g(2044,null)}case"sql":return e?.description||g(2052,null);case"web_fetch":{let i=e;return i?.url?ue(g(2058,null,jI(i.url))):g(2059,null)}case"exit_plan_mode":return g(2037,null);default:return g(2039,null,t)}}function UE(r,t){if(r)return`synth-skill-${r}`;let e=t.path??t.name;return`synth-skill-${ht(e).toString(16)}`}function lu(r,t){let e=UE(t,r),n=g(2120,null),i=ns(r.name),o=r.path?`[${i}](${y.file(r.path)})`:void 0,s=o?ue(g(2078,null,o)):g(2079,null,r.name),a=o?ue(g(2050,null,o)):g(2051,null,r.name);return{toolCallId:e,toolName:"skill",displayName:n,invocationMessage:s,pastTenseMessage:a}}function cu(r,t,e){if(!(!t&&!e)){if(el.has(r)||cm.has(r)){let n=t,i=n?.command??n?.args;return typeof i=="string"?i:typeof i=="object"&&i!==null&&Le(i,{command:!0})?i.command:e}switch(r){case"grep":return t?.pattern??e;case"rg":return t?.pattern??e;case"web_fetch":return t?.url??e;default:if(t)try{return JSON.stringify(t,null,2)}catch{return e}return e}}}function du(r){if(el.has(r))return"terminal";if(LE.has(r))return"subagent";if(ME.has(r))return"search"}function uu(r){if(!r)return{};let t=typeof r.agent_type=="string"&&r.agent_type.length>0?r.agent_type:void 0,e=typeof r.description=="string"&&r.description.length>0?r.description:void 0;return{agentName:t,description:e}}function pu(r){switch(r){case"powershell":case"write_powershell":case"read_powershell":return"powershell";default:return"shellscript"}}function pi(r){try{return JSON.stringify(r)}catch{return}}function Bi(r){return typeof r=="string"?r:void 0}function GI(r,t){let e=Bi(r.path)??Bi(r.fileName),n=Bi(r.fullCommandText),i=Bi(r.intention),o=Bi(r.serverName),s=Bi(r.toolName);switch(r.kind){case"shell":{let a=n?{command:n}:void 0;wr("bash",a,t);let l=typeof a?.command=="string"?a.command:n;return{confirmationTitle:g(2029,null),invocationMessage:i??Hi("bash",Ln("bash"),l?{command:l}:void 0),toolInput:l,permissionKind:"shell",permissionPath:e}}case"custom-tool":{let a=typeof r.args=="object"&&r.args!==null?r.args:void 0,l=Bi(r.toolName);if(a&&l&&su(l)&&typeof a.command=="string"){wr(l,a,t);let c=a.command;return{confirmationTitle:g(2029,null),invocationMessage:Hi(l,Ln(l),{command:c}),toolInput:c,permissionKind:"shell",permissionPath:e}}return{confirmationTitle:g(2025,null),invocationMessage:ue(g(2024,null,He(s??r.kind))),toolInput:pi(a||r),permissionKind:r.kind,permissionPath:e}}case"write":return{confirmationTitle:g(2032,null),invocationMessage:Hi("edit",Ln("edit"),e?{path:e}:void 0),toolInput:pi(e?{path:e}:r)??void 0,permissionKind:"write",permissionPath:e};case"mcp":{let a=s??g(2026,null);return{confirmationTitle:o?g(2027,null,o):g(2025,null),invocationMessage:o?`${o}: ${a}`:a,toolInput:pi({serverName:o,toolName:s})??void 0,permissionKind:"mcp",permissionPath:e}}case"read":return{confirmationTitle:g(2028,null),invocationMessage:i??Hi("view",Ln("view"),e?{path:e}:void 0),toolInput:pi(e?{path:e,intention:i}:r)??void 0,permissionKind:"read",permissionPath:e};case"url":{let a=Bi(r.url),l=a?URL.canParse(a)?new URL(a).href:a:void 0;return{confirmationTitle:g(2031,null),invocationMessage:ue(g(2030,null)),toolInput:l?JSON.stringify({url:l}):void 0,permissionKind:"url"}}default:return{confirmationTitle:g(2025,null),invocationMessage:ue(g(2024,null,He(s??r.kind))),toolInput:pi(r)??void 0,permissionKind:r.kind,permissionPath:e}}}function JI(r){try{return JSON.stringify(r)}catch{return}}function FE(r){if(r.type!=="user.message")return!1;let t=r.data?.source;return!!t&&t.toLowerCase()!=="user"}function fu(r,t,e){let n=e?.length?{text:t,origin:{kind:"user"},attachments:e}:{text:t,origin:{kind:"user"}};return{id:r,message:n,responseParts:[],pendingTools:new Map}}function QI(r,t,e,n){if(ou(r))return;let i=t!==void 0?JI(t):void 0,o;if(i)try{o=JSON.parse(i)}catch{}let a=(wr(r,o,n)?JI(o):void 0)??i,l=du(r),c=l==="subagent"?uu(o):void 0,u=Ln(r);return{toolName:r,displayName:u,invocationMessage:Hi(r,u,o),toolInput:cu(r,o,a),toolKind:l,language:l==="terminal"?pu(r):void 0,subagentAgentName:c?.agentName,subagentDescription:c?.description,parameters:o,parentToolCallId:e}}function gu(r,t){return{id:r.id,message:r.message,responseParts:r.responseParts,usage:void 0,state:t}}async function dm(r,t,e,n){let i=new Map,o=[],s=new Map;for(let b of e){if(b.type==="tool.execution_complete"){let I=b.data;s.set(I.toolCallId,I)}if(b.type==="tool.execution_start"){let I=b.data,R=QI(I.toolName,I.arguments,I.parentToolCallId,n);if(!R)continue;i.set(I.toolCallId,R);let P=Pe(R.parameters?.command)?R.parameters.command:void 0;is(I.toolName,P)&&o.push(I.toolCallId)}}let a;if(t&&o.length>0)try{let b=await t.getFileEdits(o);if(b.length>0){a=new Map;for(let I of b){let R=a.get(I.toolCallId);R||(R=[],a.set(I.toolCallId,R)),R.push(I)}}}catch{}let l=r.toString(),c=[],u=new Map,d=new Map,f=new Map,m,h=b=>{let I=u.get(b);if(!I||(u.delete(b),I.responseParts.length===0))return;let R=d.get(b)??[];R.push(gu(I,"complete")),d.set(b,R)},v=b=>{let I=u.get(b);return I||(I=fu(q(),""),u.set(b,I)),I},S=b=>b?v(b):m;for(let b of e)switch(b.type){case"user.message":{if(FE(b))continue;let I=b.data,R=I?.messageId??I?.interactionId??"",P=I?.content??"",j=WE(I?.attachments);if(I?.parentToolCallId){let E=v(I.parentToolCallId);P&&E.responseParts.push({kind:"markdown",id:q(),content:P}),j?.length&&(E.message={...E.message,attachments:j})}else{m&&c.push(gu(m,"cancelled"));let E=b.id??R;m=fu(E,P,j)}break}case"assistant.message":{let I=b.data,R=I?.messageId??I?.interactionId??"",P=I?.content??"",j=I?.reasoningText,E=!!I?.toolRequests&&I.toolRequests.length>0,M=b.id??R,O=S(I?.parentToolCallId)??(m=fu(M,""));j&&O.responseParts.push({kind:"reasoning",id:q(),content:j}),P&&O.responseParts.push({kind:"markdown",id:q(),content:P}),I?.toolRequests?.length&&_(O,I.toolRequests,I.parentToolCallId),!I?.parentToolCallId&&!E&&O===m&&(c.push(gu(m,"complete")),m=void 0);break}case"subagent.started":{let I=b.data;f.set(I.toolCallId,{agentName:I.agentName,agentDisplayName:I.agentDisplayName,agentDescription:I.agentDescription});break}case"tool.execution_start":break;case"tool.execution_complete":{let I=b.data,R=i.get(I.toolCallId);if(!R)continue;i.delete(I.toolCallId);let P=S(I.parentToolCallId);if(!P)continue;let j=YI(I,R,l,a,f.get(I.toolCallId));P.responseParts.push(j),!I.parentToolCallId&&f.has(I.toolCallId)&&h(I.toolCallId);break}case"skill.invoked":{let I=b,R=lu(I.data,I.id);(m??(m=fu(q(),""))).responseParts.push({kind:"toolCall",toolCall:{status:"completed",toolCallId:R.toolCallId,toolName:R.toolName,displayName:R.displayName,invocationMessage:R.invocationMessage,success:!0,pastTenseMessage:R.pastTenseMessage,confirmed:"not-needed"}});break}default:break}m&&(c.push(gu(m,"cancelled")),m=void 0);for(let b of[...u.keys()])h(b);return{turns:c,subagentTurnsByToolCallId:d};function _(b,I,R){for(let P of I){let j=s.get(P.toolCallId);if(j&&i.has(P.toolCallId))continue;let E=i.get(P.toolCallId)??QI(P.name,P.arguments,R,n);E&&b.responseParts.push(YI(j??{toolCallId:P.toolCallId,success:!0},E,l,a,f.get(P.toolCallId)))}}}function WE(r){if(!r?.length)return;let t=[];for(let e of r){let n=$E(e);n&&t.push(n)}return t.length>0?t:void 0}function $E(r){switch(r.type){case"file":return{type:"resource",uri:y.file(r.path).toString(),label:r.displayName||_e(r.path),displayKind:ic(r.path)?.startsWith("image/")?"image":"document"};case"directory":return{type:"resource",uri:y.file(r.path).toString(),label:r.displayName||_e(r.path),displayKind:"directory"};case"selection":return{type:"resource",uri:y.file(r.filePath).toString(),label:r.displayName,displayKind:"selection",selection:{range:r.selection}};case"blob":{if(r.mimeType.startsWith("text/plain"))return{type:"simple",label:r.displayName??"attachment",modelRepresentation:bn(r.data).toString()};let t=r.mimeType.startsWith("image/")?"image":void 0;return{type:"embeddedResource",label:r.displayName??"attachment",data:r.data,contentType:r.mimeType,displayKind:t}}default:return}}function YI(r,t,e,n,i){let o=r.error?.message??r.result?.content,s=[];o!==void 0&&s.push({type:"text",text:o});let a=n?.get(r.toolCallId);if(a)for(let c of a){let u=c.kind==="rename"&&c.originalPath?y.file(c.originalPath).toString():y.file(c.filePath).toString(),d=y.file(c.filePath).toString(),f=c.kind!=="create",m=c.kind!=="delete";s.push({type:"fileEdit",before:f?{uri:u,content:{uri:Ni(e,c.toolCallId,c.filePath,"before")}}:void 0,after:m?{uri:d,content:{uri:Ni(e,c.toolCallId,c.filePath,"after")}}:void 0,diff:c.addedLines!==void 0||c.removedLines!==void 0?{added:c.addedLines,removed:c.removedLines}:void 0})}i&&s.push({type:"subagent",resource:Co(e,r.toolCallId),title:i.agentDisplayName,agentName:i.agentName,description:i.agentDescription});let l={status:"completed",toolCallId:r.toolCallId,toolName:t.toolName,displayName:t.displayName,invocationMessage:t.invocationMessage,toolInput:t.toolInput,success:r.success,pastTenseMessage:au(t.toolName,t.displayName,t.parameters,r.success),content:s.length>0?s:void 0,error:r.error,confirmed:"not-needed",_meta:{toolKind:t.toolKind,language:t.language,subagentDescription:t.subagentDescription,subagentAgentName:t.subagentAgentName}};return{kind:"toolCall",toolCall:l}}var tl=class{constructor(t){this.type=1,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=t}},zi=class{constructor(t){this.type=2,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=t,this.entries=new Map}},mu=class extends T{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 zi("");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),i=[];return n.entries.forEach((o,s)=>i.push([s,o.type])),i}async readFile(e){let n=this._lookupAsFile(e,!1).data;if(n)return n;throw he("file not found","EntryNotFound")}readFileStream(e){let n=this._lookupAsFile(e,!1).data,i=Zn(o=>k.concat(o.map(s=>k.wrap(s))).buffer);return i.end(n),i}async writeFile(e,n,i){let o=pe(e),s=this._lookupParentDirectory(e),a=s.entries.get(o);if(a instanceof zi)throw he("file is directory","EntryIsADirectory");if(!a&&!i.create)throw he("file not found","EntryNotFound");if(a&&i.create&&!i.overwrite)throw he("file exists already","EntryExists");if(a||(a=new tl(o),s.entries.set(o,a),this._fireSoon({type:1,resource:e})),a.mtime=Date.now(),i.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 i=this._lookup(e,!0),o=ri(n),s=o&&!!n.append;if(i){if(i instanceof zi)throw he("file is directory","EntryIsADirectory")}else{if(!o)throw he("file not found","EntryNotFound");let l=pe(e),c=this._lookupParentDirectory(e);i=new tl(l),i.data=new Uint8Array(0),c.entries.set(l,i),this._fireSoon({type:1,resource:e})}i.data||(i.data=new Uint8Array(0));let a=this.memoryFdCounter++;return this.fdMemory.set(a,{file:i,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,i,o,s){let a=this.fdMemory.get(e);if(!a)throw he("No file with that descriptor open","Unavailable");if(!a.file.data)return Promise.resolve(0);let l=k.wrap(a.file.data).slice(n,n+s);return i.set(l.buffer,o),Promise.resolve(l.byteLength)}write(e,n,i,o,s){let a=this.fdMemory.get(e);if(!a)throw he("No file with that descriptor open","Unavailable");let l=k.wrap(i).slice(o,o+s);a.file.data??=new Uint8Array(0);let c=a.append?a.file.data.byteLength:n,u=c+l.byteLength;if(u>a.file.data.byteLength){let d=new Uint8Array(u);d.set(a.file.data,0),a.file.data=d}return a.file.data.set(l.buffer,c),Promise.resolve(l.byteLength)}async rename(e,n,i){if(!i.overwrite&&this._lookup(n,!0))throw he("file exists already","EntryExists");let o=this._lookup(e,!1),s=this._lookupParentDirectory(e),a=this._lookupParentDirectory(n),l=pe(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 i=vn(e),o=pe(e),s=this._lookupAsDirectory(i,!1);s.entries.delete(o)&&(s.mtime=Date.now(),s.size-=1,this._fireSoon({type:0,resource:i},{resource:e,type:2}))}async mkdir(e){if(this._lookup(e,!0))throw he("file exists already","EntryExists");let n=pe(e),i=vn(e),o=this._lookupAsDirectory(i,!1),s=new zi(n);o.entries.set(s.name,s),o.mtime=Date.now(),o.size+=1,this._fireSoon({type:0,resource:i},{type:1,resource:e})}_lookup(e,n){let i=e.path.split("/"),o=this.root;for(let s of i){if(!s)continue;let a;if(o instanceof zi&&(a=o.entries.get(s)),!a){if(n)return;throw he("file not found","EntryNotFound")}o=a}return o}_lookupAsDirectory(e,n){let i=this._lookup(e,n);if(i instanceof zi)return i;throw he("file not a directory","EntryNotADirectory")}_lookupAsFile(e,n){let i=this._lookup(e,n);if(i instanceof tl)return i;throw he("file is a directory","EntryIsADirectory")}_lookupParentDirectory(e){let n=vn(e);return this._lookupAsDirectory(n,!1)}watch(e,n){return T.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 XI="pending-edit-content";function ZI(r,t,e){return y.from({scheme:XI,authority:cn(k.fromString(r)).toString(),path:`/${encodeURIComponent(t)}/${cn(k.fromString(e))}`})}function e_(r){let t=new mu,e=r.registerProvider(XI,t);return{dispose(){e.dispose(),t.dispose()}}}var VE=".copilot",t_=B(VE,"session-state");function BE(r){switch(r){case"autopilot":return{label:g(2000,null),description:g(1999,null)};case"autopilot_fleet":return{label:g(2002,null),description:g(2001,null)};case"interactive":return{label:g(2007,null),description:g(2006,null)};case"exit_only":return{label:g(2004,null),description:g(2003,null)};default:return}}function n_(r){let t=Oe(r.toolArgs)?Reflect.get(r.toolArgs,"command"):void 0;return Pe(t)?t:void 0}function HE(r,t,e){let n={id:r,title:t.title??r,message:t.description??t.title??r,required:e};switch(t.type){case"boolean":return{...n,kind:"boolean",defaultValue:t.default};case"integer":case"number":return{...n,kind:t.type==="integer"?"integer":"number",min:t.minimum,max:t.maximum,defaultValue:t.default};case"array":{let i=Le(t.items,{enum:!0})?t.items.enum.map(o=>({id:o,label:o})):t.items.anyOf.map(o=>({id:o.const,label:o.title}));return{...n,kind:"multi-select",options:i,min:t.minItems,max:t.maxItems}}case"string":{if(Le(t,{enum:!0})){let i=t.enumNames,o=t.enum.map((s,a)=>({id:s,label:i?.[a]??s}));return{...n,kind:"single-select",options:o}}if(Le(t,{oneOf:!0})){let i=t.oneOf.map(o=>({id:o.const,label:o.title}));return{...n,kind:"single-select",options:i}}return{...n,kind:"text",format:t.format,min:t.minLength,max:t.maxLength,defaultValue:t.default}}}}function zE(r,t){if(!t||t.state==="skipped")return;let e=t.value;if(r.type==="boolean")return e.kind==="boolean"?e.value:e.kind==="text"?e.value==="true"?!0:e.value==="false"?!1:void 0:void 0;if(r.type==="number"||r.type==="integer"){if(e.kind==="number")return r.type==="integer"?Math.trunc(e.value):e.value;if(e.kind==="text"){if(e.value.trim()==="")return;let n=Number(e.value);return Number.isFinite(n)?r.type==="integer"?Math.trunc(n):n:void 0}return}if(r.type==="array")return e.kind==="selected-many"?[...e.value,...e.freeformValues??[]]:e.kind==="selected"?e.value?[e.value,...e.freeformValues??[]]:[...e.freeformValues??[]]:e.kind==="text"?e.value?[e.value]:[]:void 0;if(e.kind==="text"||e.kind==="selected")return e.value}function qE(r){let t=process.env.XDG_STATE_HOME;return t?B(t,t_):B(r,t_)}var KE=/^(?:\d{10,}-copilot-tool-output-[a-z0-9]{6}|copilot-tool-output-\d{10,}-[a-z0-9]{6})\.txt$/i;function jE(r,t){let e=Ht(y.file(r)),n=Ht(y.file(t)),i=Ht(y.joinPath(e,".."));if(!Ve.isEqual(i,n))return!1;let o=Math.max(r.lastIndexOf("/"),r.lastIndexOf("\\")),s=o>=0?r.substring(o+1):r;return KE.test(s)}var rs=class extends T{constructor(e,n,i,o,s,a,l,c){super();this._instantiationService=n;this._logService=i;this._fileService=s;this._environmentService=a;this._configurationService=l;this._telemetryService=c;this._activeToolCalls=new Map;this._parentToolCallIdsByAgentId=new Map;this._pendingPermissions=new Map;this._pendingUserInputs=new Map;this._pendingElicitations=new Map;this._pendingPlanReviews=new Map;this._turnId="";this._steeringMessagesInFlight=new Set;this._pendingSteeringFlips=new Map;this._pendingClientToolCalls=new Map;this._pendingEditContentUris=new Map;this._currentMarkdownPartIds=new Map;this._currentReasoningPartIds=new Map;this._hasReportedActivity=!1;this.sessionId=e.rawSessionId,this.sessionUri=e.sessionUri,this._onDidSessionProgress=e.onDidSessionProgress,this._wrapperFactory=e.wrapperFactory,this._shellManager=e.shellManager,this._workingDirectory=e.workingDirectory,this._customizationDirectory=e.customizationDirectory,this._appliedSnapshot=e.clientSnapshot??{clientId:"",tools:[],plugins:[]},this._clientToolNames=new Set(this._appliedSnapshot.tools.map(u=>u.name)),this._databaseRef=o.openDatabase(e.sessionUri),this._register(A(()=>this._databaseRef.dispose())),this._sessionDataDir=o.getSessionDataDir(e.sessionUri),this._editTracker=this._instantiationService.createInstance(Mi,e.sessionUri.toString(),this._databaseRef.object),this._register(A(()=>this._denyPendingPermissions())),this._register(A(()=>this._shellManager?.dispose())),this._register(A(()=>this._cancelPendingUserInputs())),this._register(A(()=>this._cancelPendingElicitations())),this._register(A(()=>this._cancelPendingPlanReviews())),this._register(A(()=>this._drainPendingSteeringFlips())),this._shellManager&&this._register(this._shellManager.onDidAssociateTerminal(({toolCallId:u,terminalUri:d,displayName:f})=>{let m=this._activeToolCalls.get(u);m&&(m.content.push({type:"terminal",resource:d,title:f}),this._emitAction({type:"session/toolCallContentChanged",turnId:this._turnId,toolCallId:u,content:m.content}))})),this._register(A(()=>this._cancelPendingClientToolCalls()))}_emitAction(e,n){this._onDidSessionProgress.fire({kind:"action",session:this.sessionUri,action:e,parentToolCallId:n})}_beginSteeringTurn(e){let n=this._turnId;n&&this._emitAction({type:"session/turnComplete",turnId:n});let i=q();return this._emitAction({type:"session/turnStarted",turnId:i,message:e.message,queuedMessageId:e.id}),this.resetTurnState(i),i}_drainPendingSteeringFlips(){if(this._pendingSteeringFlips.size===0)return;let e=[...this._pendingSteeringFlips.keys()];this._pendingSteeringFlips.clear();for(let n of e)this._onDidSessionProgress.fire({kind:"steering_consumed",session:this.sessionUri,id:n})}_takeMatchingPendingSteering(e){if(this._pendingSteeringFlips.size!==0){for(let[n,i]of this._pendingSteeringFlips)if(i.message.text===e)return this._pendingSteeringFlips.delete(n),i}}_parentToolCallIdForSubagentEvent(e){return e.agentId?this._parentToolCallIdsByAgentId.get(e.agentId):void 0}_shouldDropUnmappedSubagentEvent(e,n){return!this._parentToolCallIdForSubagentEvent(e)&&e.agentId?(this._logService.warn(`[Copilot:${this.sessionId}] Dropping ${n} for unknown subagent agentId=${e.agentId}`),!0):!1}resetTurnState(e){this._turnId=e,this._currentMarkdownPartIds.clear(),this._currentReasoningPartIds.clear(),this._parentToolCallIdsByAgentId.clear()}_completeActiveTurn(){if(!this._turnId)return;let e=this._turnId;this._emitAction({type:"session/turnComplete",turnId:e}),this._turnId="",this._currentMarkdownPartIds.clear(),this._currentReasoningPartIds.clear(),this._parentToolCallIdsByAgentId.clear()}_getEditFilePaths(e){return ru(e).map(n=>this._resolveEditFilePath(n))}_resolveEditFilePath(e){return Yt(e)||!this._workingDirectory||this._workingDirectory.scheme!==oe.file?e:B(this._workingDirectory.fsPath,e)}_sendToolInvokedTelemetry(e,n,i){let o;e?o="success":n==="rejected"||n==="denied"||n==="cancelled"?o="userCancelled":o="error";let s=this._clientToolNames.has(i.toolName),a=i.mcpServerName?"mcp":s?"client":"agentHost",l=Date.now()-i.startTimeMs;this._telemetryService.publicLog2("languageModelToolInvoked",{result:o,chatSessionId:this.sessionUri.toString(),toolId:i.toolName,toolExtensionId:void 0,toolSourceKind:a,invocationTimeMs:l})}emitInitialMarkdown(e){this._emitMarkdownDelta(e)}_emitMarkdownDelta(e,n){let i=n??"",o=this._currentMarkdownPartIds.get(i);if(!o){o=q(),this._currentMarkdownPartIds.set(i,o),this._emitAction({type:"session/responsePart",turnId:this._turnId,part:{kind:"markdown",id:o,content:e}},n);return}this._emitAction({type:"session/delta",turnId:this._turnId,partId:o,content:e},n)}_emitReasoningDelta(e,n){let i=n??"",o=this._currentReasoningPartIds.get(i);if(!o){o=q(),this._currentReasoningPartIds.set(i,o),this._emitAction({type:"session/responsePart",turnId:this._turnId,part:{kind:"reasoning",id:o,content:e}},n);return}this._emitAction({type:"session/reasoning",turnId:this._turnId,partId:o,content:e},n)}get appliedSnapshot(){return this._appliedSnapshot}get customizationDirectory(){return this._customizationDirectory}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(i,{toolCallId:o})=>{try{let s=this._pendingClientToolCalls.get(o);s||(s=new fe,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 i=this._pendingClientToolCalls.get(e);i||(i=new fe,this._pendingClientToolCalls.set(e,i));let o=n.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
`)??"",s=n.content?.filter(a=>a.type==="embeddedResource").map(a=>({data:a.data,mimeType:a.contentType,type:/^image(\/|$)/.test(a.contentType)?"image":"resource"}));n.success?i.complete({textResultForLlm:o,resultType:"success",binaryResultsForLlm:s?.length?s:void 0}):i.complete({textResultForLlm:o||n.error?.message||"Tool call failed",resultType:"failure",error:n.error?.message,binaryResultsForLlm:s?.length?s:void 0})}async initializeSession(){let e=await this._wrapperFactory({onPermissionRequest:n=>this.handlePermissionRequest(n),onUserInputRequest:(n,i)=>this.handleUserInputRequest(n,i),onElicitationRequest:n=>this.handleElicitationRequest(n),requestUnsandboxedCommandConfirmation:n=>this.requestUnsandboxedCommandConfirmation(n),clientTools:this.createClientSdkTools(),hooks:{onPreToolUse:n=>this._handlePreToolUse(n),onPostToolUse:n=>this._handlePostToolUse(n)}});if(this._store.isDisposed)throw e.dispose(),new re;this._wrapper=this._register(e),this._subscribeToEvents(),this._subscribeForLogging()}async send(e,n,i,o){i&&(this._turnId=i),this._logService.info(`[Copilot:${this.sessionId}] sendMessage called: "${e.substring(0,100)}${e.length>100?"...":""}" (${n?.length??0} attachments)`);let s=zI(e);if(s?.command==="compact"){try{await this._wrapper.session.rpc.history.compact()}catch(l){throw this._logService.error(l,`[Copilot:${this.sessionId}] rpc.history.compact failed`),l}return}if(s?.command==="research"&&(e=s.rest?`/research ${s.rest}`:"/research"),s?.command==="plan"&&(o="plan",e=s.rest),s?.command==="rubber-duck")if(!process.env.RUBBER_DUCK_AGENT)e=s.rest;else{let l=s.rest;e=l?`The user has requested a rubber duck review via the /rubber-duck command. Use the task tool with agent_type: "rubber-duck" to get an independent critique of your current approach, plan, or recent work. Summarize the relevant context for the rubber duck agent so it has what it needs to evaluate it.

Additional instructions: ${l}`:'The user has requested a rubber duck review via the /rubber-duck command. Use the task tool with agent_type: "rubber-duck" to get an independent critique of your current approach, plan, or recent work. Summarize the relevant context for the rubber duck agent so it has what it needs to evaluate it.'}let a=n?.length?(await Promise.all(n.map(l=>this._toSdkAttachment(l)))).filter(yi):void 0;a?.length&&this._logService.trace(`[Copilot:${this.sessionId}] Attachments: ${JSON.stringify(a.map(l=>({type:l.type})))}`),await this.applyMode(o),await this._wrapper.session.send({prompt:e,attachments:a?.length?a:void 0}),this._logService.info(`[Copilot:${this.sessionId}] session.send() returned`)}async _toSdkAttachment(e){if(e.type==="simple")return e.modelRepresentation?{type:"blob",data:Xr(k.fromString(e.modelRepresentation)),mimeType:"text/plain",displayName:e.label}:void 0;if(e.type==="embeddedResource")return{type:"blob",data:e.data,mimeType:e.contentType,displayName:e.label};if(e.type!=="resource")return;let n=y.parse(e.uri),i=n.scheme==="file"?n.fsPath:n.toString(),o=e.label??i;if(e.displayKind==="selection"&&e.selection)try{let a=await this._readSelectedText(n,e.selection.range);return{type:"selection",filePath:i,displayName:o,text:a,selection:e.selection.range}}catch(a){return this._logService.warn(`[Copilot:${this.sessionId}] Failed to read selected text for ${n.toString()}: ${a}`),{type:"file",path:i,displayName:o}}return e.displayKind==="selection"?{type:"file",path:i,displayName:o}:{type:e.displayKind==="directory"?"directory":"file",path:i,displayName:o}}async _readSelectedText(e,n){let o=(await this._fileService.readFile(e)).value.toString(),s=ly(o),a=this._getOffsetAt(s,n.start),l=this._getOffsetAt(s,n.end);return o.substring(a,Math.max(a,l))}_getOffsetAt(e,n){let i=Math.max(0,Math.min(n.line,e.length-1)),o=0;for(let a=0;a<i;a++)o+=e[a].length;let s=e[i].replace(/\r\n|\r|\n$/,"");return o+Math.max(0,Math.min(n.character,s.length))}async applyMode(e){if(!(!e||e===this._lastAppliedMode))try{await this._wrapper.session.rpc.mode.set({mode:e}),this._lastAppliedMode=e,this._logService.info(`[Copilot:${this.sessionId}] rpc.mode.set succeeded: mode=${e}`)}catch(n){this._logService.error(n,`[Copilot:${this.sessionId}] rpc.mode.set failed: mode=${e}`)}}async sendSteering(e){if(!(this._steeringMessagesInFlight.has(e.id)||this._pendingSteeringFlips.has(e.id))){this._steeringMessagesInFlight.add(e.id),this._logService.info(`[Copilot:${this.sessionId}] Sending steering message: "${e.message.text.substring(0,100)}"`);try{await this._wrapper.session.send({prompt:e.message.text,mode:"immediate"}),this._pendingSteeringFlips.set(e.id,e)}catch(n){this._logService.error(`[Copilot:${this.sessionId}] Steering message failed`,n)}finally{this._steeringMessagesInFlight.delete(e.id)}}}async getMessages(){let e=await this._wrapper.session.getEvents(),n;try{n=this._databaseRef.object}catch{}return(await dm(this.sessionUri,n,e,this._workingDirectory)).turns}async getSubagentMessages(e){let n=await this._wrapper.session.getEvents(),i;try{i=this._databaseRef.object}catch{}return(await dm(this.sessionUri,i,n,this._workingDirectory)).subagentTurnsByToolCallId.get(e)??[]}async abort(){this._logService.info(`[Copilot:${this.sessionId}] Aborting session...`),this._denyPendingPermissions(),this._drainPendingSteeringFlips(),await this._wrapper.session.abort()}async destroySession(){await this._wrapper.session.disconnect()}async setModel(e,n){this._logService.info(`[Copilot:${this.sessionId}] Changing model to: ${e}`),await this._wrapper.session.setModel(e,{reasoningEffort:n})}async setAgent(e){if(e){let n=e;this._logService.info(`[Copilot:${this.sessionId}] Selecting custom agent: ${n}`);try{await this._wrapper.session.rpc.agent.select({name:n})}catch(i){throw this._logService.error(i,`[Copilot:${this.sessionId}] rpc.agent.select failed: name=${n}`),i}}else{this._logService.info(`[Copilot:${this.sessionId}] Clearing custom agent selection`);try{await this._wrapper.session.rpc.agent.deselect()}catch(n){throw this._logService.error(n,`[Copilot:${this.sessionId}] rpc.agent.deselect failed`),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:"reject"};let i=this._getInternalSessionResourcePath(e);if(i)return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving internal session resource ${i}`),{kind:"approve-once"};if(e.kind==="read"&&typeof e.path=="string"&&this._isSessionAttachmentPath(e.path))return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving session attachment ${e.path}`),{kind:"approve-once"};if(e.kind==="read"&&typeof e.path=="string"&&jE(e.path,this._environmentService.tmpDir.fsPath))return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving Copilot SDK tool-output temp file ${e.path}`),{kind:"approve-once"};let o=e.kind==="shell"||e.kind==="custom-tool"&&typeof e.toolName=="string"&&su(e.toolName);this._logService.info(`[Copilot:${this.sessionId}] Requesting confirmation for tool call: ${n}`);let s=new fe;if(this._pendingPermissions.set(n,s),o&&await this._isShellSandboxedByDefault())return this._pendingPermissions.get(n)===s?(this._pendingPermissions.delete(n),this._logService.info(`[Copilot:${this.sessionId}] Auto-approving sandboxed shell command for tool call ${n}`),{kind:"approve-once"}):{kind:"reject"};let{confirmationTitle:a,invocationMessage:l,toolInput:c,permissionKind:u,permissionPath:d}=GI(e,this._workingDirectory),f=await this._buildEditsForPermission(e,n);if(!this._pendingPermissions.has(n))return{kind:"reject"};let m=e.toolName??e.kind,h=this._activeToolCalls.get(n)?.parentToolCallId;this._onDidSessionProgress.fire({kind:"pending_confirmation",session:this.sessionUri,state:{status:"pending-confirmation",toolCallId:n,toolName:m,displayName:Ln(m),invocationMessage:l,toolInput:c,confirmationTitle:a,edits:f},permissionKind:u,permissionPath:d,parentToolCallId:h});let v=await s.p;return this._logService.info(`[Copilot:${this.sessionId}] Permission response: toolCallId=${n}, approved=${v}`),{kind:v?"approve-once":"reject"}}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 i=Ht(y.file(qE(this._environmentService.userHome.fsPath))),o=Ht(y.joinPath(i,this.sessionId));if(!Ve.isEqualOrParent(o,i))return;let s=Ht(y.file(n));return Ve.isEqualOrParent(s,o)?n:void 0}_isSessionAttachmentPath(e){let n=Ht(y.joinPath(this._sessionDataDir,Ec)),i=Ht(y.file(e));return Ve.isEqualOrParent(i,n)}async _isShellSandboxedByDefault(){return!this._shellManager||this._configurationService.getRootValue(Rn,"disableCustomTerminalTool")===!0?!1:this._shellManager.getOrCreateSandboxEngine().isEnabled()}async _buildEditsForPermission(e,n){if(e.kind!=="write")return;let i=typeof e.fileName=="string"?e.fileName:void 0,o=typeof e.newFileContents=="string"?e.newFileContents:void 0;if(!i||o===void 0)return;let s=y.file(i),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: ${i}`,f)}let c=ZI(this.sessionUri.toString(),n,i);try{await this._fileService.writeFile(c,k.fromString(o))}catch(f){this._logService.warn(`[Copilot:${this.sessionId}] Failed to write pending edit content for ${i}`,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 u=typeof e.diff=="string"?JE(e.diff):void 0;return{items:[{...l?{before:{uri:a,content:{uri:a}}}:{},after:{uri:a,content:{uri:c.toString()}},...u?{diff:u}:{}}]}}respondToPermissionRequest(e,n){let i=this._pendingPermissions.get(e);return i?(this._pendingPermissions.delete(e),this._deletePendingEditContent(e),i.complete(n),!0):!1}async requestUnsandboxedCommandConfirmation(e){let n=new fe;this._pendingPermissions.set(e.toolCallId,n);let i=Ln(e.toolName),o=e.blockedDomains?.length?e.blockedDomains.join(", "):void 0,s=o?g(2014,null,o):g(2015,null),a=e.reason?g(2013,null,e.reason):o?g(2011,null,o):g(2012,null);return this._onDidSessionProgress.fire({kind:"pending_confirmation",session:this.sessionUri,state:{status:"pending-confirmation",toolCallId:e.toolCallId,toolName:e.toolName,displayName:i,invocationMessage:a,toolInput:e.command,confirmationTitle:s},parentToolCallId:this._activeToolCalls.get(e.toolCallId)?.parentToolCallId}),n.p}async handleUserInputRequest(e,n){if(this._configurationService.getEffectiveValue(this.sessionUri.toString(),Mt,"autoApprove")==="autopilot")return{answer:"The user is not available to answer your question. Choose a pragmatic option best aligned with the context of the request.",wasFreeform:!0};let o=e.question.substring(0,100);try{let s=q(),a=q();this._logService.info(`[Copilot:${this.sessionId}] User input request: requestId=${s}, question="${o}"`);let l=new fe;this._pendingUserInputs.set(s,{deferred:l,questionId:a});let c={id:s,questions:[e.choices&&e.choices.length>0?{kind:"single-select",id:a,message:e.question,required:!0,options:e.choices.map(m=>({id:m,label:m})),allowFreeformInput:e.allowFreeform??!0}:{kind:"text",id:a,message:e.question,required:!0}]};this._emitAction({type:"session/inputRequested",request:c});let u=await l.p;if(this._logService.info(`[Copilot:${this.sessionId}] User input response: requestId=${s}, response=${u.response}`),u.response!=="accept"||!u.answers)return{answer:"",wasFreeform:!0};let d=u.answers[a];if(!d||d.state==="skipped")return{answer:"",wasFreeform:!0};let{value:f}=d;if(f.kind==="text")return{answer:f.value,wasFreeform:!0};if(f.kind==="selected"){let m=!e.choices?.includes(f.value);return{answer:f.value,wasFreeform:m}}return{answer:"",wasFreeform:!0}}catch(s){throw this._logService.error(s,`[Copilot:${this.sessionId}] Failed to handle user input request: question="${o}"`),s}}async handleElicitationRequest(e){if(this._configurationService.getEffectiveValue(this.sessionUri.toString(),Mt,"autoApprove")==="autopilot")return{action:"cancel"};let i=e.message.substring(0,100);try{let o=q();this._logService.info(`[Copilot:${this.sessionId}] Elicitation request: requestId=${o}, mode=${e.mode??"form"}, source=${e.elicitationSource??"<unknown>"}, message="${i}"`);let s=e.mode==="url"?void 0:e.requestedSchema,a=new Set(s?.required??[]),l=s?Object.entries(s.properties).map(([h,v])=>HE(h,v,a.has(h))):void 0,c=new fe;this._pendingElicitations.set(o,{deferred:c,schema:s});let u={id:o,message:e.message,...e.mode==="url"&&e.url?{url:e.url}:{},...l&&l.length>0?{questions:l}:{}};this._emitAction({type:"session/inputRequested",request:u});let d=await c.p;if(this._logService.info(`[Copilot:${this.sessionId}] Elicitation response: requestId=${o}, response=${d.response}`),d.response==="decline")return{action:"decline"};if(d.response!=="accept")return{action:"cancel"};let f=d.answers??{};if(!s){let h=f.answer;return h&&h.state!=="skipped"&&h.value.kind==="text"?{action:"accept",content:{answer:h.value.value}}:{action:"accept"}}let m={};for(let[h,v]of Object.entries(s.properties)){let S=zE(v,f[h]);S!==void 0&&(m[h]=S)}return{action:"accept",content:m}}catch(o){throw this._logService.error(o,`[Copilot:${this.sessionId}] Failed to handle elicitation request: message="${i}"`),o}}respondToUserInputRequest(e,n,i){let o=this._pendingPlanReviews.get(e);if(o)return this._pendingPlanReviews.delete(e),o.deferred.complete(this._resolveExitPlanMode(o,n,i)),!0;let s=this._pendingElicitations.get(e);if(s)return this._pendingElicitations.delete(e),s.deferred.complete({response:n,answers:i}),!0;let a=this._pendingUserInputs.get(e);return a?(this._pendingUserInputs.delete(e),a.deferred.complete({response:n,answers:i}),!0):!1}_resolveExitPlanMode(e,n,i){if(n!=="accept")return{approved:!1};let o=i?.[e.questionId];if(!o||o.state==="skipped")return{approved:!1};let s=o.value,a,l;if(s.kind==="selected")a=s.value,l=s.freeformValues?.find(f=>f.trim().length>0)?.trim();else if(s.kind==="text")l=s.value.trim()||void 0;else return{approved:!1};let c=a&&e.actions.includes(a)?a:e.actions.includes(e.recommendedAction)?e.recommendedAction:void 0;return l?{approved:!1,feedback:l,...c?{selectedAction:c}:{}}:c?{approved:!0,selectedAction:c,...c==="autopilot"||c==="autopilot_fleet"?{autoApproveEdits:!0}:{}}:{approved:!1}}async _handlePreToolUse(e){try{if(is(e.toolName,n_(e))){let n=this._getEditFilePaths(e.toolArgs);await Promise.all(n.map(i=>this._editTracker.trackEditStart(i)))}}catch(n){throw this._logService.error(n,`[Copilot:${this.sessionId}] Failed in onPreToolUse: tool=${e.toolName}`),n}}async _handlePostToolUse(e){try{if(is(e.toolName,n_(e))){let n=this._getEditFilePaths(e.toolArgs);await Promise.all(n.map(i=>this._editTracker.completeEdit(i)))}}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;this._register(e.onSystemNotification(i=>{let o=HI(i);if(!o){this._logService.trace(`[Copilot:${n}] Ignoring system.notification kind=${i.data.kind.type}`);return}if(this._logService.info(`[Copilot:${n}] System notification received: kind=${i.data.kind.type}`),this._turnId){this._emitAction({type:"session/responsePart",turnId:this._turnId,part:{kind:"systemNotification",content:o.content}});return}let s=q();this.resetTurnState(s),this._emitAction({type:"session/turnStarted",turnId:s,message:{text:o.messageText,origin:{kind:"systemNotification"}}})})),this._register(e.onUserMessage(i=>{if(i.data.source&&i.data.source.toLowerCase()!=="user")return;let o=this._takeMatchingPendingSteering(i.data.content);o&&this._beginSteeringTurn(o),this._turnId&&this._databaseRef.object.setTurnEventId(this._turnId,i.id)})),this._register(e.onMessageDelta(i=>{this._logService.trace(`[Copilot:${n}] delta: ${i.data.deltaContent}`),!this._shouldDropUnmappedSubagentEvent(i,"assistant.message_delta")&&this._emitMarkdownDelta(i.data.deltaContent,this._parentToolCallIdForSubagentEvent(i))})),this._register(e.onMessage(i=>{if(this._logService.info(`[Copilot:${n}] Full message received: ${i.data.content.length} chars`),!i.data.content||this._shouldDropUnmappedSubagentEvent(i,"assistant.message"))return;let o=this._parentToolCallIdForSubagentEvent(i),s=o??"";if(this._currentMarkdownPartIds.has(s))return;let a=q();this._currentMarkdownPartIds.set(s,a),this._emitAction({type:"session/responsePart",turnId:this._turnId,part:{kind:"markdown",id:a,content:i.data.content}},o)})),this._register(e.onToolStart(i=>{if(ou(i.data.toolName)){if(this._logService.trace(`[Copilot:${n}] Tool started (hidden): ${i.data.toolName}`),i.data.toolName==="report_intent"){let m=i.data.arguments?.intent;typeof m=="string"&&m.length>0&&(this._hasReportedActivity=!0,this._emitAction({type:"session/activityChanged",activity:m}))}return}this._logService.info(`[Copilot:${n}] Tool started: ${i.data.toolName}`);let o=i.data.arguments!==void 0?pi(i.data.arguments):void 0,s;if(o)try{s=JSON.parse(o)}catch{}wr(i.data.toolName,s,this._workingDirectory)&&(o=pi(s));let a=Ln(i.data.toolName);if(this._shouldDropUnmappedSubagentEvent(i,"tool.execution_start"))return;let l=this._parentToolCallIdForSubagentEvent(i);this._activeToolCalls.set(i.data.toolCallId,{toolName:i.data.toolName,displayName:a,parameters:s,content:[],parentToolCallId:l,startTimeMs:Date.now(),mcpServerName:i.data.mcpServerName});let c=du(i.data.toolName),u=c==="subagent"?uu(s):void 0,d=this._clientToolNames.has(i.data.toolName)?this._appliedSnapshot.clientId:void 0;this._currentMarkdownPartIds.delete(l??""),this._currentReasoningPartIds.delete(l??"");let f={toolKind:c,language:c==="terminal"?pu(i.data.toolName):void 0};u?.description&&(f.subagentDescription=u.description),u?.agentName&&(f.subagentAgentName=u.agentName),o!==void 0&&(f.toolArguments=o),i.data.mcpServerName&&(f.mcpServerName=i.data.mcpServerName),i.data.mcpToolName&&(f.mcpToolName=i.data.mcpToolName),this._emitAction({type:"session/toolCallStart",turnId:this._turnId,toolCallId:i.data.toolCallId,toolName:i.data.toolName,displayName:a,toolClientId:d,_meta:f},l),!d&&this._emitAction({type:"session/toolCallReady",turnId:this._turnId,toolCallId:i.data.toolCallId,invocationMessage:Hi(i.data.toolName,a,s),toolInput:cu(i.data.toolName,s,o),confirmed:"not-needed"},l)})),this._register(e.onToolComplete(async i=>{let o=this._activeToolCalls.get(i.data.toolCallId);if(!o)return;let s=o.parentToolCallId??this._parentToolCallIdForSubagentEvent(i);if(!s&&i.agentId){this._logService.warn(`[Copilot:${this.sessionId}] Dropping tool.execution_complete for unknown subagent agentId=${i.agentId}`);return}this._logService.info(`[Copilot:${n}] Tool completed: ${i.data.toolCallId}`),this._activeToolCalls.delete(i.data.toolCallId);let a=o.displayName,l=i.data.error?.message??i.data.result?.content,c=[...o.content];l!==void 0&&c.push({type:"text",text:l});let u=Pe(o.parameters?.command)?o.parameters.command:void 0,d=is(o.toolName,u)?this._getEditFilePaths(o.parameters):[];for(let f of d)try{let m=await this._editTracker.takeCompletedEdit(this._turnId,i.data.toolCallId,f);m&&c.push(m)}catch(m){this._logService.warn(`[Copilot:${n}] Failed to take completed edit`,m)}if(su(o.toolName)&&this._shellManager){let f=this._shellManager.getTerminalUriForToolCall(i.data.toolCallId);f&&!c.some(m=>m.type==="terminal"&&m.resource===f)&&c.push({type:"terminal",resource:f,title:o.displayName})}this._sendToolInvokedTelemetry(i.data.success,i.data.error?.code,o),this._emitAction({type:"session/toolCallComplete",turnId:this._turnId,toolCallId:i.data.toolCallId,result:{success:i.data.success,pastTenseMessage:au(o.toolName,a,o.parameters,i.data.success),content:c.length>0?c:void 0,error:i.data.error}},s)})),this._register(e.onIdle(()=>{this._logService.info(`[Copilot:${n}] Session idle`),this._hasReportedActivity&&(this._hasReportedActivity=!1,this._emitAction({type:"session/activityChanged",activity:void 0})),this._completeActiveTurn()})),this._register(e.onSkillInvoked(i=>{this._logService.info(`[Copilot:${n}] Skill invoked: ${i.data.name} (${i.data.path})`);let o=lu(i.data,i.id);this._emitAction({type:"session/toolCallStart",turnId:this._turnId,toolCallId:o.toolCallId,toolName:o.toolName,displayName:o.displayName}),this._emitAction({type:"session/toolCallReady",turnId:this._turnId,toolCallId:o.toolCallId,invocationMessage:o.invocationMessage,confirmed:"not-needed"}),this._emitAction({type:"session/toolCallComplete",turnId:this._turnId,toolCallId:o.toolCallId,result:{success:!0,pastTenseMessage:o.pastTenseMessage}})})),this._register(e.onSubagentStarted(i=>{i.agentId&&this._parentToolCallIdsByAgentId.set(i.agentId,i.data.toolCallId),this._logService.info(`[Copilot:${n}] Subagent started: toolCallId=${i.data.toolCallId}, agent=${i.data.agentName}`),this._onDidSessionProgress.fire({kind:"subagent_started",session:this.sessionUri,toolCallId:i.data.toolCallId,agentName:i.data.agentName,agentDisplayName:i.data.agentDisplayName,agentDescription:i.data.agentDescription})})),this._register(e.onSessionError(i=>{this._logService.error(`[Copilot:${n}] Session error: ${i.data.errorType} - ${i.data.message}`),this._emitAction({type:"session/error",turnId:this._turnId,error:{errorType:i.data.errorType,message:i.data.message,stack:i.data.stack}})})),this._register(e.onUsage(i=>{let o={};typeof i.data.cost=="number"&&(o.cost=i.data.cost),this._logService.trace(`[Copilot:${n}] Usage: model=${i.data.model}, in=${i.data.inputTokens??"?"}, out=${i.data.outputTokens??"?"}, cacheRead=${i.data.cacheReadTokens??"?"}, cost=${i.data.cost??"?"}`);let s={inputTokens:i.data.inputTokens,outputTokens:i.data.outputTokens,model:i.data.model,cacheReadTokens:i.data.cacheReadTokens,...Object.keys(o).length>0?{_meta:o}:{}};this._emitAction({type:"session/usage",turnId:this._turnId,usage:s})})),this._register(e.onReasoningDelta(i=>{this._logService.trace(`[Copilot:${n}] Reasoning delta: ${i.data.deltaContent.length} chars`),!this._shouldDropUnmappedSubagentEvent(i,"assistant.reasoning_delta")&&this._emitReasoningDelta(i.data.deltaContent,this._parentToolCallIdForSubagentEvent(i))})),this._register(e.onSessionModeChanged(i=>{this._logService.info(`[Copilot:${n}] session.mode_changed: ${i.data.previousMode} -> ${i.data.newMode}`);let o=i.data.newMode;o!=="interactive"&&o!=="plan"&&o!=="autopilot"||(this._lastAppliedMode=o,this._syncAhpConfigFromSdkMode(o))}))}_syncAhpConfigFromSdkMode(e){let n=this.sessionUri.toString(),i={};switch(e){case"plan":i.mode="plan";break;case"autopilot":i.mode="interactive",i.autoApprove="autopilot";break;case"interactive":i.mode="interactive";break}this._configurationService.updateSessionConfig(n,i)}async handleExitPlanModeRequest(e){let n=q(),i=q();if(this._logService.info(`[Copilot:${this.sessionId}] exitPlanMode.request: rpcId=${n}, actions=[${e.actions.join(",")}], recommended=${e.recommendedAction}`),this._configurationService.getEffectiveValue(this.sessionUri.toString(),Mt,"autoApprove")==="autopilot"){let d=GE(e);return this._logService.info(`[Copilot:${this.sessionId}] exitPlanMode.request auto-accepted (autoApprove=autopilot): selectedAction=${d.selectedAction??"(none)"}`),d}let s=null;try{s=(await this._wrapper.session.rpc.plan.read()).path??null}catch(d){this._logService.warn(`[Copilot:${this.sessionId}] rpc.plan.read failed for exit_plan_mode: ${d instanceof Error?d.message:String(d)}`)}let a=e.summary||g(2005,null);if(s){let d=y.file(s);a+=`

[${g(2010,null)}](${d.toString()})`}this._emitMarkdownDelta(a);let l=e.actions.map(d=>{let f=BE(d);return{id:d,label:f?.label??d,description:f?.description,recommended:d===e.recommendedAction}}),c={id:n,questions:[{kind:"single-select",id:i,title:g(2009,null),message:g(2008,null),required:!0,options:l,allowFreeformInput:!0}]},u=new fe;this._pendingPlanReviews.set(n,{actions:e.actions,recommendedAction:e.recommendedAction,questionId:i,deferred:u}),this._onDidSessionProgress.fire({kind:"action",session:this.sessionUri,action:{type:"session/inputRequested",request:c}});try{return await u.p}catch(d){return this._logService.error(d,`[Copilot:${this.sessionId}] exitPlanMode.request handler failed: rpcId=${n}`),{approved:!1}}}_subscribeForLogging(){let e=this._wrapper,n=this.sessionId;this._register(e.onSessionStart(i=>{this._logService.trace(`[Copilot:${n}] Session started: model=${i.data.selectedModel??"default"}, producer=${i.data.producer}`)})),this._register(e.onSessionResume(i=>{this._logService.trace(`[Copilot:${n}] Session resumed: eventCount=${i.data.eventCount}`)})),this._register(e.onSessionInfo(i=>{this._logService.trace(`[Copilot:${n}] Session info [${i.data.infoType}]: ${i.data.message}`)})),this._register(e.onSessionModelChange(i=>{this._logService.trace(`[Copilot:${n}] Model changed: ${i.data.previousModel??"(none)"} -> ${i.data.newModel}`)})),this._register(e.onSessionHandoff(i=>{this._logService.trace(`[Copilot:${n}] Session handoff: sourceType=${i.data.sourceType}, remoteSessionId=${i.data.remoteSessionId??"(none)"}`)})),this._register(e.onSessionTruncation(i=>{this._logService.trace(`[Copilot:${n}] Session truncation: removed ${i.data.tokensRemovedDuringTruncation} tokens, ${i.data.messagesRemovedDuringTruncation} messages`)})),this._register(e.onSessionSnapshotRewind(i=>{this._logService.trace(`[Copilot:${n}] Snapshot rewind: upTo=${i.data.upToEventId}, eventsRemoved=${i.data.eventsRemoved}`)})),this._register(e.onSessionShutdown(i=>{this._logService.trace(`[Copilot:${n}] Session shutdown: type=${i.data.shutdownType}, apiDuration=${i.data.totalApiDurationMs}ms`)})),this._register(e.onSessionUsageInfo(i=>{this._logService.trace(`[Copilot:${n}] Usage info: ${i.data.currentTokens}/${i.data.tokenLimit} tokens, ${i.data.messagesLength} messages`)})),this._register(e.onSessionCompactionStart(()=>{this._logService.trace(`[Copilot:${n}] Compaction started`)})),this._register(e.onSessionCompactionComplete(i=>{this._logService.trace(`[Copilot:${n}] Compaction complete: success=${i.data.success}, tokensRemoved=${i.data.tokensRemoved??"?"}`)})),this._register(e.onUserMessage(i=>{this._logService.trace(`[Copilot:${n}] User message: ${i.data.content.length} chars, ${i.data.attachments?.length??0} attachments`)})),this._register(e.onPendingMessagesModified(()=>{this._logService.trace(`[Copilot:${n}] Pending messages modified`)})),this._register(e.onTurnStart(i=>{this._logService.trace(`[Copilot:${n}] Turn started: ${i.data.turnId}`)})),this._register(e.onIntent(i=>{this._logService.trace(`[Copilot:${n}] Intent: ${i.data.intent}`)})),this._register(e.onReasoning(i=>{this._logService.trace(`[Copilot:${n}] Reasoning: ${i.data.content.length} chars`)})),this._register(e.onTurnEnd(i=>{this._logService.trace(`[Copilot:${n}] Turn ended: ${i.data.turnId}`)})),this._register(e.onAbort(i=>{this._logService.trace(`[Copilot:${n}] Aborted: ${i.data.reason}`)})),this._register(e.onToolUserRequested(i=>{this._logService.trace(`[Copilot:${n}] Tool user-requested: ${i.data.toolName} (${i.data.toolCallId})`)})),this._register(e.onToolPartialResult(i=>{this._logService.trace(`[Copilot:${n}] Tool partial result: ${i.data.toolCallId} (${i.data.partialOutput.length} chars)`)})),this._register(e.onToolProgress(i=>{this._logService.trace(`[Copilot:${n}] Tool progress: ${i.data.toolCallId} - ${i.data.progressMessage}`)})),this._register(e.onSkillInvoked(i=>{this._logService.trace(`[Copilot:${n}] Skill invoked: ${i.data.name} (${i.data.path})`)})),this._register(e.onSubagentStarted(i=>{this._logService.trace(`[Copilot:${n}] Subagent started: ${i.data.agentName} (${i.data.agentDisplayName})`)})),this._register(e.onSubagentCompleted(i=>{i.agentId&&this._parentToolCallIdsByAgentId.delete(i.agentId),this._logService.trace(`[Copilot:${n}] Subagent completed: ${i.data.agentName}`),this._onDidSessionProgress.fire({kind:"subagent_completed",session:this.sessionUri,toolCallId:i.data.toolCallId})})),this._register(e.onSubagentFailed(i=>{i.agentId&&this._parentToolCallIdsByAgentId.delete(i.agentId),this._logService.error(`[Copilot:${n}] Subagent failed: ${i.data.agentName} - ${i.data.error}`),this._onDidSessionProgress.fire({kind:"subagent_completed",session:this.sessionUri,toolCallId:i.data.toolCallId})})),this._register(e.onSubagentSelected(i=>{this._logService.trace(`[Copilot:${n}] Subagent selected: ${i.data.agentName}`)})),this._register(e.onHookStart(i=>{this._logService.trace(`[Copilot:${n}] Hook started: ${i.data.hookType} (${i.data.hookInvocationId})`)})),this._register(e.onHookEnd(i=>{this._logService.trace(`[Copilot:${n}] Hook ended: ${i.data.hookType} (${i.data.hookInvocationId}), success=${i.data.success}`)})),this._register(e.onSystemMessage(i=>{this._logService.trace(`[Copilot:${n}] System message [${i.data.role}]: ${i.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 i=await this._wrapper.session.rpc.history.truncate({eventId:e});this._logService.info(`[Copilot:${this.sessionId}] SDK truncation removed ${i.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(i=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to delete pending edit content: ${n.toString()}`,i)}))}_cancelPendingUserInputs(){for(let[,e]of this._pendingUserInputs)e.deferred.complete({response:"cancel"});this._pendingUserInputs.clear()}_cancelPendingElicitations(){for(let[,e]of this._pendingElicitations)e.deferred.complete({response:"cancel"});this._pendingElicitations.clear()}_cancelPendingPlanReviews(){for(let[,e]of this._pendingPlanReviews)e.deferred.complete({approved:!1});this._pendingPlanReviews.clear()}_cancelPendingClientToolCalls(){for(let[,e]of this._pendingClientToolCalls)e.complete({textResultForLlm:"Tool call cancelled: session ended",resultType:"failure",error:"Session ended"});this._pendingClientToolCalls.clear()}};rs=w([C(1,qe),C(2,L),C(3,vt),C(4,Se),C(5,Ui),C(6,Je),C(7,Li)],rs);function GE(r){let t=r.actions??[],e=n=>n==="autopilot"||n==="autopilot_fleet";if(r.recommendedAction&&t.includes(r.recommendedAction)){let n=r.recommendedAction;return{approved:!0,selectedAction:n,...e(n)?{autoApproveEdits:!0}:{}}}for(let n of["autopilot","autopilot_fleet","interactive","exit_only"])if(t.includes(n))return{approved:!0,selectedAction:n,...e(n)?{autoApproveEdits:!0}:{}};return{approved:!0,autoApproveEdits:!0}}function JE(r){let t=0,e=0;for(let n of r.split(`
`))n.startsWith("+++")||n.startsWith("---")||(n.startsWith("+")?t++:n.startsWith("-")&&e++);if(!(t===0&&e===0))return{added:t,removed:e}}async function QE(r,t){if(!r||r.scheme!==oe.file||!await t.isInsideWorkTree(r))return;let e=(await t.getWorktreeRoots(r))[0]??await t.getRepositoryRoot(r);if(e)return{uri:e,displayName:_e(e.fsPath)||e.toString()}}function YE(r){let t=r.includes("://")?y.parse(r):y.parse(`https://github.com/${r}`),e=_e(t.path)||r.split("/").filter(Boolean).pop()||r,n=e.endsWith(".git")?e.slice(0,-4):e;return{uri:t,displayName:n}}async function fi(r,t){let e=typeof r?.cwd=="string"?y.file(r.cwd):typeof r?.gitRoot=="string"?y.file(r.gitRoot):void 0,n=await QE(e,t);if(n)return n;if(r?.repository)return YE(r.repository)}import{spawn as XE}from"child_process";function r_(r){let t={};for(let e of r){let n=e.configuration;n.type==="stdio"?t[e.name]={type:"local",command:n.command,args:n.args?[...n.args]:[],tools:["*"],...n.env&&{env:ZE(n.env)},...n.cwd&&{cwd:n.cwd}}:t[e.name]={type:"http",url:n.url,tools:["*"],...n.headers&&{headers:{...n.headers}}}}return t}function ZE(r){let t={};for(let[e,n]of Object.entries(r))n!==null&&(t[e]=String(n));return t}async function o_(r,t){let e=[];for(let n of r)try{let o=(await t.readFile(n.uri)).value.toString(),s=Zo(o),a=s?.getStringValue("name")??n.name,l=s?.getStringValue("description"),c=s?.getStringArrayValue("tools"),u=s?.body??o;e.push({name:a,...l?{description:l}:{},tools:c&&c.length>0?c:null,prompt:u})}catch{}return e}function fm(r){let t=new Map,e=n=>{t.has(n.id)||t.set(n.id,n)};for(let n of r){for(let i of n.agents)e(i.customization);for(let i of n.skills)e(i.customization);for(let i of n.instructions)e(i.customization);for(let i of n.hooks)e(i.customization);for(let i of n.mcpServers)e(i.customization)}return[...t.values()]}function s_(r){return l_(r)}function a_(r){return l_(r)}function l_(r){let t=new Set,e=[];for(let n of r){let i=de(n.uri.fsPath);t.has(i)||(t.add(i),e.push(i))}return e}function eP(r,t){return t===1&&r.windows?r.windows:t===2&&r.osx?r.osx:t===3&&r.linux?r.linux:r.command}function nl(r,t){let e=eP(r,mt);if(!e)return Promise.resolve("");let n=(r.timeout??30)*1e3,i=r.cwd?.fsPath;return new Promise((o,s)=>{let a=mt===1,u=XE(a?"cmd.exe":"/bin/sh",a?["/c",e]:["-c",e],{cwd:i,env:{...process.env,...r.env},stdio:["pipe","pipe","pipe"],timeout:n}),d="",f="";u.stdout.on("data",m=>{d+=m.toString()}),u.stderr.on("data",m=>{f+=m.toString()}),t&&u.stdin.write(t),u.stdin.end(),u.on("error",s),u.on("close",m=>{m===0?o(d):s(new Error(`Hook command exited with code ${m}: ${f||d}`))})})}async function i_(r,t){if(!r)return;let e=JSON.stringify(t);for(let n of r)try{let i=await nl(n,e);if(i.trim())try{let o=JSON.parse(i);if(o&&typeof o=="object")return o}catch{}}catch{}}var tP={PreToolUse:"onPreToolUse",PostToolUse:"onPostToolUse",UserPromptSubmit:"onUserPromptSubmitted",SessionStart:"onSessionStart",SessionEnd:"onSessionEnd",ErrorOccurred:"onErrorOccurred"};function c_(r,t){let e=new Map;for(let u of r){let d=tP[u.type];if(!d)continue;let f=e.get(d)??[];f.push(...u.commands),e.set(d,f)}let n={},i=e.get("onPreToolUse");(i?.length||t)&&(n.onPreToolUse=async u=>(await t?.onPreToolUse(u),i_(i,u)));let o=e.get("onPostToolUse");(o?.length||t)&&(n.onPostToolUse=async u=>(await t?.onPostToolUse(u),i_(o,u)));let s=e.get("onUserPromptSubmitted");s?.length&&(n.onUserPromptSubmitted=async u=>{let d=JSON.stringify(u);for(let f of s)try{await nl(f,d)}catch{}});let a=e.get("onSessionStart");a?.length&&(n.onSessionStart=async u=>{let d=JSON.stringify(u);for(let f of a)try{await nl(f,d)}catch{}});let l=e.get("onSessionEnd");l?.length&&(n.onSessionEnd=async u=>{let d=JSON.stringify(u);for(let f of l)try{await nl(f,d)}catch{}});let c=e.get("onErrorOccurred");return c?.length&&(n.onErrorOccurred=async u=>{let d=JSON.stringify(u);for(let f of c)try{await nl(f,d)}catch{}}),n}function d_(r,t){let e=n=>JSON.stringify(n.map(i=>({hooks:i.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:i.mcpServers.map(o=>({name:o.name,configuration:o.configuration})),skills:i.skills.map(o=>({uri:o.uri.toString(),name:o.name})),agents:i.agents.map(o=>({uri:o.uri.toString(),name:o.name})),instructions:i.instructions.map(o=>({uri:o.uri.toString(),name:o.name}))})));return e(r)===e(t)}var os=class extends T{constructor(e){super();this.session=e;this._register(A(()=>{e.disconnect().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")}get onSystemNotification(){return this._onSystemNotification??=this._sdkEvent("system.notification")}get onSessionModeChanged(){return this._onSessionModeChanged??=this._sdkEvent("session.mode_changed")}_sdkEvent(e){let n=this._register(new x),i=this.session.on(e,o=>n.fire(o));return this._register(A(i)),n.event}};var hu=V("sandboxHelperService");var nP=new Set(["7z","bz2","cjs","class","cpp","cs","css","csv","dll","exe","gif","gz","ico","jar","env","java","jpeg","jpg","js","json","jsx","lock","log","md","mjs","pdf","php","png","py","rar","rs","so","sql","svg","tar","tgz","toml","ts","tsx","txt","wasm","webp","xml","yaml","yml","zip"]),iP=new Set(["ai","cloud","com","dev","io","me","net","org","tech"]);function il(r,t=!1){if(!r)return;let e=r.trim().toLowerCase().replace(/^[^@]+@/,"").replace(/:\d+$/,"").replace(/\.+$/,"");if(!e||e.includes("/")||e==="."||e==="..")return;if(e==="*")return"*";if(!/^\*?\.?[a-z0-9.;,)!?:-]+$/.test(e))return;let n=e.replace(/[),;:!?]+$/,"");if(!n)return;let i=n.startsWith("*.")?n.slice(2):n;if(!/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))*$/.test(i))return;let o=n.startsWith("*."),s=o?n.slice(2):n;if(s&&/^[a-z0-9.-]+$/.test(s)){if(!t){let a=s.slice(s.lastIndexOf(".")+1);if(nP.has(a)||!iP.has(a))return}return o?`*.${s}`:s}}function rP(r){let t=r.trim();if(t==="*"||!t.includes("://"))return t;try{return y.parse(t).authority}catch{return t}}function gm(r,t){let e=il(rP(t),t.includes("://"));if(!e)return!1;if(e==="*")return!0;if(e.startsWith("*.")){let n=e.slice(2);return r===n||r.endsWith(`.${n}`)}return r===e}var vu=V("windowsMxcTerminalSandboxRuntime"),yu=class{constructor(){this._configVersion="0.4.0-alpha";this._containerName="vscode-terminal-sandbox"}getExecutablePath(t,e){let n=e==="arm64"?"arm64":"x64";return ae.join(t,"node_modules","@microsoft","mxc-sdk","bin",n,"wxc-exec.exe")}getRuntimeReadPaths(t,e){let n=[];return t&&n.push(t),e&&n.push(e,ae.dirname(e)),[...new Set(n)]}async createConfig(t,e){let n=this.toWindowsPath(t.tempDir),o=`${t.shell?this._quoteWindowsCommandLineArgument(t.shell):"pwsh.exe"} -NoProfile -ExecutionPolicy Bypass -Command ${this._quoteWindowsCommandLineArgument(t.command)}`,s=t.cwd?this.toWindowsPath(t.cwd):n,a={version:t.schemaVersion??this._configVersion,timeoutMs:0,filesystem:{readwritePaths:[...new Set(t.allowWritePaths.map(c=>this._normalizeWindowsPath(c)))],readonlyPaths:[...new Set([n,...t.shell&&ae.isAbsolute(t.shell)?[ae.dirname(t.shell)]:[],...t.allowReadPaths].map(c=>this._normalizeWindowsPath(c)))],deniedPaths:[...new Set(t.denyReadPaths.map(c=>this._normalizeWindowsPath(c)))]},network:this._createNetworkPolicy(t.allowNetwork,t.networkDomains),ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}},l=await e(o,a,s,this._containerName);if(!l?.process)throw new Error("Unable to build Windows MXC sandbox payload");return l.process.env=[...t.env],l}wrapCommand(t,e){return`& ${this._quotePowerShellArgument(t)} ${this._quotePowerShellArgument(e)}`}wrapUnsandboxedCommand(t){return t}toWindowsPath(t){let e;return t.authority&&t.path.length>1&&t.scheme==="file"?e=`\\\\${t.authority}${t.path}`:/^\/[a-zA-Z]:/.test(t.path)?e=t.path.slice(1):e=t.fsPath,this._normalizeWindowsPath(e)}_normalizeWindowsPath(t){return t.replace(/\//g,"\\")}_createNetworkPolicy(t,e){let n=e.allowedDomains.length>0?e.allowedDomains:void 0,i=e.deniedDomains.length>0?e.deniedDomains:void 0,o=t||!!n?.length,s={allowOutbound:o};return o&&n&&(s.allowedHosts=n),o&&i&&(s.blockedHosts=i),s}_quotePowerShellArgument(t){return`'${t.replace(/'/g,"''")}'`}_quoteWindowsCommandLineArgument(t){return`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/\\+$/g,"$&$&")}"`}};var bu=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--html-path","--info-path","--man-path","--namespace","--super-prefix","--work-tree"]);function Su(r,t,e){if(!t.keywords.includes(r.keyword.toLowerCase())||t.condition&&(!e||!t.condition(e)))return!1;if(t.subcommands){let n=oP(r.args,t.optionsWithValue);if(n===void 0||!t.subcommands.includes(n))return!1}return t.when?.(r)??!0}function oP(r,t){for(let e=0;e<r.length;e++){let n=r[e];if(n==="--")return;if(n.startsWith("-")){let i=n.includes("=")?n.substring(0,n.indexOf("=")):n;!n.includes("=")&&t?.has(i)&&e++;continue}return n.toLowerCase()}}var sP=new Map([["git","git"],["gh","git"],["node","node"],["npm","node"],["npx","node"],["pnpm","node"],["yarn","node"],["corepack","node"],["bun","node"],["deno","node"],["nvm","node"],["volta","node"],["fnm","node"],["asdf","node"],["mise","node"],["cargo","rust"],["rustc","rust"],["rustup","rust"],["go","go"],["gofmt","go"],["python","python"],["python3","python"],["pip","python"],["pip3","python"],["poetry","python"],["uv","python"],["pipx","python"],["pyenv","python"],["java","java"],["javac","java"],["jar","java"],["mvn","java"],["mvnw","java"],["gradle","java"],["gradlew","java"],["sdk","java"],["dotnet","dotnet"],["nuget","nuget"],["msbuild","msbuild"],["ruby","ruby"],["gem","ruby"],["bundle","ruby"],["bundler","ruby"],["rake","ruby"],["rbenv","ruby"],["rvm","ruby"],["ccache","nativeBuild"],["sccache","nativeBuild"],["cmake","nativeBuild"],["conan","conan"]]);function p_(r,t){if(t===1)return[];switch(r){case"git":switch(t){case 2:case 3:default:return["~/.gitconfig","~/.config/git/config","~/.gitignore","~/.gitignore_global","~/.config/git/ignore","~/.config/git/attributes"]}case"node":switch(t){case 2:return["~/.npm","~/Library/Caches/node","~/Library/Caches/electron","~/Library/Caches/ms-playwright","~/Library/Caches/Yarn","~/Library/Caches/deno","~/Library/pnpm","~/.electron-gyp","~/.node-gyp","~/.yarn/berry","~/.local/share/pnpm","~/.pnpm-store","~/.bun/install/cache","~/.bun/bin","~/.deno","~/.nvm/versions","~/.nvm/alias","~/.volta/bin","~/.volta/tools","~/.fnm","~/.asdf/installs/nodejs","~/.asdf/shims","~/.local/share/mise/installs/node","~/.local/share/mise/shims"];case 3:default:return["~/.npm","~/.cache/node","~/.cache/node/corepack","~/.cache/electron","~/.cache/ms-playwright","~/.cache/yarn","~/.electron-gyp","~/.node-gyp","~/.yarn/berry","~/.local/share/pnpm","~/.pnpm-store","~/.bun/install/cache","~/.bun/bin","~/.deno","~/.cache/deno","~/.nvm/versions","~/.nvm/alias","~/.volta/bin","~/.volta/tools","~/.fnm","~/.asdf/installs/nodejs","~/.asdf/shims","~/.local/share/mise/installs/node","~/.local/share/mise/shims"]}case"rust":switch(t){case 2:case 3:default:return["~/.cargo/bin","~/.cargo/registry","~/.cargo/git","~/.rustup/toolchains"]}case"go":switch(t){case 2:return["~/go/pkg/mod","~/go/bin","~/Library/Caches/go-build"];case 3:default:return["~/go/pkg/mod","~/go/bin","~/.cache/go-build"]}case"python":switch(t){case 2:return["~/Library/Caches/pip","~/Library/Caches/pypoetry","~/Library/Caches/uv","~/.local/bin","~/.local/share/virtualenv","~/.local/share/pipx","~/.pyenv/versions","~/.pyenv/shims"];case 3:default:return["~/.cache/pip","~/.cache/pypoetry","~/.cache/uv","~/.local/bin","~/.local/share/virtualenv","~/.local/share/pipx","~/.pyenv/versions","~/.pyenv/shims"]}case"java":switch(t){case 2:case 3:default:return["~/.m2/repository","~/.gradle/caches","~/.gradle/wrapper/dists","~/.sdkman/candidates"]}case"dotnet":switch(t){case 2:case 3:default:return["~/.dotnet"]}case"nuget":switch(t){case 2:return["~/.nuget/packages","~/Library/Caches/NuGet/v3-cache"];case 3:default:return["~/.nuget/packages","~/.local/share/NuGet/v3-cache"]}case"msbuild":switch(t){case 2:case 3:default:return[]}case"ruby":switch(t){case 2:return["~/.gem","~/.rbenv/versions","~/.rbenv/shims","~/.rvm/rubies"];case 3:default:return["~/.gem","~/.rbenv/versions","~/.rbenv/shims","~/.rvm/rubies"]}case"nativeBuild":switch(t){case 2:return["~/Library/Caches/ccache","~/Library/Caches/sccache"];case 3:default:return["~/.cache/ccache","~/.cache/sccache"]}case"conan":switch(t){case 2:case 3:default:return["~/.conan2/p","~/.conan2/b"]}case"gnupg":switch(t){case 2:case 3:default:return["~/.gnupg"]}}}function u_(r,t){let e=new Set;for(let i of t)for(let o of aP)Su(i,o,{os:r})&&e.add(o.value);let n=[...e].flatMap(i=>p_(i,r));return[...new Set(n)]}var aP=[{keywords:["gpg","gpg2"],value:"gnupg"},{keywords:["git"],value:"gnupg",subcommands:["commit"],optionsWithValue:bu}];function Iu(r,t,e=[]){if(t.length===0)return u_(r,e);let n=new Set;for(let o of t){let s=sP.get(o.toLowerCase());s&&n.add(s)}let i=[...n].flatMap(o=>p_(o,r));return[...new Set([...i,...u_(r,e)])]}var lP=[{keywords:["node","npm","npx","pnpm","yarn","corepack","bun","deno","nvm","volta","fnm","asdf","mise"],value:"node"},{keywords:["git"],value:"gnupg",subcommands:["commit"],optionsWithValue:bu,condition:({os:r})=>r!==1,when:dP}];function cP(r,t){switch(r){case"gnupg":switch(t){case 1:return{};case 2:case 3:default:return{network:{allowAllUnixSockets:!0},filesystem:{allowRead:["~/.gnupg"],allowWrite:["~/.gnupg"]}}}case"node":switch(t){case 1:return{};case 2:case 3:default:return{filesystem:{allowWrite:["~/.volta/"]}}}}}function _u(r,t){let e=new Set;for(let i of t)for(let o of lP)Su(i,o,{os:r})&&e.add(o.value);let n={};for(let i of e)g_(n,cP(i,r));return n}function dP(r){return r.args.some(t=>t==="-S"||t.startsWith("-S")||t==="--gpg-sign"||t.startsWith("--gpg-sign="))}function g_(r,t){for(let[e,n]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(r,e)){r[e]=n;continue}let i=r[e];if(Array.isArray(i)&&Array.isArray(n)){r[e]=[...new Set([...i,...n])];continue}f_(i)&&f_(n)&&g_(i,n)}}function f_(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var FX=V("terminalSandboxService");var Jt=class extends T{constructor(e,n,i,o){super();this._host=e;this._fileService=n;this._logService=i;this._windowsMxcRuntime=o;this._sandboxSettingsId=q();this._runtimeResolved=!1;this._runAsNode=!1;this._needsForceUpdateConfigFile=!0;this._commandAllowListKeywords=[];this._commandAllowListCommandDetails=[];this._commandAllowNetwork=!1;this._os=mt;this._defaultWritePaths=[];this._buildSandboxPayload=(e,n,i,o,s)=>this._host.buildWindowsMxcSandboxPayload(e,n,i,o,s);this._pathJoin=(...e)=>(this._os===1?ae:Z).join(...e);this._register(Q.runAndSubscribe(this._host.onDidChangeSandboxSettings,()=>{this.setNeedsForceUpdateConfigFile()})),this._register(this._host.onDidChangeRoots(()=>this.setNeedsForceUpdateConfigFile()))}static{this._urlRegex=/(?:https?|wss?):\/\/[^\s'"`|&;<>]+/gi}static{this._sshRemoteRegex=/(?:^|[\s'"`])(?:[^\s@:'"`]+@)?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})(?::[^\s'"`|&;<>]+)(?=$|[\s'"`|&;<>])/gi}static{this._hostRegex=/(?:^|[\s'"`(=])([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})(?::\d+)?(?=(?:\/[^\s'"`|&;<>]*)?(?:$|[\s'"`)\]|,;|&<>]))/gi}async isEnabled(e){return this._isSandboxConfiguredEnabled(e)}async isSandboxAllowNetworkEnabled(e){return await this._isSandboxConfiguredEnabled(e)?this._isSandboxAllowNetworkConfigured():!1}areUnsandboxedCommandsAllowed(){return this._areUnsandboxedCommandsAllowed()}areRetryWithAllowNetworkRequestsAllowed(){return this._areRetryWithAllowNetworkRequestsAllowed()}isAutoApproveUnsandboxedCommands(){return this._areUnsandboxedCommandsAllowed()&&this._getSettingValue("chat.agent.sandbox.autoApproveUnsandboxedCommands")===!0}async getOS(){return this._os=await this._host.getOS(),this._os}getTempDir(){return this._tempDir}setNeedsForceUpdateConfigFile(){this._needsForceUpdateConfigFile=!0}getResolvedNetworkDomains(){let e=this._getSettingValue("chat.agent.allowedNetworkDomains")??[],n=this._getSettingValue("chat.agent.deniedNetworkDomains")??[];return{allowedDomains:e,deniedDomains:n}}async wrapCommand(e,n,i,o,s,a){let l=this._areUnsandboxedCommandsAllowed(),c=this._areRetryWithAllowNetworkRequestsAllowed(),d=n!==!0&&a!==!0&&(c||l)?this._getBlockedDomains(e):{blockedDomains:[],deniedDomains:[]},f=c&&d.blockedDomains.length>0,m=n!==!0&&(a===!0&&c||f),h=this._normalizeCommandDetails(s??[]),v=this._normalizeCommandKeywords(h.map(M=>M.keyword)),S=Iu(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),_=Iu(this._os,v,h),b=_u(this._os,this._commandAllowListCommandDetails),I=_u(this._os,h);if((this._commandAllowListKeywords.length===0||this._needsForceUpdateConfigFile||!this._areStringArraysEqual(this._commandAllowListKeywords,v)||!this._areStringArraysEqual(S,_)||!this._areObjectsEqual(b,I)||this._commandCwd?.toString()!==o?.toString()||this._commandAllowNetwork!==m||this._os===1&&(this._commandLine!==e||this._commandShell!==i))&&(this._commandAllowListKeywords=v,this._commandAllowListCommandDetails=h,this._commandCwd=o,this._commandLine=e,this._commandShell=i,this._commandAllowNetwork=m,await this.getSandboxConfigPath(!0)),!this._sandboxConfigPath||!this._tempDir)throw new Error("Sandbox config path or temp dir not initialized");if(!n&&!c&&l&&d.blockedDomains.length>0)return{command:this._wrapUnsandboxedCommand(e,i),isSandboxWrapped:!1,blockedDomains:d.blockedDomains,deniedDomains:d.deniedDomains,requiresUnsandboxConfirmation:!0};if(n&&l)return{command:this._wrapUnsandboxedCommand(e,i),isSandboxWrapped:!1};let P=f?{blockedDomains:d.blockedDomains,deniedDomains:d.deniedDomains}:void 0;if(this._os===1){if(!this._mxcPath)throw new Error("MXC executable path not resolved");return{command:this._windowsMxcRuntime.wrapCommand(this._mxcPath,this._sandboxConfigPath),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...P}}if(!this._execPath)throw new Error("Executable path not set to run sandbox commands");if(!this._srtPath)throw new Error("Sandbox runtime path not resolved");if(!this._rgPath)throw new Error("Ripgrep path not resolved");let j=this._getSandboxCommandWithPreservedCwd(e,o),E=`PATH="$PATH:${this._pathDirname(this._rgPath)}" TMPDIR="${this._tempDir.path}" CLAUDE_TMPDIR="${this._tempDir.path}" "${this._execPath}" "${this._srtPath}" --settings "${this._sandboxConfigPath}" -c ${this._quoteShellArgument(j)}`;if(this._runAsNode){let M=`ELECTRON_RUN_AS_NODE=1 ${E}`;return{command:this._wrapSandboxRuntimeCommandForLaunch(M,o),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...P}}return{command:this._wrapSandboxRuntimeCommandForLaunch(E,o),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...P}}async checkForSandboxingPrereqs(e=!1,n){if(!await this._isSandboxConfiguredEnabled(n))return{enabled:!1,sandboxConfigPath:void 0,failedCheck:void 0};let i=await this.getSandboxConfigPath(e,n);return i?await this._checkSandboxDependencies(e)?{enabled:!0,sandboxConfigPath:i,failedCheck:void 0}:{enabled:!0,sandboxConfigPath:i,failedCheck:"dependencies",missingDependencies:await this.getMissingSandboxDependencies()}:{enabled:!0,sandboxConfigPath:i,failedCheck:"config"}}async getSandboxConfigPath(e=!1,n){if(await this._isSandboxConfiguredEnabled(n))return await this._resolveRuntimeInfo(),(!this._sandboxConfigPath||e||this._needsForceUpdateConfigFile)&&(this._sandboxConfigPath=await this._createSandboxConfig(),this._needsForceUpdateConfigFile=!1),this._sandboxConfigPath}async getMissingSandboxDependencies(){if(await this.getOS()===1)return[];(!this._sandboxDependencyStatus||!this._sandboxDependencyStatus.bubblewrapInstalled||!this._sandboxDependencyStatus.socatInstalled)&&(this._sandboxDependencyStatus=await this._host.checkSandboxDependencies());let n=[];return this._sandboxDependencyStatus&&!this._sandboxDependencyStatus.bubblewrapInstalled&&n.push("bubblewrap"),this._sandboxDependencyStatus&&!this._sandboxDependencyStatus.socatInstalled&&n.push("socat"),n}async cleanupTempDir(){if(this._tempDir)try{await this._fileService.del(this._tempDir,{recursive:!0,useTrash:!1})}catch(e){this._logService.warn("TerminalSandboxEngine: Failed to delete sandbox temp dir",e)}}async _checkSandboxDependencies(e=!1){if(await this.getOS()===1)return!0;if(!e&&this._sandboxDependencyStatus)return this._sandboxDependencyStatus.bubblewrapInstalled&&this._sandboxDependencyStatus.socatInstalled;let i=await this._host.checkSandboxDependencies();return this._sandboxDependencyStatus=i,i&&!i.bubblewrapInstalled&&this._logService.warn("TerminalSandboxEngine: bubblewrap (bwrap) is not installed"),i&&!i.socatInstalled&&this._logService.warn("TerminalSandboxEngine: socat is not installed"),i?i.bubblewrapInstalled&&i.socatInstalled:!0}_quoteShellArgument(e){return`'${e.replace(/'/g,"'\\''")}'`}_getSandboxCommandWithPreservedCwd(e,n){return this._os!==3||!n?.path||n.path===this._tempDir?.path?e:`cd ${this._quoteShellArgument(n.path)} && ${e}`}_wrapSandboxRuntimeCommandForLaunch(e,n){let i=this._tempDir?.path;return this._os===3&&n?.path&&i&&n.path!==i?`cd ${this._quoteShellArgument(i)}; ${e}`:e}_wrapUnsandboxedCommand(e,n){return this._os===1?this._windowsMxcRuntime.wrapUnsandboxedCommand(e):this._tempDir?.path?n?`env TMPDIR="${this._tempDir.path}" ${this._quoteShellArgument(n)} -c ${this._quoteShellArgument(e)}`:`(TMPDIR="${this._tempDir.path}"; export TMPDIR; ${e})`:e}_getBlockedDomains(e){if(this._isSandboxAllowNetworkConfigured())return{blockedDomains:[],deniedDomains:[]};let n=this._extractDomains(e);if(n.length===0)return{blockedDomains:[],deniedDomains:[]};let{allowedDomains:i,deniedDomains:o}=this.getResolvedNetworkDomains(),s=new Set,a=new Set;for(let l of n){if(o.some(c=>gm(l,c))){s.add(l),a.add(l);continue}i.some(c=>gm(l,c))||s.add(l)}return{blockedDomains:[...s],deniedDomains:[...a]}}_extractDomains(e){let n=new Set,i;for(Jt._urlRegex.lastIndex=0;(i=Jt._urlRegex.exec(e))!==null;){let o=this._extractDomainFromUrl(i[0]);o&&n.add(o)}for(Jt._sshRemoteRegex.lastIndex=0;(i=Jt._sshRemoteRegex.exec(e))!==null;){let o=il(i[1],!0);o&&n.add(o)}for(Jt._hostRegex.lastIndex=0;(i=Jt._hostRegex.exec(e))!==null;){let o=il(i[1]);o&&n.add(o)}return[...n]}_extractDomainFromUrl(e){try{let n=y.parse(e).authority;return il(n,!0)}catch{return}}_normalizeCommandKeywords(e){return[...new Set(e.map(n=>n.toLowerCase()))].sort()}_normalizeCommandDetails(e){let n=new Set,i=[];for(let o of e){let s={keyword:o.keyword.toLowerCase(),args:[...o.args]},a=JSON.stringify(s);n.has(a)||(n.add(a),i.push(s))}return i.sort((o,s)=>o.keyword.localeCompare(s.keyword)||o.args.join("\0").localeCompare(s.args.join("\0")))}_areStringArraysEqual(e,n){return e.length===n.length&&e.every((i,o)=>i===n[o])}_areObjectsEqual(e,n){return JSON.stringify(e)===JSON.stringify(n)}_isSandboxAllowedByPrecheckInputs(e){return e?.isDefaultApprovalPermissionEnabled!==!1}async _isSandboxConfiguredEnabled(e){if(!this._isSandboxAllowedByPrecheckInputs(e))return!1;if(await this.getOS(),this._os===1)return this._getSandboxConfiguredWindowsEnabledValue()==="allowNetwork";let n=this._getSandboxConfiguredEnabledValue();return n==="on"||n==="allowNetwork"}async _resolveRuntimeInfo(){if(this._runtimeResolved)return;this._runtimeResolved=!0;let e=await this._host.getRuntimeInfo();this._appRoot=e.appRoot,this._execPath=e.execPath,this._runAsNode=e.runAsNode??!1,this._userHome=await this._host.getUserHome(),this._srtPath=this._pathJoin(this._appRoot,"node_modules","@vscode","sandbox-runtime","dist","cli.js");let n=this._os===1?"win32":this._os===2?"darwin":"linux",i=this._os===1?"rg.exe":"rg";this._rgPath=this._pathJoin(this._appRoot,"node_modules","@vscode","ripgrep-universal","bin",`${n}-${Kh}`,i),this._mxcPath=this._windowsMxcRuntime.getExecutablePath(this._appRoot,e.arch)}async _createSandboxConfig(){if(await this.isEnabled()&&!this._tempDir&&await this._initTempDir(),!this._tempDir)return;let e=this._commandAllowNetwork||await this.isSandboxAllowNetworkEnabled(),n=this._os===3?this._getSettingValue("chat.agent.sandbox.fileSystem.linux")??{}:{},i=this._os===2?this._getSettingValue("chat.agent.sandbox.fileSystem.mac")??{}:{},o=this._os===1?this._getSettingValue("chat.agent.sandbox.fileSystem.windows")??{}:{},s=this._os===1?this._getSettingValue("chat.agent.sandbox.advanced.windows.schemaVersion"):void 0,a=this._getSettingValue("chat.agent.sandbox.advanced.runtime")??{},l=_u(this._os,this._commandAllowListCommandDetails),c=this._getCommandRuntimeFileSystemPaths(l,"allowRead"),u=this._getCommandRuntimeFileSystemPaths(l,"allowWrite"),d=y.joinPath(this._tempDir,`vscode-sandbox-settings-${this._sandboxSettingsId}.json`),f=[],m=[],h=[],v;if(this._os===1){let _=await this._getWindowsMxcFilesystemPolicy(),b=await this._getWindowsMxcEnvironment();f=await this._resolveFileSystemPaths([...await this._updateAllowWritePathsWithWorkspaceFolders(o.allowWrite),..._.readwritePaths]),m=await this._resolveFileSystemPaths([...o.allowRead??[],..._.readonlyPaths]),h=await this._resolveFileSystemPaths(o.denyRead??[]),this._windowsMxcEnvironment=b}else this._os===2?(f=await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(i.allowWrite,u)),m=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(i.allowRead,f,c)),h=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome(i.denyRead)),v=i.denyWrite?await this._resolveFileSystemPaths(i.denyWrite):void 0):this._os===3&&(f=await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(n.allowWrite,u)),m=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(n.allowRead,f,c)),h=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome(n.denyRead)),v=await this._resolveFileSystemPaths(n.denyWrite));let S=this._os===1?await this._windowsMxcRuntime.createConfig({command:this._commandLine??"",shell:this._commandShell,cwd:this._commandCwd??this._getDefaultWindowsMxcCwd(),tempDir:this._tempDir,schemaVersion:s,allowNetwork:e,networkDomains:this.getResolvedNetworkDomains(),allowReadPaths:m,allowWritePaths:f,denyReadPaths:h,env:this._windowsMxcEnvironment??[]},this._buildSandboxPayload):{network:e?{allowedDomains:[],deniedDomains:[],enabled:!1}:this.getResolvedNetworkDomains(),filesystem:{denyRead:h,allowRead:m,allowWrite:f,denyWrite:v}};return this._os!==1&&(this._mergeAdditionalSandboxConfigProperties(S,e?this._withoutNetworkRuntimeSetting(a):a),this._mergeAdditionalSandboxConfigProperties(S,l)),this._sandboxConfigPath=this._getUriPath(d),await this._fileService.createFile(d,k.fromString(JSON.stringify(S,null,"	")),{overwrite:!0}),this._sandboxConfigPath}_getCommandRuntimeFileSystemPaths(e,n){let i=e.filesystem;if(!this._isObjectForSandboxConfigMerge(i))return[];let o=i[n];return Array.isArray(o)?o.filter(s=>typeof s=="string"):[]}_withoutNetworkRuntimeSetting(e){let n={...e};return delete n.network,n}_mergeAdditionalSandboxConfigProperties(e,n){for(let[i,o]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(e,i)){e[i]=o;continue}let s=e[i];this._isObjectForSandboxConfigMerge(s)&&this._isObjectForSandboxConfigMerge(o)&&this._mergeAdditionalSandboxConfigProperties(s,o)}}_isObjectForSandboxConfigMerge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async _getWindowsMxcFilesystemPolicy(){return this._windowsMxcFilesystemPolicy||(this._windowsMxcFilesystemPolicy=await this._host.getWindowsMxcFilesystemPolicy()??{readonlyPaths:[],readwritePaths:[]}),this._windowsMxcFilesystemPolicy}async _getWindowsMxcEnvironment(){return this._windowsMxcEnvironment||(this._windowsMxcEnvironment=await this._host.getWindowsMxcEnvironment()??[]),this._windowsMxcEnvironment}_pathDirname(e){return(this._os===1?ae:Z).dirname(e)}_getUriPath(e){return this._os===1?this._windowsMxcRuntime.toWindowsPath(e):e.path}async _initTempDir(){await this.isEnabled()&&(this._needsForceUpdateConfigFile=!0,this._tempDir=await this._host.getSandboxTempDir(),this._tempDir?(await this._fileService.createFolder(this._tempDir),this._defaultWritePaths.push(this._getUriPath(this._tempDir))):this._logService.warn("TerminalSandboxEngine: Cannot create sandbox settings file because no tmpDir is available in this environment"))}async _updateAllowWritePathsWithWorkspaceFolders(e,n=[]){let i=this._host.getWriteRoots().map(o=>this._getUriPath(o));return[...new Set([...i,...this._defaultWritePaths,...await this._getWorkspaceStorageReadPaths(),...e??[],...n])]}_updateDenyReadPathsWithHome(e){if(this._os===1)return[...new Set(e??[])];let n=this._userHome?this._getUriPath(this._userHome):void 0;return[...new Set([...e??[],...n?[n]:[]])]}async _updateAllowReadPathsWithAllowWrite(e,n,i=[]){return[...new Set([...e??[],...Iu(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),...i,...this._getSandboxRuntimeReadPaths(),...await this._getWorkspaceStorageReadPaths(),...n])]}async _resolveFileSystemPaths(e){let n=await Promise.all((e??[]).map(i=>this._resolveFileSystemPath(i)));return[...new Set(n)]}async _resolveFileSystemPath(e){let n=this._os===3?this._expandHomePath(e):e;if(!this._isAbsoluteFileSystemPath(n))return n;try{let i=await this._fileService.realpath(this._toFileSystemResource(n)),o=i?this._getUriPath(i):void 0;return o&&o!==n?o:n}catch{return n}}_isAbsoluteFileSystemPath(e){return(this._os===1?ae:Z).isAbsolute(e)}_toFileSystemResource(e){return this._os===1?this._toWindowsFileSystemResource(e):this._userHome?.with({path:e})??this._tempDir?.with({path:e})??this._host.getWriteRoots()[0]?.with({path:e})??y.file(e)}_toWindowsFileSystemResource(e){let n=e.replace(/\\/g,"/");if(/^\/\/[^/]/.test(n)){let i=n.indexOf("/",2);return i===-1?y.from({scheme:"file",authority:n.slice(2),path:"/"}):y.from({scheme:"file",authority:n.slice(2,i),path:n.slice(i)||"/"})}return/^[a-zA-Z]:($|\/)/.test(n)?y.from({scheme:"file",path:`/${n[0].toLowerCase()}${n.slice(1)}`}):/^\/[a-zA-Z]:($|\/)/.test(n)?y.from({scheme:"file",path:`/${n[1].toLowerCase()}${n.slice(2)}`}):y.from({scheme:"file",path:n})}_expandHomePath(e){let n=this._userHome?.path;return n?e==="~"?n:e.startsWith("~/")?this._pathJoin(n,e.slice(2)):e:e}_getSandboxRuntimeReadPaths(){if(!this._appRoot)return[];if(this._os===1)return this._windowsMxcRuntime.getRuntimeReadPaths(this._appRoot,this._mxcPath);let e=[this._appRoot];if(this._execPath)for(let n of[this._execPath,this._pathDirname(this._execPath)])this._isPathUnderAppRoot(n)||e.push(n);return e}_isPathUnderAppRoot(e){return this._appRoot?e===this._appRoot||e.startsWith(`${this._appRoot}${this._os===1?ae.sep:Z.sep}`):!1}async _getWorkspaceStorageReadPaths(){let e=await this._host.getWorkspaceStorageReadRoot();return e?[this._getUriPath(e)]:[]}_getDefaultWindowsMxcCwd(){return this._host.getWriteRoots()[0]}_getSandboxConfiguredEnabledValue(){return this._getSettingValue("chat.agent.sandbox.enabled")??"off"}_getSandboxConfiguredWindowsEnabledValue(){return this._getSettingValue("chat.agent.sandbox.enabledWindows")??"off"}_isSandboxAllowNetworkConfigured(){return this._os===1?this._getSandboxConfiguredWindowsEnabledValue()==="allowNetwork":this._getSandboxConfiguredEnabledValue()==="allowNetwork"}_areUnsandboxedCommandsAllowed(){return this._getSettingValue("chat.agent.sandbox.allowUnsandboxedCommands")===!0}_areRetryWithAllowNetworkRequestsAllowed(){return this._getSettingValue("chat.agent.sandbox.retryWithAllowNetworkRequests")===!0}_getSettingValue(e){return this._host.getSandboxSetting(e)}};Jt=w([C(1,Se),C(2,L),C(3,vu)],Jt);var uP="tmp",mm=class{constructor(t,e,n,i,o,s){this._sessionId=t;this._workingDirectory=e;this._environmentService=n;this._productService=i;this._agentConfigurationService=o;this.onDidChangeRoots=Q.None;this._sandboxHelper=s,this.onDidChangeSandboxSettings=this._agentConfigurationService.onDidRootConfigChange}async getOS(){return mt}async getRuntimeInfo(){let t=de(rt.asFileUri("").path),e=!!process.versions.electron;return{appRoot:t,execPath:process.execPath,runAsNode:e}}async getUserHome(){return this._environmentService.userHome}async getSandboxTempDir(){let t=this._environmentService.userHome;if(!t)return;let e=y.joinPath(t,this._productService.dataFolderName,uP);return y.joinPath(e,`agenthost_${this._sessionId}`)}async getWorkspaceStorageReadRoot(){}getWriteRoots(){return this._workingDirectory?[this._workingDirectory]:[]}async checkSandboxDependencies(){return this._sandboxHelper.checkSandboxDependencies()}async getWindowsMxcFilesystemPolicy(){return this._sandboxHelper.getWindowsMxcFilesystemPolicy()}async getWindowsMxcEnvironment(){return this._sandboxHelper.getWindowsMxcEnvironment()}async buildWindowsMxcSandboxPayload(t,e,n,i,o){return this._sandboxHelper.buildWindowsMxcSandboxPayload(t,e,n,i,o)}getSandboxSetting(t){let e=Db[t];return e===void 0?void 0:this._agentConfigurationService.getRootValue(ka,"sandbox")?.[e]}};function m_(r,t,e,n,i,o,s){let a=new mm(o,s,t,e,n,i);return r.createInstance(Jt,a)}var h_=8e4,pP=12e4,hm="<<<COPILOT_SENTINEL_",fP="The command opened the alternate buffer and is still running in the terminal. It likely launched an interactive terminal UI. Use write_bash/write_powershell to interact with it, or shutdown the shell to stop it.";function gP(r){let t=Math.max(r.lastIndexOf("/"),r.lastIndexOf("\\"));switch(r.slice(t+1).toLowerCase().replace(/\.exe$/,"")){case"pwsh":case"powershell":case"pwsh-preview":return"powershell";case"bash":case"sh":case"zsh":case"fish":case"csh":case"ksh":case"nu":case"xonsh":case"git-cmd":case"wsl":case"ubuntu":case"ubuntu1804":case"kali":case"debian":case"opensuse-42":case"sles-12":return"bash";default:return K?"powershell":"bash"}}var Rr=class extends T{constructor(e,n,i,o,s,a,l,c,u){super();this._sessionUri=e;this.workingDirectory=n;this._terminalManager=i;this._logService=o;this._instantiationService=s;this._environmentService=a;this._productService=l;this._agentConfigurationService=c;this._sandboxHelper=u;this._shells=new Map;this._toolCallShells=new Map;this._busyShellIds=new Set;this._heldShellReleaseListeners=new Map;this._onDidAssociateTerminal=this._register(new x);this.onDidAssociateTerminal=this._onDidAssociateTerminal.event;this._register(A(()=>{for(let d of this._heldShellReleaseListeners.values())d.dispose();this._heldShellReleaseListeners.clear();for(let d of this._shells.values())this._terminalManager.hasTerminal(d.terminalUri)&&this._terminalManager.disposeTerminal(d.terminalUri);this._shells.clear(),this._toolCallShells.clear(),this._busyShellIds.clear()}))}getResolvedExecutable(){return this._resolvedExecutable||(this._resolvedExecutable=this._terminalManager.getDefaultShell()),this._resolvedExecutable}getOrCreateSandboxEngine(){if(!this._sandboxEngine){let e=this._sessionUri.path.split("/").pop()??q(),n=m_(this._instantiationService,this._environmentService,this._productService,this._agentConfigurationService,this._sandboxHelper,e,this.workingDirectory);this._register(n),this._register(A(()=>{n.cleanupTempDir().catch(i=>this._logService.warn("[ShellManager] Sandbox temp dir cleanup failed",i))})),this._sandboxEngine=n}return this._sandboxEngine}async getOrCreateShell(e,n,i,o){for(let f of this._shells.values()){if(f.shellType!==e||!this._terminalManager.hasTerminal(f.terminalUri))continue;if(this._terminalManager.getExitCode(f.terminalUri)!==void 0){this._shells.delete(f.id);continue}if(!this._busyShellIds.has(f.id))return this._busyShellIds.add(f.id),this._trackToolCall(i,f.id),this._makeReference(f)}let s=q(),a=`agenthost-terminal://shell/${s}`,l={kind:"session",session:this._sessionUri.toString(),turnId:n,toolCallId:i},c=e==="bash"?"Bash":"PowerShell",u=await this.getResolvedExecutable();await this._terminalManager.createTerminal({channel:a,claim:l,name:c,cwd:o??this.workingDirectory?.fsPath},{shell:u,preventShellHistory:!0,nonInteractive:!0});let d={id:s,terminalUri:a,shellType:e,executable:u};return this._shells.set(s,d),this._busyShellIds.add(s),this._trackToolCall(i,s),this._logService.info(`[ShellManager] Created ${e} shell ${s} (terminal=${a},  executable=${u})`),this._makeReference(d)}_makeReference(e){let n=!1;return{object:e,dispose:()=>{n||(n=!0,this._busyShellIds.delete(e.id))}}}holdShellUntilCommandFinishes(e){if(this._heldShellReleaseListeners.has(e.id))return;let n=new z,i=()=>{this._busyShellIds.delete(e.id),this._heldShellReleaseListeners.delete(e.id),n.dispose()};n.add(this._terminalManager.onCommandFinished(e.terminalUri,i)),n.add(this._terminalManager.onExit(e.terminalUri,i)),this._heldShellReleaseListeners.set(e.id,n)}_trackToolCall(e,n){this._toolCallShells.set(e,n);let i=this._shells.get(n);if(i){let o=i.shellType==="bash"?"Bash":"PowerShell";this._onDidAssociateTerminal.fire({toolCallId:e,terminalUri:i.terminalUri,displayName:o})}}getTerminalUriForToolCall(e){let n=this._toolCallShells.get(e);if(n)return this._shells.get(n)?.terminalUri}getShell(e){return this._shells.get(e)}listShells(){let e=[];for(let n of this._shells.values())this._terminalManager.hasTerminal(n.terminalUri)&&e.push(n);return e}shutdownShell(e){let n=this._shells.get(e);return n?(this._heldShellReleaseListeners.get(e)?.dispose(),this._heldShellReleaseListeners.delete(e),this._terminalManager.disposeTerminal(n.terminalUri),this._shells.delete(e),this._busyShellIds.delete(e),this._logService.info(`[ShellManager] Shut down shell ${e}`),!0):!1}};Rr=w([C(2,Po),C(3,L),C(4,qe),C(5,Ma),C(6,Lt),C(7,Je),C(8,hu)],Rr);function mP(){return q().replace(/-/g,"")}function hP(r,t){return t==="powershell"?`Write-Output "${hm}${r}_EXIT_$LASTEXITCODE>>>"`:`echo "${hm}${r}_EXIT_$?>>>"`}function y_(r){return r==="powershell"?"":" "}function yP(r){let t=r.replace(/\r\n|\r/g,`
`);return/(?<!\\)\n/.test(t)}function v_(r){return Ye||yP(r)}function vP(r,t){let e=`${hm}${t}_EXIT_`,n=r.indexOf(e);if(n===-1)return{found:!1,exitCode:-1,outputBeforeSentinel:r};let i=r.substring(0,n),o=r.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:i}}function Er(r){let t=py(r).trim();return t.length>h_&&(t=t.substring(t.length-h_)),t}function Mn(r){return{textResultForLlm:r,resultType:"success"}}function St(r,t){return{textResultForLlm:r,resultType:"failure",error:t}}function Nn(r,t){return{toolResult:r,keepShellBusy:t?.keepShellBusy}}function b_(r){return Nn(Mn(r),{keepShellBusy:!0})}function bP(){return Nn(St(fP,"alternateBuffer"),{keepShellBusy:!0})}function S_(r,t,e,n,i){t.createAltBufferPromise(r.terminalUri,n).then(()=>{e.info("[ShellTool] Command entered alternate buffer"),i(bP())})}async function SP(r,t,e,n,i){let o=n.supportsCommandDetection(r.terminalUri)?await IP(r,t,e,n,i):await _P(r,t,e,n,i);return{...o,toolResult:{...o.toolResult,textResultForLlm:`Shell ID: ${r.id}
${o.toolResult.textResultForLlm}`}}}async function IP(r,t,e,n,i){let o=new z,s=new Promise(a=>{let l=!1,c=d=>{l||(l=!0,o.dispose(),a(d))};o.add(n.onCommandFinished(r.terminalUri,d=>{let f=Er(d.output),m=d.exitCode??0;i.info(`[ShellTool] Command completed (shell integration) with exit code ${m}`),c(Nn(m===0?Mn(`Exit code: ${m}
${f}`):St(`Exit code: ${m}
${f}`)))})),S_(r,n,i,o,c),o.add(n.onExit(r.terminalUri,d=>{i.info(`[ShellTool] Shell exited unexpectedly with code ${d}`);let f=n.getContent(r.terminalUri)??"",m=Er(f);c(Nn(St(`Shell exited with code ${d}
${m}`)))})),o.add(n.onClaimChanged(r.terminalUri,d=>{d.kind==="session"&&!d.toolCallId&&(i.info("[ShellTool] Continuing in background (claim narrowed)"),c(b_("The user chose to continue this command in the background. The terminal is still running.")))}));let u=setTimeout(()=>{i.warn(`[ShellTool] Command timed out after ${e}ms`);let d=n.getContent(r.terminalUri)??"",f=Er(d);c(Nn(St(`Command timed out after ${Math.round(e/1e3)}s. Partial output:
${f}`,"timeout")))},e);o.add(A(()=>clearTimeout(u)))});try{await n.sendText(r.terminalUri,`${y_(r.shellType)}${t}`,{shouldExecute:!0,bracketedPasteMode:v_(t)})}catch(a){throw o.dispose(),a}return s}async function _P(r,t,e,n,i){let o=mP(),s=hP(o,r.shellType),a=new z,c=(n.getContent(r.terminalUri)??"").length,u=new Promise(d=>{let f=!1,m=S=>{f||(f=!0,a.dispose(),d(S))},h=()=>{let S=n.getContent(r.terminalUri)??"",_=Math.min(c,S.length),b=S.substring(_),I=vP(b,o);if(I.found){let R=Er(I.outputBeforeSentinel);i.info(`[ShellTool] Command completed with exit code ${I.exitCode}`),I.exitCode===0?m(Nn(Mn(`Exit code: ${I.exitCode}
${R}`))):m(Nn(St(`Exit code: ${I.exitCode}
${R}`)))}};a.add(n.onData(r.terminalUri,()=>{h()})),S_(r,n,i,a,m),a.add(n.onExit(r.terminalUri,S=>{i.info(`[ShellTool] Shell exited unexpectedly with code ${S}`);let b=(n.getContent(r.terminalUri)??"").substring(c),I=Er(b);m(Nn(St(`Shell exited with code ${S}
${I}`)))})),a.add(n.onClaimChanged(r.terminalUri,S=>{S.kind==="session"&&!S.toolCallId&&(i.info("[ShellTool] Continuing in background (claim narrowed)"),m(b_("The user chose to continue this command in the background. The terminal is still running.")))}));let v=setTimeout(()=>{i.warn(`[ShellTool] Command timed out after ${e}ms`);let _=(n.getContent(r.terminalUri)??"").substring(c),b=Er(_);m(Nn(St(`Command timed out after ${Math.round(e/1e3)}s. Partial output:
${b}`,"timeout")))},e);a.add(A(()=>clearTimeout(v))),h()});try{await n.sendText(r.terminalUri,`${y_(r.shellType)}${t}`,{shouldExecute:!0,bracketedPasteMode:v_(t)}),await n.sendText(r.terminalUri,s,{shouldExecute:!0})}catch(d){throw a.dispose(),d}return u}async function I_(r,t,e,n){let i=await r.getResolvedExecutable(),o=gP(i),s=r.getOrCreateSandboxEngine(),a=await s.isEnabled(),l=a?s.getResolvedNetworkDomains():void 0,c={name:o,description:o==="bash"?qc(i)?wP(a,l):xP(a,l):TP(o,i,a,l),parameters:{type:"object",properties:{command:{type:"string",description:"The command to execute"},timeout:{type:"number",description:"Timeout in milliseconds (default 120000)"},...a?{requestUnsandboxedExecution:{type:"boolean",description:"Request that this command run outside the sandbox. Only set this after first executing the command in the sandbox and observing that sandboxing caused the failure. The user will be prompted before the command runs unsandboxed."},requestUnsandboxedExecutionReason:{type:"string",description:"A short explanation of the sandboxed execution failure or blocked-domain requirement that justifies retrying outside the sandbox. Only provide this when requestUnsandboxedExecution is true."}}:{}},required:["command"]},overridesBuiltInTool:!0,handler:async(_,b)=>{let I=_.timeout??pP,R=await r.getOrCreateShell(o,b.toolCallId,b.toolCallId),P=!0;try{let j=_.command;if(a){if(_.requestUnsandboxedExecution&&!s.areUnsandboxedCommandsAllowed())return St("Unsandboxed execution is disabled by the chat.agent.sandbox.allowUnsandboxedCommands setting.","unsandboxed_disabled");let M=s.isAutoApproveUnsandboxedCommands(),O=async te=>{if(M)return!0;if(!n){let Ls=te?.join(", ")??"(unknown)";return St(`Command requires approval to run outside the sandbox. Blocked domains: ${Ls}. Re-run with requestUnsandboxedExecution=true and requestUnsandboxedExecutionReason explaining why unsandboxed access is required.`,"sandbox_blocked")}return await n({toolCallId:b.toolCallId,toolName:b.toolName,shellExecutable:i,command:_.command,reason:_.requestUnsandboxedExecutionReason,blockedDomains:te})},G=await s.wrapCommand(_.command,_.requestUnsandboxedExecution,i,R.object.shellType==="bash"?r.workingDirectory:void 0);if(_.requestUnsandboxedExecution&&!G.isSandboxWrapped){let te=await O(G.blockedDomains);if(typeof te!="boolean")return te;if(!te){let ye=G.blockedDomains?.join(", ")??"(none)";return St(`User declined to run command outside the sandbox. Blocked domains: ${ye}.`,"sandbox_blocked")}}if(G.requiresUnsandboxConfirmation){let te=await O(G.blockedDomains);if(typeof te!="boolean")return te;if(!te){let ye=G.blockedDomains?.join(", ")??"(unknown)";return St(`User declined to run command outside the sandbox. Blocked domains: ${ye}.`,"sandbox_blocked")}G=await s.wrapCommand(_.command,!0,i,R.object.shellType==="bash"?r.workingDirectory:void 0)}j=G.command}let E=await SP(R.object,j,I,t,e);return E.keepShellBusy&&(P=!1,r.holdShellUntilCommandFinishes(R.object)),E.toolResult}finally{P&&R.dispose()}}},u={name:`read_${o}`,description:`Read the latest output from a running ${o} shell.`,parameters:{type:"object",properties:{shell_id:{type:"string",description:"Shell ID to read from (optional; uses latest shell if omitted)"}}},overridesBuiltInTool:!0,skipPermission:!0,handler:_=>{let b=r.listShells(),I=_.shell_id?r.getShell(_.shell_id):b[b.length-1];if(!I)return St("No active shell found.","no_shell");let R=t.getContent(I.terminalUri);return Mn(R?Er(R):"(no output)")}},d={name:`write_${o}`,description:`Send input to a running ${o} 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,skipPermission:!0,handler:async _=>{let b=r.listShells(),I=b[b.length-1];return I?(await t.sendText(I.terminalUri,_.command,{shouldExecute:!1}),Mn("Input sent to shell.")):St("No active shell found.","no_shell")}},f={name:o==="bash"?"bash_shutdown":`${o}_shutdown`,description:`Stop a ${o} shell.`,parameters:{type:"object",properties:{shell_id:{type:"string",description:"Shell ID to stop (optional; stops latest shell if omitted)"}}},overridesBuiltInTool:!0,skipPermission:!0,handler:_=>{if(_.shell_id)return r.shutdownShell(_.shell_id)?Mn("Shell stopped."):St("Shell not found.","not_found");let b=r.listShells(),I=b[b.length-1];return I?(r.shutdownShell(I.id),Mn("Shell stopped.")):St("No active shell to stop.","no_shell")}},m={name:`list_${o}`,description:`List active ${o} shell instances.`,parameters:{type:"object",properties:{}},overridesBuiltInTool:!0,skipPermission:!0,handler:()=>{let _=r.listShells();if(_.length===0)return Mn("No active shells.");let b=_.map(I=>{let R=t.getExitCode(I.terminalUri),P=R!==void 0?`exited (${R})`:"running";return`- ${I.id}: ${I.shellType} [${P}]`});return Mn(b.join(`
`))}},h=o==="bash"?"powershell":"bash",v=`This tool is disabled because the configured shell is ${i}. Use the \`${o}\` tool instead.`;return[c,u,d,f,m,{name:h,description:v,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,skipPermission:!0,handler:()=>St(v,"wrong_shell")}]}function CP(r){return r.endsWith("System32\\WindowsPowerShell\\v1.0\\powershell.exe")}function TP(r,t,e,n){let i=CP(t),o=[`This tool allows you to execute ${i?"Windows PowerShell 5.1":"PowerShell"} commands in a persistent terminal session, preserving environment variables, working directory, and other context across multiple commands.`,"","Command Execution:",i?"- Use semicolons ; to chain commands on one line, NEVER use && even when asked explicitly":"- Prefer ; when chaining commands on one line","- Prefer pipelines | for object-based data flow",'- Never create a sub-shell (eg. powershell -c "command") unless explicitly asked',"","Directory Management:","- Prefer relative paths when navigating directories, only use absolute when the path is far away or the current cwd is not expected","- By default (mode=sync), shell and cwd are reused by subsequent sync commands","- Use $PWD or Get-Location for current directory","- Use Push-Location/Pop-Location for directory stack","","Program Execution:","- Supports .NET, Python, Node.js, and other executables","- Install modules via Install-Module, Install-Package","- Use Get-Command to verify cmdlet/function availability","","Async Mode:","- For long-running tasks (e.g., servers), use mode=async","- Returns a terminal ID for checking status and runtime later","- Use Start-Job for background PowerShell jobs","",`Use write_${r} to send commands or input to a terminal session.`];return e&&o.push(...__(n)),o.push("","Output Management:","- Output is automatically truncated if longer than 60KB to prevent context overflow","- Use Select-Object, Where-Object, Format-Table to filter output","- Use -First/-Last parameters to limit results","- For pager commands, add | Out-String or | Format-List","","Best Practices:","- Use proper cmdlet names instead of aliases in scripts",'- Quote paths with spaces: "C:\\Path With Spaces"',"- Prefer PowerShell cmdlets over external commands when available","- Prefer idiomatic PowerShell like Get-ChildItem instead of dir or ls for file listings","- Use Test-Path to check file/directory existence","- Be specific with Select-Object properties to avoid excessive output","- Avoid printing credentials unless absolutely required","","Interactive Input Handling:","- When a terminal command is waiting for interactive input, do NOT suggest alternatives or ask the user whether to proceed. Instead, use the ask_user tool to collect the needed values from the user, then send them.",`- Send exactly one answer per prompt using write_${r}. Never send multiple answers in a single send.`,`- After each send, call read_${r} to read the next prompt before sending the next answer.`,"- Continue one prompt at a time until the command finishes."),o.join(`
`)}function __(r){let t=["","Sandboxing:","- ATTENTION: Terminal sandboxing is enabled, commands run in a sandbox by default","- When executing commands within the sandboxed environment, all operations requiring a temporary directory must utilize the $TMPDIR environment variable. The /tmp directory is not guaranteed to be accessible or writable and must be avoided","- Tools and scripts should respect the TMPDIR environment variable, which is automatically set to an appropriate path within the sandbox","- When a command fails due to sandbox restrictions, immediately re-run it with requestUnsandboxedExecution=true. Do NOT ask the user for permission \u2014 setting this flag automatically shows a confirmation prompt to the user","- Only set requestUnsandboxedExecution=true when there is evidence of failures caused by the sandbox, e.g. 'Operation not permitted' errors, network failures, or file access errors, etc","- Do NOT set requestUnsandboxedExecution=true without first executing the command in sandbox mode. Always try the command in the sandbox first, and only set requestUnsandboxedExecution=true when retrying after that sandboxed execution failed due to sandbox restrictions.","- When setting requestUnsandboxedExecution=true, also provide requestUnsandboxedExecutionReason explaining why the command needs unsandboxed access"];if(r){let e=new Set(r.deniedDomains),n=r.allowedDomains.filter(i=>!e.has(i));n.length===0?t.push("- All network access is blocked in the sandbox"):t.push(`- Only the following domains are accessible in the sandbox (all other network access is blocked): ${n.join(", ")}`),r.deniedDomains.length>0&&t.push(`- The following domains are explicitly blocked in the sandbox: ${r.deniedDomains.join(", ")}`)}return t}function C_(r,t,e){let n=[`
Command Execution:
- Use && to chain simple commands on one line
- Prefer pipelines | over temporary files for data flow
- Never create a sub-shell (eg. bash -c "command") unless explicitly asked

Directory Management:
- Prefer relative paths when navigating directories, only use absolute when the path is far away or the current cwd is not expected
- By default (mode=sync), shell and cwd are reused by subsequent sync commands
- Use $PWD for current directory references
- Consider using pushd/popd for directory stack management
- Supports directory shortcuts like ~ and -

Program Execution:
- Supports Python, Node.js, and other executables
- Install packages via package managers (brew, apt, etc.)
- Use which or command -v to verify command availability

Async Mode:
- For long-running tasks (e.g., servers), use mode=async
- Returns a terminal ID for checking status and runtime later

Use write_${r} to send commands or input to a terminal session.`];return t&&n.push(__(e).join(`
`)),n.push(`

Output Management:
- Output is automatically truncated if longer than 60KB to prevent context overflow
- Use head, tail, grep, awk to filter and limit output size
- For pager commands, disable paging: git --no-pager or add | cat
- Use wc -l to count lines before displaying large outputs

Best Practices:
- Quote variables: "$var" instead of $var to handle spaces
- Use find with -exec or xargs for file operations
- Be specific with commands to avoid excessive output
- Avoid printing credentials unless absolutely required
- NEVER run sleep or similar wait commands in a terminal. You will be automatically notified on your next turn when async terminal commands or timed-out sync commands complete or need input. Do NOT poll for completion.

Interactive Input Handling:
- When a terminal command is waiting for interactive input, do NOT suggest alternatives or ask the user whether to proceed. Instead, use the ask_user tool to collect the needed values from the user, then send them.
- Send exactly one answer per prompt using write_${r}. Never send multiple answers in a single send.
- After each send, call read_${r} to read the next prompt before sending the next answer.
- Continue one prompt at a time until the command finishes.`),n.join("")}function xP(r,t){return["This tool allows you to execute shell commands in a persistent bash terminal session, preserving environment variables, working directory, and other context across multiple commands.",C_("bash",r,t),"- Use [[ ]] for conditional tests instead of [ ]","- Prefer $() over backticks for command substitution","- Use set -e at start of complex commands to exit on errors"].join(`
`)}function wP(r,t){return["This tool allows you to execute shell commands in a persistent zsh terminal session, preserving environment variables, working directory, and other context across multiple commands.",C_("bash",r,t),"- Use type to check command type (builtin, function, alias)","- Use jobs, fg, bg for job control","- Use [[ ]] for conditional tests instead of [ ]","- Prefer $() over backticks for command substitution","- Take advantage of zsh globbing features (**, extended globs). Note: unmatched globs fail by default (zsh: no matches found) - use a glob qualifier like *(N) or quote the glob if it should be literal","","zsh pitfalls - these WILL cause errors or hangs:","- NEVER use bare == or === as separators (e.g. echo === triggers zsh equals expansion). Quote them: echo '==='","- NEVER use status as a variable name (it is read-only in zsh). Use exit_code or ret instead"].join(`
`)}var RP=5;var EP=".md",PP=".instructions.md",kP="SKILL.md",AP="README.md";function T_(r,t){return{workspace:[{path:[".github","agents"],type:"agent"},{path:[".agents","agents"],type:"agent"},{path:[".claude","agents"],type:"agent"},{path:[".github","skills"],type:"skill"},{path:[".agents","skills"],type:"skill"},{path:[".claude","skills"],type:"skill"},{path:[".github","instructions"],type:"instruction"}],user:[{path:[".copilot","agents"],type:"agent"},{path:[".agents","skills"],type:"skill"},{path:[".copilot","instructions"],type:"instruction"}]}}var DP=100,ss=class extends T{constructor(e,n,i,o){super();this._workingDirectory=e;this._userHome=n;this._fileService=i;this._logService=o;this._onDidChange=this._register(new x);this.onDidChange=this._onDidChange.event;this._watchers=this._register(new z);this._refreshDelayer=this._register(new ar(DP));let{workspace:s,user:a}=T_(this._workingDirectory,this._userHome);this._rootUris=[...s.map(l=>ee(this._workingDirectory,...l.path)),...a.map(l=>ee(this._userHome,...l.path))],this._register(this._fileService.onDidFilesChange(l=>{this._rootUris.some(c=>l.affects(c))&&this._scheduleRefresh()}))}directories(){return this._cached||(this._cached=this._scan()),this._cached}refresh(){this._cached=void 0,this._watchers.clear()}_scheduleRefresh(){this._refreshDelayer.trigger(()=>{this.refresh(),this._onDidChange.fire()}).catch(()=>{})}async _scan(){this._watchers.clear();let e=new Il,n=[],{workspace:i,user:o}=T_(this._workingDirectory,this._userHome);return await Promise.all([...i.map(s=>this._scanRoot(this._workingDirectory,s,e,n)),...o.map(s=>this._scanRoot(this._userHome,s,e,n))]),n}async _scanRoot(e,n,i,o){let s=ee(e,...n.path),a;try{a=await this._fileService.resolve(s,{resolveMetadata:!0})}catch{return}if(!(!a.isDirectory||!a.children)){try{let l=n.type==="skill"||n.type==="instruction";this._watchers.add(this._fileService.watch(s,{recursive:l,excludes:[]}))}catch(l){this._logService.warn(`[SessionCustomizationDiscovery] Failed to watch '${s.toString()}': ${l instanceof Error?l.message:String(l)}`)}if(n.type==="skill"){let l=[];for(let c of a.children)if(c.isDirectory){let u=ee(c.resource,kP);try{(await this._fileService.resolve(u,{resolveMetadata:!1})).isFile&&!i.has(u)&&(i.add(u),l.push(u))}catch{}}o.push({uri:s,type:n.type,files:l})}else if(n.type==="agent"){let l=[];for(let c of a.children)if(c.isFile){let u=c.name;u.endsWith(EP)&&u!==AP&&!i.has(c.resource)&&(i.add(c.resource),l.push(c.resource))}o.push({uri:s,type:n.type,files:l})}else if(n.type==="instruction"){let l=[],c=async(u,d)=>{for(let f of u.children??[])if(f.isFile)f.name.toLowerCase().endsWith(PP)&&!i.has(f.resource)&&(i.add(f.resource),l.push(f.resource));else if(f.isDirectory&&d<RP){let m;try{m=await this._fileService.resolve(f.resource,{resolveMetadata:!0})}catch{}m&&await c(m,d+1)}};await c(a,0),o.push({uri:s,type:n.type,files:l})}else this._logService.warn(`[SessionCustomizationDiscovery] Unrecognized root type '${n.type}' for root '${s.toString()}'`)}}};ss=w([C(2,Se),C(3,L)],ss);var x_="VS Code Synced Data",LP="host-discovery",MP=JSON.stringify({name:x_,description:"Customization data discovered from this workspace and your home directory"},null,"	");function NP(r){switch(r){case"agent":return"agents";case"skill":return"skills";case"instruction":return"rules"}}var as=class extends T{constructor(e,n,i){super();this._fileService=n;let o=`host-${ht(e.toString())}`;this._rootUri=y.joinPath(i.basePath,LP,o)}get rootUri(){return this._rootUri}get lastNonce(){return this._lastNonce}async bundle(e){if(e.length===0)return;try{await this._fileService.del(this._rootUri,{recursive:!0})}catch{}let n=y.joinPath(this._rootUri,".plugin","plugin.json");await this._fileService.writeFile(n,k.fromString(MP));let i=[];for(let a of e){let l=NP(a.type);for(let c of a.files){let u=pe(c),d,f;if(a.type==="skill"){let h=pe(vn(c));d=y.joinPath(this._rootUri,l,h,u),f=`${l}/${h}/${u}`}else d=y.joinPath(this._rootUri,l,u),f=`${l}/${u}`;let m=await this._fileService.readFile(c);await this._fileService.writeFile(d,m.value),i.push(`${f}:${m.value.toString()}`)}}i.sort();let o=String(ht(i.join(`
`)));this._lastNonce=o;let s=this._rootUri.toString();return{ref:{type:"plugin",id:Gt(s),uri:s,name:x_,enabled:!0,nonce:o}}}};as=w([C(1,Se),C(2,Dn)],as);function w_(r){let t=new Map;if(r){for(let n of r)if(!(n.enabled===!1||!n.children))for(let i of n.children){if(i.type!=="agent")continue;let o=i.uri.toString();t.has(o)||t.set(o,i)}}let e=[...t.values()];return e.sort((n,i)=>n.name.localeCompare(i.name)||n.uri.toString().localeCompare(i.uri.toString())),e}var R_="thinkingLevel",WP=["low","medium","high","xhigh"],$P={mode:"customize",sections:{identity:{action:"replace",content:"You are an AI assistant using Copilot CLI runtime in VS Code. You help users with software engineering tasks. When asked about your identity, you must state that you are an AI assistant using Copilot CLI runtime in VS Code."}}};function VP(r){return WP.some(t=>t===r)}function BP(r){return y.joinPath(r,"..",`${_e(r.fsPath)}.worktrees`)}function HP(r){return r.replace(/\//g,"-")}function zP(r,t){return`agents/${t?`${t}-${r.substring(0,8)}`:r}`}function qP(r){let e=r.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").split("-").filter(n=>n.length>0).slice(0,8).join("-").slice(0,48).replace(/-+$/g,"");return e.length>0?e:void 0}function E_(r){return g(1998,null,He(r))+`

`}function KP(r,t){if(r.length===0)return r;let e=r.slice(),n=e[0],i=n.responseParts[0];if(i?.kind==="markdown"){let o=n.responseParts.slice();o[0]={...i,content:t+i.content},e[0]={...n,responseParts:o}}else{let o=[{kind:"markdown",id:q(),content:t},...n.responseParts];e[0]={...n,responseParts:o}}return e}var me=class extends T{constructor(e,n,i,o,s,a,l,c,u,d){super();this._logService=e;this._instantiationService=n;this._fileService=i;this._sessionDataService=o;this._gitService=s;this._terminalManager=a;this._configurationService=l;this._otelService=c;this._checkpointService=d;this.id="copilotcli";this._onDidSessionProgress=this._register(new x);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidMaterializeSession=this._register(new x);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._models=In(this,[]);this.models=this._models;this._sessions=this._register(new We);this._resumingSessions=new Map;this._provisionalSessions=new Map;this._createdWorktrees=new Map;this._pendingFirstTurnAnnouncements=new Map;this._sessionSequencer=new Ze;this._activeClients=new Fe;this._lastSessionSyncEnabled=this._isSessionSyncEnabled();this._plugins=this._register(this._instantiationService.createInstance(rl)),this.onDidCustomizationsChange=this._plugins.onDidChange,this._register(u.registerProvider(new iu(this.id,{hasHistory:f=>!this._provisionalSessions.has(f)&&this._sessions.has(f)}))),this._register(this._configurationService.onDidRootConfigChange(()=>{this._restartClientIfSessionSyncChanged().catch(f=>this._logService.error("[Copilot] Failed to restart client after session sync change",f))}))}static{this._BRANCH_COMPLETION_LIMIT=25}_isSessionSyncEnabled(){return this._configurationService.getRootValue(Pa,ig)===!0}async _restartClientIfSessionSyncChanged(){let e=this._isSessionSyncEnabled();this._lastSessionSyncEnabled!==e&&(this._lastSessionSyncEnabled=e,this._client&&this._sessions.size===0&&(this._logService.info(`[Copilot] Session sync changed to ${e}, restarting CopilotClient`),await this._stopClient()))}_createCopilotClient(e){return new UP(e)}getDescriptor(){return{provider:"copilotcli",displayName:"Copilot CLI",description:"Copilot SDK agent running in a dedicated process"}}getProtectedResources(){return[lo]}getCustomizations(){return this._plugins.getConfiguredHostCustomizations()}async getSessionCustomizations(e){return this._plugins.getSessionCustomizationsSettled(await this._getSessionCustomizationDirectory(e))}async _getSessionCustomizationDirectory(e){let n=H.id(e),i=this._provisionalSessions.get(n);if(i)return i.workingDirectory;let o=this._sessions.get(n),s=o?void 0:await this._readSessionMetadata(e);return o?.customizationDirectory??s?.customizationDirectory??s?.workingDirectory}async authenticate(e,n){if(e!==lo.resource)return!1;let i=this._githubToken!==n;return this._githubToken=n,this._logService.info(`[Copilot] Auth token ${i?"updated":"unchanged"}`),i&&this._client&&this._sessions.size===0&&(this._logService.info("[Copilot] Restarting CopilotClient with new token"),await this._stopClient()),i&&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()}_enablePlanModeOnClient(e){let n=e.connection;if(!n){this._logService.warn("[Copilot] Could not enable plan mode: client.connection is null");return}if(typeof n.sendRequest!="function"){this._logService.warn(`[Copilot] Could not enable plan mode: client.connection.sendRequest is ${typeof n.sendRequest}`);return}if(typeof n.onRequest!="function"){this._logService.warn(`[Copilot] Could not enable plan mode: client.connection.onRequest is ${typeof n.onRequest}`);return}let i=n.sendRequest.bind(n);n.sendRequest=(s,a)=>(s==="session.create"||s==="session.resume")&&a&&typeof a=="object"?i(s,{...a,requestExitPlanMode:!0}):i(s,a);let o=n.onRequest("exitPlanMode.request",async s=>{let a=this._sessions.get(s.sessionId);return a?a.handleExitPlanModeRequest(s):(this._logService.warn(`[Copilot] exitPlanMode.request for unknown session ${s.sessionId}`),{approved:!1})});this._register(A(()=>o.dispose()))}async _ensureClient(){let e=this._githubToken;if(!e)throw new N(Io,"Authentication is required to use Copilot",this.getProtectedResources());if(this._client)return this._client;if(this._clientStarting)return this._clientStarting;let n=(async()=>{this._logService.info("[Copilot] Starting CopilotClient... (with token)");let i=Object.assign({},process.env,{ELECTRON_RUN_AS_NODE:"1"});delete i.NODE_OPTIONS,delete i.VSCODE_INSPECTOR_OPTIONS,delete i.VSCODE_ESM_ENTRYPOINT,delete i.VSCODE_HANDLES_UNCAUGHT_ERRORS;for(let m of Object.keys(i))m!=="ELECTRON_RUN_AS_NODE"&&(m.startsWith("VSCODE_")||m.startsWith("ELECTRON_"))&&delete i[m];i.COPILOT_CLI_RUN_AS_NODE="1",i.USE_BUILTIN_RIPGREP="false";let o=y.joinPath(rt.asFileUri(""),"..","node_modules","@github","copilot","index.js").fsPath,s=await es(),a=de(s),l=Object.keys(i).find(m=>m.toUpperCase()==="PATH")??"PATH",c=i[l];i[l]=c?`${c}${qr}${a}`:a,this._logService.info(`[Copilot] Resolved CLI path: ${o}`);let u=await this._otelService.getSdkTelemetryConfig(),d={gitHubToken:e,useLoggedInUser:!1,connection:FP.forStdio({path:o}),env:i,telemetry:u,enableRemoteSessions:this._isSessionSyncEnabled()},f=this._createCopilotClient(d);if(await f.start(),this._githubToken!==e)throw await f.stop(),new Error("Copilot authentication changed while the client was starting");return this._logService.info("[Copilot] CopilotClient started successfully"),this._enablePlanModeOnClient(f),this._client=f,this._clientStarting=void 0,f})();return this._clientStarting=n,n.catch(()=>{this._clientStarting=void 0}),n}_createThinkingLevelConfigSchema(e,n){if(!e?.length)return;let i=e.map(o=>{switch(o){case"low":return g(1993,null);case"medium":return g(1994,null);case"high":return g(1992,null);case"xhigh":return g(1996,null);default:return o}});return{type:"object",properties:{[R_]:{type:"string",title:g(1995,null),description:g(1991,null),default:n,enum:[...e],enumLabels:i}}}}_getReasoningEffort(e){let n=e?.config?.[R_];return VP(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 i={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&&(i.config=o)}return i}}catch{}return{id:e}}}_serializeAgentSelection(e){return JSON.stringify({uri:e.uri})}_parseAgentSelection(e){if(e)try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.uri=="string")return{uri:n.uri}}catch{}}async _resolveAgentName(e,n,i){for(let l of n.plugins){let c=l.agents.find(u=>u.uri.toString()===i.uri);if(c)return c.name}let o=await this.getSessionCustomizations(e),a=w_(o).find(l=>l.uri.toString()===i.uri);if(a)return a.name}async listSessions(){this._logService.info("[Copilot] Listing sessions...");let n=await(await this._ensureClient()).listSessions(),i=new Gr(4),o=new Map,a=(await Promise.all(n.map(async l=>{let c=H.uri(this.id,l.sessionId),u=await this._readStoredSessionMetadata(c);if(!u)return;let{project:d,resolved:f}=u;f||(d=await this._resolveSessionProject(l.context,i,o),this._storeSessionProjectResolution(c,d));let m=u.workingDirectory??(typeof l.context?.workingDirectory=="string"?y.file(l.context.workingDirectory):void 0);return{session:c,startTime:l.startTime.getTime(),modifiedTime:l.modifiedTime.getTime(),project:d,summary:l.summary,model:u.model,agent:u.agent,workingDirectory:m,customizationDirectory:u.customizationDirectory}}))).filter(l=>l!==void 0);return this._logService.info(`[Copilot] Found ${a.length} sessions`),a}async getSessionMetadata(e){let n=H.id(e),i=await this._readStoredSessionMetadata(e);if(!i)return;let s=await(await this._ensureClient()).getSessionMetadata(n);if(!s)return;let a=i?.project;if(i&&!i.resolved){let c=new Gr(1);a=await this._resolveSessionProject(s?.context,c,new Map),this._storeSessionProjectResolution(e,a)}let l=i?.workingDirectory??(typeof s?.context?.workingDirectory=="string"?y.file(s.context.workingDirectory):void 0);return{session:e,startTime:s?.startTime.getTime()??Date.now(),modifiedTime:s?.modifiedTime.getTime()??Date.now(),project:a,summary:s?.summary,model:i?.model,agent:i?.agent,workingDirectory:l,customizationDirectory:i?.customizationDirectory}}async _listModels(){this._logService.info("[Copilot] Listing models...");let i=(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,_meta:typeof o.billing?.multiplier=="number"?{multiplierNumeric:o.billing.multiplier}:void 0}));return this._logService.info(`[Copilot] Found ${i.length} models`),i}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 l=H.id(e.fork.session);return this._sessionSequencer.queue(l,async()=>{this._logService.info(`[Copilot] Forking session ${l} at turnId=${e.fork.turnId}`);let u=await(this._sessions.get(l)??await this._resumeSession(l)).getNextTurnEventId(e.fork.turnId),f=(await n.rpc.sessions.fork({sessionId:l,...u?{toEventId:u}:{}})).sessionId,m=this._sessionDataService.getSessionDataDirById(f),h=y.joinPath(m,Ca);try{let b=await this._sessionDataService.tryOpenDatabase(e.fork.session);if(b)try{await Pr.mkdir(m.fsPath,{recursive:!0}),await b.object.vacuumInto(h.fsPath)}finally{b.dispose()}}catch(b){this._logService.warn(`[Copilot] Failed to copy session database for fork: ${b instanceof Error?b.message:String(b)}`)}let v=await this._resumeSession(f);e.fork.turnIdMapping&&await v.remapTurnIds(e.fork.turnIdMapping);let S=v.sessionUri;this._logService.info(`[Copilot] Forked session created: ${S.toString()}`);let _=await fi({cwd:e.workingDirectory?.fsPath},this._gitService);return await this._storeSessionMetadata(S,e.model,e.workingDirectory,e.workingDirectory,_,!0),e.agent!==void 0&&await this._storeSessionAgentMetadata(S,e.agent),{session:S,workingDirectory:e.workingDirectory,..._?{project:_}:{}}})}let i=e.session?H.id(e.session):q(),o=H.uri(this.id,i);if(this._sessions.has(i)){this._logService.info(`[Copilot] createSession is a no-op: session already materialized: ${o.toString()}`);let l=await fi({cwd:e.workingDirectory.fsPath},this._gitService);return{session:o,workingDirectory:e.workingDirectory,...l?{project:l}:{}}}let s=this._provisionalSessions.has(i);e.activeClient&&(this._getOrCreateActiveClient(o).updateTools(e.activeClient.clientId,e.activeClient.tools),e.activeClient.customizations!==void 0&&await this._plugins.sync(e.activeClient.clientId,e.activeClient.customizations,e.workingDirectory));let a=await fi({cwd:e.workingDirectory.fsPath},this._gitService);return s||this._provisionalSessions.set(i,{sessionId:i,sessionUri:o,workingDirectory:e.workingDirectory,model:e.model,agent:e.agent,project:a}),this._logService.info(`[Copilot] Session created (provisional): ${o.toString()}`),{session:o,workingDirectory:e.workingDirectory,provisional:!0,...a?{project:a}:{}}}async _materializeProvisional(e,n){let i=this._provisionalSessions.get(e);if(!i)throw new Error(`Cannot materialize unknown provisional session: ${e}`);let o=await this._ensureClient(),s=i.sessionUri,a=this._configurationService.getSessionConfigValues(s.toString()),l={provider:this.id,session:s,workingDirectory:i.workingDirectory,model:i.model,config:a},c=i.workingDirectory,d=await this._getOrCreateActiveClient(s).snapshot(c),f=await this._resolveSessionWorkingDirectory(l,e,n),m=this._instantiationService.createInstance(Rr,s,f),h=this._buildSessionConfig(d,m),v=async b=>{let I=i.agent?await this._resolveAgentName(i.sessionUri,d,i.agent):void 0,R=await o.createSession({model:i.model?.id,reasoningEffort:this._getReasoningEffort(i.model),...I?{agent:I}:{},sessionId:e,streaming:!0,workingDirectory:f?.fsPath,...await h(b)});return new os(R)},S;try{S=this._createAgentSession(v,e,m,f,c,d),await S.initializeSession(),this._registerInitializedSession(e,S)}catch(b){throw S?.dispose(),await this._removeCreatedWorktree(e),b}let _=await fi({cwd:f?.fsPath},this._gitService);return this._provisionalSessions.delete(e),await this._storeSessionMetadata(s,i.model,f,c,_,!0),i.agent!==void 0&&await this._storeSessionAgentMetadata(s,i.agent),this._checkpointService.captureBaseline(s,f).catch(b=>{this._logService.warn(`[Copilot:${e}] Baseline checkpoint capture failed: ${b instanceof Error?b.message:String(b)}`)}),this._logService.info(`[Copilot] Session materialized: ${s.toString()}`),this._onDidMaterializeSession.fire({session:s,workingDirectory:f,project:_}),S}async resolveSessionConfig(e){let n=e.workingDirectory?await this._getGitInfo(e.workingDirectory):void 0,i=bt({type:"string",title:g(1985,null),description:g(1990,null),enum:n?["folder","worktree"]:["folder"],enumLabels:n?[g(1986,null),g(1988,null)]:[g(1986,null)],enumDescriptions:n?[g(1987,null),g(1989,null)]:[g(1987,null)],default:n?"worktree":"folder",readOnly:!n,sessionMutable:!1}),o=n?"worktree":"folder",s=i.validate(e.config?.isolation)?e.config.isolation:o,a,l;if(n){let d=s==="folder";l=s==="worktree"?n.defaultBranch:n.currentBranch,a=bt({type:"string",title:g(1983,null),description:g(1984,null),enum:[l],enumLabels:[l],default:l,enumDynamic:!d,readOnly:d,sessionMutable:!1})}let c=wn({isolation:i,...Mt.definition,...a?{branch:a}:{}}),u=c.validateOrDefault(e.config,{isolation:s,autoApprove:"default",mode:"interactive",...l!==void 0?{branch:l}:{}});return{schema:c.toProtocol(),values:u}}async sessionConfigCompletions(e){return e.property!=="branch"||!e.workingDirectory?{items:[]}:{items:(await this._getBranches(e.workingDirectory,e.query)).map(i=>({value:i,label:i}))}}async setClientCustomizations(e,n,i){let o=await this._getSessionCustomizationDirectory(e);return this._plugins.sync(n,i,o,s=>{this._onDidSessionProgress.fire({kind:"action",session:e,action:s})})}setClientTools(e,n,i){let o=H.id(e),s=this._getOrCreateActiveClient(e),a=this._sessions.has(o);this._logService.info(`[Copilot:${o}] setClientTools: clientId=${n}, tools=[${i.map(l=>l.name).join(", ")||"(none)"}], hasCachedSdkSession=${a}`),s.updateTools(n,i)}onClientToolCallComplete(e,n,i){let o=e,s;for(;s=Ge(o);)o=s.parentSession;let a=H.id(o);this._sessions.get(a)?.handleClientToolCallComplete(n,i)}setCustomizationEnabled(e,n){this._plugins.setEnabled(e,n)}async sendMessage(e,n,i,o){let s=H.id(e);await this._sessionSequencer.queue(s,async()=>{let a;this._provisionalSessions.has(s)?a=await this._materializeProvisional(s,n):a=this._sessions.get(s);let l=this._activeClients.get(e),c=!!a;this._logService.info(`[Copilot:${s}] sendMessage: cachedEntry=${c}, hasActiveClient=${!!l}, activeClientId=${l?"(set)":"(none)"}`),a&&l&&await l.isOutdated(a.appliedSnapshot,a.customizationDirectory)&&(this._logService.info(`[Copilot:${s}] Session config changed (isOutdated=true), refreshing session. snapshotClientId=${a.appliedSnapshot.clientId}`),this._sessions.deleteAndDispose(s),a=void 0),a||this._logService.info(`[Copilot:${s}] No cached entry${c?" (was evicted by isOutdated)":""}, calling _resumeSession`),a??=await this._resumeSession(s),o&&a.resetTurnState(o);let u=this._pendingFirstTurnAnnouncements.get(s);u!==void 0&&(this._pendingFirstTurnAnnouncements.delete(s),a.emitInitialMarkdown(u));try{let d=this._resolveSdkMode(e);await a.send(n,i,o,d)}catch(d){let f=d?.code,m=d instanceof Error?d.message:String(d);throw this._logService.error(`[Copilot:${s}] entry.send() failed: code=${f}, message=${m}, hadCachedEntry=${c}, errorType=${d?.constructor?.name}`),d}})}_resolveSdkMode(e){let n=e.toString(),i=this._configurationService.getEffectiveValue(n,Mt,"mode");if(i==="plan")return"plan";if(i==="interactive")return this._configurationService.getEffectiveValue(n,Mt,"autoApprove")==="autopilot"?"autopilot":"interactive"}setPendingMessages(e,n,i){let o=H.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=Ge(e);if(n){let l=n.parentSession,c;for(;c=Ge(l);)l=c.parentSession;let u=H.id(l),d=this._sessions.get(u)??await this._resumeSession(u).catch(f=>{this._logService.warn(`[Copilot:${u}] Failed to resume root for subagent restore`,f)});return d?d.getSubagentMessages(n.toolCallId):[]}let i=H.id(e);if(this._provisionalSessions.has(i))return[];let o=this._sessions.get(i)??await this._resumeSession(i).catch(l=>{this._logService.warn(`[Copilot:${i}] Failed to resume session for message lookup`,l)});if(!o)return[];let s=await o.getMessages(),a=await this._readWorktreeMetadata(e).catch(l=>{this._logService.warn(`[Copilot:${i}] Failed to read worktree branch metadata`,l)});return a?.branchName?KP(s,E_(a.branchName)):s}async disposeSession(e){let n=H.id(e);await this._sessionSequencer.queue(n,async()=>{await this._destroyAndDisposeSession(n)})}async onArchivedChanged(e,n){let i=H.id(e);await this._sessionSequencer.queue(i,async()=>{n?await this._cleanupWorktreeOnArchive(e,i):await this._recreateWorktreeOnUnarchive(e,i)})}async _cleanupWorktreeOnArchive(e,n){let i=await this._readWorktreeMetadata(e).catch(()=>{});if(!i?.worktreePath||!i.repositoryRoot)return;let{branchName:o,worktreePath:s,repositoryRoot:a}=i;try{await Pr.access(s.fsPath)}catch{this._createdWorktrees.delete(n);return}if(!await this._gitService.branchExists(a,o).catch(()=>!1)){this._logService.info(`[Copilot:${n}] Skipping worktree cleanup: branch '${o}' is missing`);return}if(await this._gitService.hasUncommittedChanges(s).catch(()=>!0)){this._logService.info(`[Copilot:${n}] Skipping worktree cleanup: '${s.fsPath}' has uncommitted changes`);return}try{await this._gitService.removeWorktree(a,s),this._logService.info(`[Copilot:${n}] Removed worktree '${s.fsPath}' on archive`)}catch(u){this._logService.warn(`[Copilot:${n}] Failed to remove worktree '${s.fsPath}' on archive: ${u instanceof Error?u.message:String(u)}`)}finally{this._createdWorktrees.delete(n)}}async _recreateWorktreeOnUnarchive(e,n){let i=await this._readWorktreeMetadata(e).catch(()=>{});if(!i?.worktreePath||!i.repositoryRoot)return;let{branchName:o,worktreePath:s,repositoryRoot:a}=i;try{await Pr.access(s.fsPath);return}catch{}if(!await this._gitService.branchExists(a,o).catch(()=>!1)){this._logService.info(`[Copilot:${n}] Skipping worktree recreation: branch '${o}' is missing`);return}try{await Pr.mkdir(y.joinPath(s,"..").fsPath,{recursive:!0}),await this._gitService.addExistingWorktree(a,s,o),this._createdWorktrees.set(n,{repositoryRoot:a,worktree:s}),this._logService.info(`[Copilot:${n}] Recreated worktree '${s.fsPath}' on unarchive`)}catch(c){this._logService.warn(`[Copilot:${n}] Failed to recreate worktree '${s.fsPath}' on unarchive: ${c instanceof Error?c.message:String(c)}`)}}async abortSession(e){let n=H.id(e);await this._sessionSequencer.queue(n,async()=>{let i=this._sessions.get(n);i&&await i.abort()})}async truncateSession(e,n){let i=H.id(e);this._provisionalSessions.has(i)||await this._sessionSequencer.queue(i,async()=>{this._logService.info(`[Copilot:${i}] Truncating session${n!==void 0?` at turnId=${n}`:" (all turns)"}`);let o=this._sessions.get(i)??await this._resumeSession(i),s;n?s=await o.getNextTurnEventId(n):s=await o.getFirstTurnEventId(),s?await o.truncateAtEventId(s,n):this._logService.info(`[Copilot:${i}] No event ID found for truncation, nothing to truncate`),this._logService.info(`[Copilot:${i}] Session truncated`)})}async changeModel(e,n){let i=H.id(e),o=this._provisionalSessions.get(i);if(o){o.model=n;return}let s=this._sessions.get(i);s&&await s.setModel(n.id,this._getReasoningEffort(n)),await this._storeSessionMetadata(e,n,void 0,void 0,void 0)}async changeAgent(e,n){let i=H.id(e),o=this._provisionalSessions.get(i);if(o){o.agent=n;return}let s=this._sessions.get(i);if(s){let a=n?await this._resolveAgentName(e,s.appliedSnapshot,n):void 0;await s.setAgent(a)}await this._storeSessionAgentMetadata(e,n)}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[,i]of this._sessions)if(i.respondToPermissionRequest(e,n))return}respondToUserInputRequest(e,n,i){for(let[,o]of this._sessions)if(o.respondToUserInputRequest(e,n,i))return}hasSession(e){let n=H.id(e);return this._sessions.has(n)||this._provisionalSessions.has(n)}_getOrCreateActiveClient(e){let n=this._activeClients.get(e);return n||(n=new vm(i=>this._plugins.getAppliedPlugins(i)),this._activeClients.set(e,n)),n}_createAgentSession(e,n,i,o,s,a){let l=H.uri(this.id,n);return this._instantiationService.createInstance(rs,{sessionUri:l,rawSessionId:n,onDidSessionProgress:this._onDidSessionProgress,wrapperFactory:e,shellManager:i,workingDirectory:o,customizationDirectory:s,clientSnapshot:a})}_registerInitializedSession(e,n){if(this._shutdownPromise)throw n.dispose(),new re;this._sessions.set(e,n)}async _destroyAndDisposeSession(e){let n=this._provisionalSessions.get(e);if(n){this._provisionalSessions.delete(e),this._activeClients.delete(n.sessionUri);return}let i=this._sessions.get(e);if(i)try{await i.destroySession()}catch(o){this._logService.warn(`[Copilot:${e}] Failed to destroy session before cleanup: ${o instanceof Error?o.message:String(o)}`)}this._sessions.deleteAndDispose(e),await this._removeCreatedWorktree(e)}_buildSessionConfig(e,n){let i=e.plugins;return async o=>{let a=this._configurationService.getRootValue(Rn,"disableCustomTerminalTool")===!0?[]:await I_(n,this._terminalManager,this._logService,o.requestUnsandboxedCommandConfirmation),l=await o_(i.flatMap(c=>c.agents),this._fileService);return{onPermissionRequest:o.onPermissionRequest,onUserInputRequest:o.onUserInputRequest,onElicitationRequest:o.onElicitationRequest,hooks:c_(i.flatMap(c=>c.hooks),o.hooks),mcpServers:r_(i.flatMap(c=>c.mcpServers)),customAgents:l,skillDirectories:s_(i.flatMap(c=>c.skills)),instructionDirectories:a_(i.flatMap(c=>c.instructions)),systemMessage:$P,tools:[...a,...o.clientTools],gitHubToken:this._githubToken,infiniteSessions:{enabled:!0}}}}_resumeSession(e){let n=this._resumingSessions.get(e);if(n)return n;let i=this._doResumeSession(e);this._resumingSessions.set(e,i);let o=()=>{this._resumingSessions.get(e)===i&&this._resumingSessions.delete(e)};return i.then(o,o),i}async _doResumeSession(e){this._logService.info(`[Copilot:${e}] _resumeSession called \u2014 session not in memory, resuming...`);let n=await this._ensureClient(),i=H.uri(this.id,e),o=await this._readSessionMetadata(i),s=o.customizationDirectory??o.workingDirectory,l=await this._getOrCreateActiveClient(i).snapshot(s),c=await n.getSessionMetadata(e).catch(v=>{this._logService.warn(`[Copilot:${e}] getSessionMetadata failed`,v)}),u=o.workingDirectory??(typeof c?.context?.workingDirectory=="string"?y.file(c.context.workingDirectory):void 0);if(!u)throw new Error(`workingDirectory is required to resume Copilot session '${e}'`);let d=this._instantiationService.createInstance(Rr,i,u),f=this._buildSessionConfig(l,d),m=async v=>{let S=await f(v),_=o.agent?await this._resolveAgentName(i,l,o.agent):void 0;try{this._logService.info(`[Copilot:${e}] Calling SDK resumeSession...`);let b=await n.resumeSession(e,{...S,workingDirectory:u?.fsPath,..._?{agent:_}:{}});return this._logService.info(`[Copilot:${e}] SDK resumeSession succeeded`),new os(b)}catch(b){let I=b?.code,R=b instanceof Error?b.message:String(b);if(this._logService.warn(`[Copilot:${e}] SDK resumeSession failed: code=${I}, message=${R}`),!b||I!==-32603)throw b;this._logService.warn(`[Copilot:${e}] Resume failed (code=-32603), falling back to createSession with same ID`);let P=await n.createSession({...S,sessionId:e,streaming:!0,model:o.model?.id,reasoningEffort:this._getReasoningEffort(o.model),..._?{agent:_}:{},workingDirectory:u?.fsPath});return this._logService.info(`[Copilot:${e}] Fallback createSession succeeded`),new os(P)}},h=this._createAgentSession(m,e,d,u,s,l);try{await h.initializeSession()}catch(v){throw h.dispose(),v}return this._registerInitializedSession(e,h),h}async _getGitInfo(e){if(!await this._gitService.isInsideWorkTree(e))return;let n=await this._gitService.getCurrentBranch(e)??"HEAD",i=await this._gitService.getDefaultBranch(e)??n;return{currentBranch:n,defaultBranch:i}}async _getBranches(e,n){return this._gitService.getBranches(e,{query:n,limit:me._BRANCH_COMPLETION_LIMIT})}async _resolveSessionWorkingDirectory(e,n,i){if(e?.config?.isolation!=="worktree"||!e.workingDirectory||typeof e.config.branch!="string")return e?.workingDirectory;let o=await this._gitService.getRepositoryRoot(e.workingDirectory);if(!o)return e.workingDirectory;let s=BP(o),a=i?qP(i):void 0,l=zP(n,a),c=y.joinPath(s,HP(l));await Pr.mkdir(s.fsPath,{recursive:!0});let u=typeof e.config.branch=="string"?e.config.branch:void 0;await this._gitService.addWorktree(o,c,l,u),this._createdWorktrees.set(n,{repositoryRoot:o,worktree:c}),this._pendingFirstTurnAnnouncements.set(n,E_(l));let d=H.uri(this.id,n);try{await this._writeWorktreeMetadata(d,{branchName:l,baseBranch:u,worktreePath:c,repositoryRoot:o})}catch(f){this._logService.warn(`[Copilot:${n}] Failed to persist worktree branch metadata: ${f instanceof Error?f.message:String(f)}`)}return c}async _removeCreatedWorktree(e){let n=this._createdWorktrees.get(e);if(n)try{await this._gitService.removeWorktree(n.repositoryRoot,n.worktree)}catch(i){this._logService.warn(`[Copilot:${e}] Failed to remove worktree '${n.worktree.fsPath}': ${i instanceof Error?i.message:String(i)}`)}finally{this._createdWorktrees.delete(e)}}static{this._META_MODEL="copilot.model"}static{this._META_AGENT="copilot.agent"}static{this._META_CWD="copilot.workingDirectory"}static{this._META_CUSTOMIZATION_DIRECTORY="copilot.customizationDirectory"}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"}static{this._META_WORKTREE_PATH="copilot.worktree.path"}static{this._META_WORKTREE_REPOSITORY_ROOT="copilot.worktree.repositoryRoot"}async _writeWorktreeMetadata(e,n){let i=this._sessionDataService.openDatabase(e);try{let o=[i.object.setMetadata(me._META_WORKTREE_BRANCH,n.branchName),i.object.setMetadata(me._META_WORKTREE_PATH,n.worktreePath.toString()),i.object.setMetadata(me._META_WORKTREE_REPOSITORY_ROOT,n.repositoryRoot.toString())];n.baseBranch&&o.push(i.object.setMetadata(nd,n.baseBranch)),await Promise.all(o)}finally{i.dispose()}}async _readWorktreeMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(n)try{let[i,o,s]=await Promise.all([n.object.getMetadata(me._META_WORKTREE_BRANCH),n.object.getMetadata(me._META_WORKTREE_PATH),n.object.getMetadata(me._META_WORKTREE_REPOSITORY_ROOT)]);if(!i)return;let a=o?y.parse(o):void 0,l=s?y.parse(s):void 0;return{branchName:i,worktreePath:a,repositoryRoot:l}}finally{n.dispose()}}async _storeSessionMetadata(e,n,i,o,s,a=s!==void 0){let l=this._sessionDataService.openDatabase(e),c=l.object;try{let u=[];n&&u.push(c.setMetadata(me._META_MODEL,this._serializeModelSelection(n))),i&&u.push(c.setMetadata(me._META_CWD,i.toString())),o&&u.push(c.setMetadata(me._META_CUSTOMIZATION_DIRECTORY,o.toString())),a&&u.push(c.setMetadata(me._META_PROJECT_RESOLVED,"true")),s&&(u.push(c.setMetadata(me._META_PROJECT_URI,s.uri.toString())),u.push(c.setMetadata(me._META_PROJECT_DISPLAY_NAME,s.displayName))),await Promise.all(u)}finally{l.dispose()}}async _readSessionMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(!n)return{};try{let[i,o,s,a]=await Promise.all([n.object.getMetadata(me._META_MODEL),n.object.getMetadata(me._META_AGENT),n.object.getMetadata(me._META_CWD),n.object.getMetadata(me._META_CUSTOMIZATION_DIRECTORY)]);return{model:this._parseModelSelection(i),agent:this._parseAgentSelection(o),workingDirectory:s?y.parse(s):void 0,customizationDirectory:a?y.parse(a):void 0}}finally{n.dispose()}}async _readStoredSessionMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(n)try{let[i,o,s,a,l,c,u]=await Promise.all([n.object.getMetadata(me._META_MODEL),n.object.getMetadata(me._META_AGENT),n.object.getMetadata(me._META_CWD),n.object.getMetadata(me._META_CUSTOMIZATION_DIRECTORY),n.object.getMetadata(me._META_PROJECT_RESOLVED),n.object.getMetadata(me._META_PROJECT_URI),n.object.getMetadata(me._META_PROJECT_DISPLAY_NAME)]),d=s?y.parse(s):void 0,f=c&&u?{uri:y.parse(c),displayName:u}:void 0;return{model:this._parseModelSelection(i),agent:this._parseAgentSelection(o),workingDirectory:d,customizationDirectory:a?y.parse(a):void 0,project:f,resolved:l==="true"||f!==void 0}}finally{n.dispose()}}async _storeSessionAgentMetadata(e,n){let i=this._sessionDataService.openDatabase(e);try{await i.object.setMetadata(me._META_AGENT,n?this._serializeAgentSelection(n):"")}finally{i.dispose()}}async _storeSessionProjectResolution(e,n){await this._storeSessionMetadata(e,void 0,void 0,void 0,n,!0)}_resolveSessionProject(e,n,i){let o=this._projectContextKey(e);if(!o)return Promise.resolve(void 0);let s=i.get(o);return s||(s=n.queue(()=>fi(e,this._gitService)),i.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())}};me=w([C(0,L),C(1,qe),C(2,Se),C(3,vt),C(4,Nt),C(5,Po),C(6,Je),C(7,nu),C(8,Ud),C(9,En)],me);var ym=class extends T{constructor(e,n,i,o,s,a){super();this._resolvePlugin=i;this._onDidRefresh=o;this._logService=s;this._customizations=[];this._discovery=this._register(a.createInstance(ss,e,n)),this._bundler=this._register(a.createInstance(as,e)),this._fileService=a.invokeFunction(l=>l.get(Se)),this._settled=this._refresh(),this._register(this._discovery.onDidChange(()=>{this._settled=this._refresh().finally(()=>this._onDidRefresh())}))}whenSettled(){return this._settled}currentCustomizations(){return this._customizations}currentPlugin(){return this._plugin}async _refresh(){try{let e=await this._discovery.directories();this._customizations=await jP(e,this._fileService),this._plugin=void 0;let n=await this._bundler.bundle(e);if(!n)return;let i=y.parse(n.ref.uri);this._plugin=await this._resolvePlugin(i)}catch(e){this._logService.warn(`[Copilot:SessionDiscoveredEntry] Discovery/bundle failed: ${e instanceof Error?e.message:String(e)}`),this._customizations=[],this._plugin=void 0}}};function jP(r,t){return Promise.all(r.map(async e=>{let n=e.uri.toString();return{type:"directory",id:Gt(n),uri:n,name:pe(e.uri),enabled:!0,contents:GP(e.type),writable:!1,load:{kind:"loaded"},children:await Promise.all(e.files.map(i=>JP(i,e.type,t)))}}))}function GP(r){switch(r){case"agent":return"agent";case"skill":return"skill";case"instruction":return"rule"}}async function JP(r,t,e){let n=r.toString(),i=Gt(n);if(t==="agent"){let o=await sm(r,e);return{type:"agent",id:i,uri:n,name:o.name}}return t==="skill"?{type:"skill",id:i,uri:n,name:pe(vn(r))}:{type:"rule",id:i,uri:n,name:pe(r)}}var rl=class extends T{constructor(e,n,i,o,s){super();this._pluginManager=e;this._logService=n;this._fileService=i;this._configurationService=o;this._instantiationService=s;this._onDidChange=this._register(new x);this.onDidChange=this._onDidChange.event;this._enablement=new Map;this._clientCustomizations=[];this._hostCustomizations=[];this._clientSync=Promise.resolve([]);this._hostSync=Promise.resolve([]);this._clientRevision=0;this._hostRevision=0;this._lastAppliedRefs=[];this._sessionDiscovered=new Map;this._applyHostCustomizations(),this._register(this._configurationService.onDidRootConfigChange(()=>{this._applyHostCustomizations()}))}dispose(){for(let e of this._sessionDiscovered.values())e.dispose();this._sessionDiscovered.clear(),super.dispose()}getConfiguredHostCustomizations(){return this._hostCustomizations.map(e=>e.customization)}getSessionCustomizations(e){let n=[...this._hostCustomizations.map(s=>this._applyEnablement(s.customization)),...this._clientCustomizations.map(s=>this._applyEnablement(s.customization))],o=(e?this._getOrCreateSessionEntry(e):void 0)?.currentCustomizations()??[];for(let s of o)n.push(this._applyEnablement(s));return n}async getSessionCustomizationsSettled(e){let n=e?this._getOrCreateSessionEntry(e):void 0;return await Promise.all([this._hostSync.catch(i=>{this._logService.warn("[Copilot:PluginController] Host customization update failed",i)}),this._clientSync.catch(i=>{this._logService.warn("[Copilot:PluginController] Customization sync failed",i)}),n?.whenSettled()]),this.getSessionCustomizations(e)}async getAppliedPlugins(e){let n=e?this._getOrCreateSessionEntry(e):void 0,[i,o]=await Promise.all([this._hostSync.catch(c=>(this._logService.warn("[Copilot:PluginController] Host customization update failed",c),this._hostCustomizations)),this._clientSync.catch(c=>(this._logService.warn("[Copilot:PluginController] Customization sync failed",c),this._clientCustomizations)),n?.whenSettled()]),a=(n?.currentCustomizations()??[]).some(c=>this._isEnabled(c))?n?.currentPlugin():void 0,l=a?[a]:[];return[...i.filter(c=>!!c.plugin&&this._isEnabled(c.customization)).map(c=>c.plugin),...o.filter(c=>!!c.plugin&&this._isEnabled(c.customization)).map(c=>c.plugin),...l]}_getOrCreateSessionEntry(e){let n=e.toString(),i=this._sessionDiscovered.get(n);return i||(i=new ym(e,y.file(this._getUserHome()),o=>this._tryParsePlugin(o),()=>this._onDidChange.fire(),this._logService,this._instantiationService),this._sessionDiscovered.set(n,i)),i}setEnabled(e,n){this._enablement.set(e,n)}_applyHostCustomizations(){let n=(this._configurationService.getRootValue(Rn,"customizations")??[]).map(Ab);if(Me(n,this._lastAppliedRefs))return;this._lastAppliedRefs=n;let i=++this._hostRevision;this._hostCustomizations=n.map(o=>({customization:{...o,load:{kind:"loading"}}})),this._onDidChange.fire(),this._hostSync=Promise.all(n.map(o=>this._resolveConfiguredCustomization(o))).then(o=>(i===this._hostRevision&&(this._hostCustomizations=o),o)).finally(()=>{i===this._hostRevision&&this._onDidChange.fire()})}sync(e,n,i,o){let s=++this._clientRevision;this._clientCustomizations=n.map(d=>({customization:{...d,clientId:e,load:{kind:"loading"}}})),o?.({type:"session/customizationsChanged",customizations:[...this.getSessionCustomizations(i)]});let a=new Map;for(let d of this._clientCustomizations){let f=this._applyEnablement(d.customization);a.set(f.uri,f)}let l=d=>{let f=this._applyEnablement(d.customization);Me(a.get(f.uri),f)||(a.set(f.uri,f),o?.({type:"session/customizationUpdated",customization:f}))},c=this._clientSync;return(this._clientSync=c.catch(d=>{this._logService.warn("[Copilot:PluginController] Previous customization sync failed",d)}).then(async()=>{let d=await this._pluginManager.syncCustomizations(e,n,m=>{s===this._clientRevision&&l({customization:{...m,clientId:e}})}),f=await Promise.all(d.map(m=>this._resolveSyncedCustomization(m,e)));if(s===this._clientRevision){this._clientCustomizations=f;for(let m of f)l(m)}return f})).then(d=>d.map(f=>({customization:this._applyEnablement(f.customization),...f.pluginDir?{pluginDir:f.pluginDir}:{}})))}_isEnabled(e){return this._enablement.get(e.uri)??e.enabled}_applyEnablement(e){let n=this._isEnabled(e);return e.enabled===n?e:{...e,enabled:n}}async _resolveConfiguredCustomization(e){let n=y.parse(e.uri),i=await this._tryParsePlugin(n);return i?{customization:{...e,load:{kind:"loaded"},children:fm([i])},pluginDir:n,plugin:i}:{customization:{...e,load:{kind:"error",message:g(1997,null)}}}}async _resolveSyncedCustomization(e,n){let i={...e.customization,clientId:n};if(!e.pluginDir)return{customization:i};let o=await this._tryParsePlugin(e.pluginDir);return o?{customization:{...i,children:fm([o])},pluginDir:e.pluginDir,plugin:o}:{customization:{...i,load:{kind:"error",message:g(1997,null)}}}}async _tryParsePlugin(e){try{return await Qd(e,this._fileService,void 0,this._getUserHome())}catch(n){this._logService.warn(`[Copilot:PluginController] Error parsing plugin '${e.toString()}': ${n instanceof Error?n.message:String(n)}`);return}}_getUserHome(){return process.env.HOME??process.env.USERPROFILE??""}};rl=w([C(0,Dn),C(1,L),C(2,Se),C(3,Je),C(4,qe)],rl);var vm=class{constructor(t){this._resolvePlugins=t;this._tools=[];this._clientId=""}updateTools(t,e){this._clientId=t,this._tools=e}async snapshot(t){return{clientId:this._clientId,tools:this._tools,plugins:await this._resolvePlugins(t)}}async isOutdated(t,e){let n=await this._resolvePlugins(e);if(!d_(t.plugins,n)||t.tools.length!==this._tools.length)return!0;let i=new Map(t.tools.map(o=>[o.name,o]));for(let o of this._tools){let s=i.get(o.name);if(!s||s.description!==o.description||!Me(s.inputSchema,o.inputSchema))return!0}return!1}};import{CAPIClient as QP,RequestType as Cu}from"@vscode/copilot-api";var Sm=520,YP=300,XP=1800,P_="2025-04-01",ZP=300,ek="gpt-4o-mini",tk=.1,nk=1,ik="conversation-background",kr=class extends Error{constructor(e,n,i){super(i??n.error.message);this.status=e;this.envelope=n;this.name="CopilotApiError"}};function bm(r,t,e,n="CAPI request failed"){let i;if(e)try{let o=JSON.parse(e);if(o&&typeof o=="object"&&o.type==="error"){let s=o.error;s&&typeof s=="object"&&typeof s.type=="string"&&typeof s.message=="string"&&(i=o)}}catch{}return i||(i={type:"error",error:{type:"api_error",message:e||`${r} ${t}`},request_id:null}),new kr(r,i,`${n}: ${r} ${t} \u2014 ${i.error.message}`)}var cs=V("copilotApiService"),ls=class{constructor(t,e,n){this._logService=e;this._productService=n;this._capiBasePromise=null;this._clientsByToken=new Map;this._copilotTokensByGithub=new Map;this._fetch=t??globalThis.fetch}messages(t,e,n){return e.stream?this._messagesStreaming(t,e,n):this._messagesNonStreaming(t,e,n)}async countTokens(t,e,n){throw new Error("countTokens not supported by CAPI")}async models(t,e){let n=await this._getClientForToken(t);this._logService.debug("[CopilotApiService] GET models");let i=await n.makeRequest({method:"GET",headers:{...e?.headers,Authorization:`Bearer ${t}`},signal:e?.signal},{type:Cu.Models});if(!i.ok){(i.status===401||i.status===403)&&this._invalidateClientForToken(t);let s=await i.text().catch(()=>"");throw bm(i.status,i.statusText,s,"CAPI models request failed")}return(await i.json()).data??[]}async utilityChatCompletion(t,e,n){let i=await this._getClientForToken(t),o=await this._getCopilotToken(t),s=await this._resolveUtilityModelId(t,ek),a=q();this._logService.debug("[CopilotApiService] POST chat completions",`model=${s} requestId=${a}`);let l=JSON.stringify({model:s,messages:e.messages.map(f=>({role:f.role,content:f.content})),stream:!1,temperature:e.temperature??tk,top_p:nk}),c=await i.makeRequest({method:"POST",headers:{...n?.headers,"Content-Type":"application/json",Authorization:`Bearer ${o}`,"X-Request-Id":a,"OpenAI-Intent":ik},body:l,signal:n?.signal},{type:Cu.ChatCompletions});if(!c.ok){(c.status===401||c.status===403)&&this._invalidateCopilotTokenForGithub(t);let f=await c.text().catch(()=>"");throw bm(c.status,c.statusText,f,"CAPI chat completion request failed")}let d=(await c.json())?.choices?.[0]?.message?.content;if(typeof d!="string")throw new Error("CAPI chat completion returned no text content");return d}_getCapiBase(){return this._capiBasePromise||(this._capiBasePromise=this._buildCapiBase().catch(t=>{throw this._capiBasePromise=null,t})),this._capiBasePromise}async _buildCapiBase(){let[t,e]=await Promise.all([ad(o=>this._logService.warn("[CopilotApiService] getMachineId failed",o)),ld(o=>this._logService.warn("[CopilotApiService] getDevDeviceId failed",o))]);return{extensionInfo:{name:"agent-host",sessionId:q(),machineId:t,deviceId:e,vscodeVersion:this._productService.version,version:this._productService.version,buildType:this._productService.quality==="stable"?"prod":"dev"},userUrl:"https://api.github.com/copilot_internal/user"}}async*_messagesStreaming(t,e,n){let i=await this._sendRequest(t,e,!0,n);if(!i.body)throw new Error("CAPI response has no body");yield*this._readSSE(i.body)}async _messagesNonStreaming(t,e,n){return(await this._sendRequest(t,e,!1,n)).json()}async _sendRequest(t,e,n,i){let o=await this._getClientForToken(t),s=q();this._logService.debug("[CopilotApiService] POST messages",`model=${e.model} stream=${n} requestId=${s}`);let{system:a,...l}=e,c=JSON.stringify({...l,stream:n,...a!==void 0?{system:typeof a=="string"?[{type:"text",text:a}]:a}:{}}),u=await o.makeRequest({method:"POST",headers:{...i?.headers,"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-Request-Id":s,"OpenAI-Intent":"conversation"},body:c,signal:i?.signal},{type:Cu.ChatMessages});if(!u.ok){(u.status===401||u.status===403)&&this._invalidateClientForToken(t);let d=await u.text().catch(()=>"");throw bm(u.status,u.statusText,d)}return u}_getClientForToken(t){let e=Date.now()/1e3,n=this._clientsByToken.get(t);if(n)return n.then(o=>o.expiresAt-e>YP?o.capiClient:(this._clientsByToken.delete(t),this._getClientForToken(t))).catch(o=>{throw this._clientsByToken.delete(t),o});let i=this._buildClientForToken(t).catch(o=>{throw this._clientsByToken.delete(t),o});return this._clientsByToken.set(t,i),i.then(o=>o.capiClient)}_invalidateClientForToken(t){this._clientsByToken.delete(t)}async _buildClientForToken(t){let{extensionInfo:e,userUrl:n}=await this._getCapiBase(),i=this._fetch,o=new QP(e,void 0,{fetch:(l,c)=>i(l,{method:c.method??"GET",headers:c.headers,body:c.body,signal:c.signal})});this._logService.debug("[CopilotApiService] Discovering CAPI endpoints via /copilot_internal/user");let s=await this._fetch(n,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","X-GitHub-Api-Version":P_}});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`Copilot endpoint discovery failed: ${s.status} ${s.statusText} \u2014 ${l}`)}let a=await s.json();return o.updateDomains({endpoints:a.endpoints??{},sku:a.access_type_sku??""},void 0),this._logService.debug("[CopilotApiService] CAPI endpoint discovered, api=",a.endpoints?.api),{capiClient:o,expiresAt:Date.now()/1e3+XP}}_getCopilotToken(t){let e=Date.now()/1e3,n=this._copilotTokensByGithub.get(t);if(n)return n.then(o=>o.expiresAt-e>ZP?o.token:(this._copilotTokensByGithub.get(t)===n&&this._copilotTokensByGithub.delete(t),this._getCopilotToken(t))).catch(o=>{throw this._copilotTokensByGithub.get(t)===n&&this._copilotTokensByGithub.delete(t),o});let i=this._buildCopilotToken(t).catch(o=>{throw this._copilotTokensByGithub.get(t)===i&&this._copilotTokensByGithub.delete(t),o});return this._copilotTokensByGithub.set(t,i),i.then(o=>o.token)}_invalidateCopilotTokenForGithub(t){this._copilotTokensByGithub.delete(t)}async _buildCopilotToken(t){let e=await this._getClientForToken(t);this._logService.debug("[CopilotApiService] Minting Copilot session token");let n=await e.makeRequest({method:"GET",headers:{Authorization:`token ${t}`,"X-GitHub-Api-Version":P_}},{type:Cu.CopilotToken});if(!n.ok){let l=await n.text().catch(()=>"");throw new Error(`Copilot session token mint failed: ${n.status} ${n.statusText} \u2014 ${l}`)}let i=await n.json();if(typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("Copilot session token mint returned malformed envelope");let o=Date.now()/1e3,s=typeof i.refresh_in=="number"?i.refresh_in:void 0,a=Math.max(s!==void 0?o+s:i.expires_at,o+60);return{token:i.token,expiresAt:a,modelIdsByFamily:new Map}}async _resolveUtilityModelId(t,e){let n=this._copilotTokensByGithub.get(t),i=n?await n:void 0,o=i?.modelIdsByFamily.get(e);if(o)return o;let a=(await this.models(t)).find(l=>l.capabilities?.family===e);if(!a)throw new Error(`No CAPI model available for family '${e}'`);return i?.modelIdsByFamily.set(e,a.id),a.id}async*_readSSE(t){let e=t.getReader(),n=new TextDecoder,i="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;i+=n.decode(s,{stream:!0});let a=i.split(`
`);i=a.pop()??"";for(let l of a){let c=this._parseDataLine(l);if(c!==void 0&&(yield c,c.type==="message_stop"))return}}if(i.trim()){let o=this._parseDataLine(i);if(o!==void 0&&(yield o,o.type==="message_stop"))return}}finally{try{await e.cancel()}catch{}e.releaseLock()}}_parseDataLine(t){if(!t.startsWith("data: "))return;let e=t.slice(6).trim(),n;try{n=JSON.parse(e)}catch{this._logService.warn("[CopilotApiService] Failed to parse SSE data:",e);return}if(typeof n!="object"||n===null)return;let o=n.type;if(typeof o=="string"){if(o==="error"){let s=n.error,a;if(s&&typeof s=="object"&&typeof s.type=="string"&&typeof s.message=="string")a=n;else{let l;typeof s=="string"?l=s:typeof s?.message=="string"?l=s.message:l="Unknown streaming error",a={type:"error",error:{type:"api_error",message:l},request_id:null}}throw new kr(Sm,a)}if(rk.has(o))return n}}};ls=w([C(1,L),C(2,Lt)],ls);var rk=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function ds(r){switch(r){case"default":case"acceptEdits":case"bypassPermissions":case"plan":case"dontAsk":case"auto":return r;default:return}}var k_="thinkingLevel";function Im(r){if(r!==void 0)return r==="max"?"xhigh":r}function ol(r){let t=r?.config?.[k_];switch(t){case"low":case"medium":case"high":case"xhigh":case"max":return t;default:return}}var ok=["low","medium","high","xhigh","max"];function A_(r){return ok.includes(r)}function sk(r){switch(r){case"low":return g(1881,null);case"medium":return g(1883,null);case"high":return g(1880,null);case"xhigh":return g(1885,null);case"max":return g(1882,null)}}function D_(r){if(r.length===0)return;let t=r.includes("high")?"high":void 0;return{type:"object",properties:{[k_]:{type:"string",title:g(1884,null),description:g(1879,null),enum:[...r],enumLabels:r.map(sk),...t!==void 0?{default:t}:{}}}}}var qi=class{constructor(){this._entries=new Map}registerAndFire(t,e){let n=new fe;return this._entries.set(t,n),e(),n.p}register(t){let e=this._entries.get(t);e&&!e.isSettled&&e.error(new re);let n=new fe;return this._entries.set(t,n),n.p}respond(t,e){let n=this._entries.get(t);return n?(this._entries.delete(t),n.complete(e),!0):!1}denyAll(t){for(let[,e]of this._entries)e.isSettled||e.complete(t);this._entries.clear()}rejectAll(t){for(let[,e]of this._entries)e.isSettled||e.error(t);this._entries.clear()}};import*as Tu from"fs";import{pathToFileURL as ak}from"url";var ps=V("claudeAgentSdkService"),us=class{constructor(t){this._logService=t;this._firstLoadFailureLogged=!1}async listSessions(){return(await this._getSdk()).listSessions(void 0)}async getSessionInfo(t){return(await this._getSdk()).getSessionInfo(t)}async startup(t){return(await this._getSdk()).startup(t)}async getSessionMessages(t,e){return(await this._getSdk()).getSessionMessages(t,e)}async listSubagents(t,e){return(await this._getSdk()).listSubagents(t,e)}async getSubagentMessages(t,e,n){return(await this._getSdk()).getSubagentMessages(t,e,n)}async createSdkMcpServer(t){return(await this._getSdk()).createSdkMcpServer(t)}async tool(t,e,n,i){return(await this._getSdk()).tool(t,e,n,i)}async _getSdk(){if(this._sdkModule)return this._sdkModule;try{return this._sdkModule=await this._loadSdk(),this._sdkModule}catch(t){throw this._firstLoadFailureLogged||(this._firstLoadFailureLogged=!0,this._logService.error("[Claude] Failed to load @anthropic-ai/claude-agent-sdk",t)),t}}async _loadSdk(){let t=process.env[oa];if(!t)throw new Error(`Cannot load @anthropic-ai/claude-agent-sdk: ${oa} is not set. Set the 'chat.agentHost.claudeAgent.path' setting to a locally-installed SDK package.`);let e=t;if(Tu.statSync(t).isDirectory()){let n=JSON.parse(Tu.readFileSync(B(t,"package.json"),"utf8")),i=n.exports?.["."]?.default??n.exports?.["."]?.import??n.main??"index.js";e=an(t,i)}return import(ak(e).href)}};us=w([C(0,L)],us);var al={Bash:{permissionKind:"shell",toolKind:"terminal"},BashOutput:{permissionKind:"shell",toolKind:"terminal"},KillBash:{permissionKind:"shell",toolKind:"terminal"},Read:{permissionKind:"read",pathField:"file_path"},Glob:{permissionKind:"read",pathField:"path",toolKind:"search"},Grep:{permissionKind:"read",pathField:"path",toolKind:"search"},LS:{permissionKind:"read",pathField:"path"},NotebookRead:{permissionKind:"read",pathField:"notebook_path"},Write:{permissionKind:"write",pathField:"file_path",isFileEdit:!0},Edit:{permissionKind:"write",pathField:"file_path",isFileEdit:!0},MultiEdit:{permissionKind:"write",pathField:"file_path",isFileEdit:!0},NotebookEdit:{permissionKind:"write",pathField:"notebook_path",isFileEdit:!0},TodoWrite:{permissionKind:"write"},WebFetch:{permissionKind:"url",pathField:"url"},Task:{permissionKind:"custom-tool",toolKind:"subagent"},Agent:{permissionKind:"custom-tool",toolKind:"subagent"},ExitPlanMode:{permissionKind:"custom-tool",interactive:!0},AskUserQuestion:{permissionKind:"custom-tool",interactive:!0}},sl="mcp__";function xu(r){let t=al[r];return t?t.permissionKind:r.startsWith(sl)?"mcp":"custom-tool"}function Wt(r){switch(r){case"Bash":return g(1928,null);case"BashOutput":return g(1929,null);case"KillBash":return g(1934,null);case"Read":return g(1940,null);case"Glob":return g(1932,null);case"Grep":return g(1933,null);case"LS":return g(1935,null);case"NotebookRead":return g(1939,null);case"Write":return g(1944,null);case"Edit":return g(1930,null);case"MultiEdit":return g(1937,null);case"NotebookEdit":return g(1938,null);case"TodoWrite":return g(1942,null);case"WebFetch":return g(1943,null);case"Task":case"Agent":return g(1941,null);case"ExitPlanMode":return g(1931,null);case"AskUserQuestion":return g(1927,null)}return r.startsWith(sl)?g(1936,null,r.slice(sl.length)):r}function Fn(r,t){let e=al[r];if(!e?.pathField||typeof t!="object"||t===null)return;let n=t[e.pathField];return typeof n=="string"?n:void 0}function O_(r){return al[r]?.isFileEdit===!0}var L_=new Set(Object.entries(al).filter(([,r])=>r.interactive).map(([r])=>r));function M_(r){switch(xu(r)){case"shell":return g(1924,null);case"write":return g(1926,null);case"read":return g(1923,null);case"url":return g(1925,null);case"mcp":{let t=r.startsWith(sl)?r.slice(sl.length).split("__")[0]:void 0;return t?g(1922,null,t):g(1921,null)}default:return g(1921,null)}}function Wn(r){let t=al[r];if(t?.toolKind)return{toolKind:t.toolKind}}function Ft(r){return{markdown:r}}function fs(r){let t=y.file(r);return`[${ns(pe(t))}](${t})`}function Un(r,t){if(r===null||typeof r!="object")return;let e=r[t];return typeof e=="string"&&e.length>0?e:void 0}function N_(r){let t=Un(r,"command");return t?t.split(`
`)[0]:void 0}function gi(r,t,e){switch(r){case"Bash":{let n=N_(e);return n?Ft(g(1966,null,He(Gn(n,80)))):g(1965,null)}case"BashOutput":return g(1967,null);case"KillBash":return g(1974,null);case"Read":case"NotebookRead":{let n=Fn(r,e);return n?Ft(g(1978,null,fs(n))):g(1977,null)}case"LS":{let n=Fn(r,e);return n?Ft(g(1976,null,fs(n))):g(1975,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let n=Fn(r,e);return n?Ft(g(1969,null,fs(n))):g(1968,null)}case"TodoWrite":return g(1979,null);case"Grep":{let n=Un(e,"pattern");return n?Ft(g(1973,null,He(Gn(n,80)))):g(1972,null)}case"Glob":{let n=Un(e,"pattern");return n?Ft(g(1971,null,He(Gn(n,80)))):g(1970,null)}case"WebFetch":{let n=Un(e,"url");return n?Ft(g(1980,null,`[${ns(Gn(n,80))}](${n})`)):g(1981,null)}case"Task":case"Agent":{let n=Un(e,"description");return n||t}default:return t}}function wu(r,t,e,n){if(!n)return g(1950,null,t);switch(r){case"Bash":{let i=N_(e);return i?Ft(g(1946,null,He(Gn(i,80)))):g(1945,null)}case"BashOutput":return g(1947,null);case"KillBash":return g(1956,null);case"Read":case"NotebookRead":{let i=Fn(r,e);return i?Ft(g(1960,null,fs(i))):g(1959,null)}case"LS":{let i=Fn(r,e);return i?Ft(g(1958,null,fs(i))):g(1957,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let i=Fn(r,e);return i?Ft(g(1949,null,fs(i))):g(1948,null)}case"TodoWrite":return g(1962,null);case"Grep":{let i=Un(e,"pattern");return i?Ft(g(1955,null,He(Gn(i,80)))):g(1954,null)}case"Glob":{let i=Un(e,"pattern");return i?Ft(g(1953,null,He(Gn(i,80)))):g(1952,null)}case"WebFetch":{let i=Un(e,"url");return i?Ft(g(1963,null,`[${ns(Gn(i,80))}](${i})`)):g(1964,null)}case"Task":case"Agent":return g(1961,null);default:return g(1951,null,t)}}function Ki(r,t){if(t!==void 0){if(r==="Bash"||r==="BashOutput"||r==="KillBash"){let e=Un(t,"command");if(e)return e}if(r==="Grep"||r==="Glob"){let e=Un(t,"pattern");if(e)return e}try{return JSON.stringify(t,null,2)}catch{return}}}import{z as ct}from"zod";function F_(r){if(!r||r.type!=="object"||!r.properties)return{};let t=new Set(r.required??[]),e={};for(let[n,i]of Object.entries(r.properties)){let o;try{o=Ru(i)}catch{o=ct.any()}t.has(n)||(o=o.optional()),e[n]=o}return e}function Ru(r){if(!r||typeof r!="object")return ct.any();let t;if(Array.isArray(r.enum)&&r.enum.length>0){let e=r.enum.filter(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null);e.length===0?t=ct.any():e.length===1?t=ct.literal(e[0]):t=ct.union(e.map(n=>ct.literal(n)))}else if(Array.isArray(r.oneOf)&&r.oneOf.length>0)t=U_(r.oneOf);else if(Array.isArray(r.anyOf)&&r.anyOf.length>0)t=U_(r.anyOf);else switch(Array.isArray(r.type)?r.type[0]:r.type){case"string":t=ct.string();break;case"number":t=ct.number();break;case"integer":t=ct.number().int();break;case"boolean":t=ct.boolean();break;case"array":t=ct.array(r.items?Ru(r.items):ct.any());break;case"object":{let n={},i=new Set(r.required??[]);for(let[o,s]of Object.entries(r.properties??{})){let a;try{a=Ru(s)}catch{a=ct.any()}i.has(o)||(a=a.optional()),n[o]=a}t=ct.object(n);break}case"null":t=ct.null();break;default:t=ct.any()}return r.nullable&&(t=t.nullable()),r.description&&(t=t.describe(r.description)),r.default!==void 0&&(t=t.default(r.default)),t}function U_(r){let t=r.map(e=>{try{return Ru(e)}catch{return ct.any()}});return t.length===1?t[0]:ct.union(t)}var W_="claudecode/toolUseId";async function $_(r,t,e){let n=await Promise.all(r.map(i=>e.tool(i.name,i.description??"",F_(i.inputSchema),async(o,s)=>{let a=lk(s);return a===void 0?{content:[{type:"text",text:`Client tool "${i.name}" could not run: SDK omitted tool_use_id (expected at extra._meta["${W_}"]).`}],isError:!0}:t(a)})));return e.createSdkMcpServer({name:_m,tools:n})}function lk(r){if(!r||typeof r!="object")return;let t=r._meta;if(!t||typeof t!="object")return;let e=t[W_];return typeof e=="string"?e:void 0}var _m="client";function gs(r){let t=`mcp__${_m}__`;return r.startsWith(t)?r.slice(t.length):r}function V_(r){return r.startsWith(`mcp__${_m}__`)}function ll(r,t,e){let n=new Cm(t,e);for(let i of r){let o=ck(i);o!==void 0&&n.consume(o)}return n.finish()}function ck(r){switch(r.type){case"user":return dk(r);case"assistant":return uk(r);case"system":return pk(r);default:return}}function dk(r){let t=gk(r.message);if(t===void 0||Sk(t))return;if(typeof t=="string")return{kind:"user-text",uuid:r.uuid,text:t};let e=t.filter(n=>n.type==="text");if(e.length===0){let n=t.filter(i=>i.type==="tool_result");return n.length>0?{kind:"user-tool-results",uuid:r.uuid,results:n}:void 0}return{kind:"user-text",uuid:r.uuid,text:e.map(n=>n.text).join(`
`)}}function uk(r){let t=mk(r.message);if(!(t===void 0||t.length===0))return{kind:"assistant",uuid:r.uuid,blocks:t}}function pk(r){let t=hk(r.message);if(t===void 0||!fk.has(t))return;let e=yk(r.message)??`[${t}]`;return{kind:"system-notification",uuid:r.uuid,subtype:t,text:e}}var fk=new Set(["compact_boundary","notification"]),B_=/^<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat)>/,Cm=class{constructor(t,e){this._session=t;this._logService=e;this._turns=[];this._toolUses=new Map}consume(t){switch(t.kind){case"user-text":this._closeActive(),this._active={id:t.uuid,userText:t.text,responseParts:[],pendingToolUseIds:new Set,toolCallParts:new Map};return;case"user-tool-results":for(let e of t.results)this._attachToolResult(e);return;case"assistant":this._consumeAssistant(t);return;case"system-notification":if(this._active===void 0)return;this._active.responseParts.push({kind:"systemNotification",content:t.text});return}}finish(){return this._closeActive(),this._turns}_consumeAssistant(t){if(this._active===void 0){this._logService.warn(`[claudeReplayMapper] assistant envelope ${t.uuid} arrived before any user message; dropping`);return}let e=0,n=0;for(let i of t.blocks)i.type==="text"&&typeof i.text=="string"?this._active.responseParts.push({kind:"markdown",id:`${this._active.id}#${t.uuid}#text-${e++}`,content:i.text}):i.type==="thinking"&&typeof i.thinking=="string"?this._active.responseParts.push({kind:"reasoning",id:`${this._active.id}#${t.uuid}#thinking-${n++}`,content:i.thinking}):i.type==="tool_use"&&typeof i.id=="string"&&typeof i.name=="string"&&this._openToolUse(i.id,gs(i.name),i.input)}_openToolUse(t,e,n){if(this._active===void 0)return;let i=Wt(e),o=n!==null&&typeof n=="object"?n:void 0,s=Wn(e),a={status:"cancelled",toolCallId:t,toolName:e,displayName:i,invocationMessage:gi(e,i,o),toolInput:o!==void 0?Ki(e,o):typeof n=="string"?n:n!==void 0?bk(n):void 0,reason:"skipped",...s?{_meta:s}:{}},l={kind:"toolCall",toolCall:a};this._active.responseParts.push(l),this._active.toolCallParts.set(t,l),this._active.pendingToolUseIds.add(t),this._toolUses.set(t,{turnId:this._active.id,parsedInput:o})}_attachToolResult(t){let e=this._toolUses.get(t.tool_use_id);if(e===void 0){this._logService.warn(`[claudeReplayMapper] tool_result for unknown tool_use_id ${t.tool_use_id}`);return}let n=e.turnId,i=this._findToolCallPart(n,t.tool_use_id);if(i===void 0)return;let o=t.is_error,s=i.toolCall,a=s._meta?.toolKind==="subagent",l=vk(t.content)??[];a&&l.push({type:"subagent",resource:Co(this._session.toString(),s.toolCallId),title:s.displayName});let c={status:"completed",toolCallId:s.toolCallId,toolName:s.toolName,displayName:s.displayName,invocationMessage:s.invocationMessage??s.displayName,toolInput:s.status==="streaming"?void 0:s.toolInput,confirmed:"not-needed",success:!o,pastTenseMessage:wu(s.toolName,s.displayName,e.parsedInput,!o),content:l.length>0?l:void 0,...s._meta?{_meta:s._meta}:{}};i.toolCall=c,this._active?.id===n&&this._active.pendingToolUseIds.delete(t.tool_use_id)}_findToolCallPart(t,e){if(this._active&&this._active.id===t)return this._active.toolCallParts.get(e);for(let n=this._turns.length-1;n>=0;n--)if(this._turns[n].id===t){for(let i of this._turns[n].responseParts)if(i.kind==="toolCall"&&i.toolCall.toolCallId===e)return i;return}}_closeActive(){if(this._active===void 0)return;let t=this._active,e=t.pendingToolUseIds.size===0?"complete":"cancelled",n={id:t.id,message:{text:t.userText,origin:{kind:"user"}},responseParts:t.responseParts,usage:void 0,state:e};this._turns.push(n),this._active=void 0}};function gk(r){if(r===null||typeof r!="object")return;let t=r.content;if(typeof t=="string")return t.length>0?t:void 0;if(!Array.isArray(t)||t.length===0)return;let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let i=n;i.type==="text"&&typeof i.text=="string"?e.push({type:"text",text:i.text}):i.type==="tool_result"&&typeof i.tool_use_id=="string"&&e.push({type:"tool_result",tool_use_id:i.tool_use_id,content:i.content,is_error:i.is_error===!0})}return e.length>0?e:void 0}function mk(r){if(r===null||typeof r!="object")return;let t=r.content;if(!Array.isArray(t))return;let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let i=n;typeof i.type=="string"&&e.push({type:i.type,text:typeof i.text=="string"?i.text:void 0,thinking:typeof i.thinking=="string"?i.thinking:void 0,id:typeof i.id=="string"?i.id:void 0,name:typeof i.name=="string"?i.name:void 0,input:i.input})}return e}function hk(r){if(r===null||typeof r!="object")return;let t=r.subtype;return typeof t=="string"?t:void 0}function yk(r){if(r===null||typeof r!="object")return;let t=r;if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message}function vk(r){if(typeof r=="string")return r.length>0?[{type:"text",text:r}]:void 0;if(!Array.isArray(r))return;let t=[];for(let e of r){if(e===null||typeof e!="object")continue;let n=e;n.type==="text"&&typeof n.text=="string"&&t.push({type:"text",text:n.text})}return t.length>0?t:void 0}function bk(r){try{return JSON.stringify(r)}catch{return}}function Sk(r){if(typeof r=="string")return B_.test(r);let t=r.find(e=>e.type==="text");return t!==void 0&&B_.test(t.text)}var Tm=class{validateOrThrow(t){let e=this.validate(t);if(e.error)throw new Error(e.error.message);return e.content}},ms=class extends Tm{constructor(e){super();this.type=e}validate(e){return typeof e!==this.type?{content:void 0,error:{message:`Expected ${this.type}, but got ${typeof e}`}}:{content:e,error:void 0}}getJSONSchema(){return{type:this.type}}},Ik=new ms("string");function H_(){return Ik}var lne=new ms("number");var cne=new ms("boolean");var _k=new ms("object");function z_(){return _k}var cl=new Set(["Task","Agent"]),Ck=/^\s*agentId:\s+([a-z0-9]+)\b/im,xm=class{constructor(t){this.toolUseId=t;this.background=!1;this._announced=!1;this._completed=!1}get agentId(){return this._agentId}setAgentId(t){this._agentId===void 0&&(this._agentId=t)}markAnnounced(){return this._announced?!1:(this._announced=!0,!0)}markCompleted(){return this._completed?!1:(this._completed=!0,!0)}},Eu=class extends T{constructor(){super(...arguments);this._spawns=new Map;this._innerToParent=new Map}dispose(){this._spawns.clear(),this._innerToParent.clear(),super.dispose()}recordSpawn(e,n){let i=this._spawns.get(e);return i||(i=new xm(e),this._spawns.set(e,i)),n?.agentId!==void 0&&i.setAgentId(n.agentId),n?.subagentType!==void 0&&i.subagentType===void 0&&(i.subagentType=n.subagentType),n?.description!==void 0&&i.description===void 0&&(i.description=n.description),i}getSpawn(e){return this._spawns.get(e)}removeSpawn(e){this._spawns.delete(e),this._evictInnerEdgesFor(e)}noteInnerTool(e,n){this._innerToParent.set(e,n)}getParentSpawn(e){let n=this._innerToParent.get(e);return n!==void 0?this._spawns.get(n):void 0}drainForegroundSpawns(){let e=[];for(let n of this._spawns.values())n.background||e.push(n);for(let n of e)this._spawns.delete(n.toolUseId),this._evictInnerEdgesFor(n.toolUseId);return e}primeFromTranscript(e){for(let[n,i]of wm(e))this.recordSpawn(n,{agentId:i})}_evictInnerEdgesFor(e){for(let[n,i]of this._innerToParent)i===e&&this._innerToParent.delete(n)}};function wm(r){let t=new Map;for(let e of r)for(let n of e.responseParts){let i=Tk(n);i&&t.set(i.toolCallId,i.agentId)}return t}function Tk(r){if(r.kind!=="toolCall")return;let t=r.toolCall;if(!cl.has(t.toolName)||t.status!=="completed"&&t.status!=="pending-result-confirmation")return;let e=t.content;if(e)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.type!=="text")continue;let o=Ck.exec(i.text);if(o)return{toolCallId:t.toolCallId,agentId:o[1]}}}var Rm=class{constructor(t,e){this._sdk=t;this._logService=e;this.name="text_suffix"}async lookup(t,e){let n=await q_(this._sdk,this._logService,e,"TextSuffix");if(n)return wm(n).get(t)}};async function q_(r,t,e,n){if(e.parentTranscript)return e.parentTranscript;try{let i=await r.getSessionMessages(e.parentSessionId,{includeSystemMessages:!0});return ll(i,e.parentUri,t)}catch(i){t.warn(`[claudeSubagentResolver] ${n}: parent transcript fetch failed: ${i}`);return}}function K_(r){let t=H_().validate(r);return t.error?void 0:t.content}function Em(r){let t=z_().validate(r);if(!(t.error||t.content===null||Array.isArray(t.content)))return t.content}var Pm=class{constructor(t,e){this._sdk=t;this._logService=e;this.name="prompt_match"}async lookup(t,e){let n=await this._loadParentPrompt(t,e);if(!n)return;let i;try{i=await this._sdk.listSubagents(e.parentSessionId)}catch(o){this._logService.warn(`[claudeSubagentResolver] PromptMatch: listSubagents failed: ${o}`);return}for(let o of i){if(e.token.isCancellationRequested)return;let s;try{s=await this._sdk.getSubagentMessages(e.parentSessionId,o)}catch(l){this._logService.warn(`[claudeSubagentResolver] PromptMatch: getSubagentMessages(${o}) failed: ${l}`);continue}let a=wk(s);if(a!==void 0&&a===n)return o}}async _loadParentPrompt(t,e){let n=await q_(this._sdk,this._logService,e,"PromptMatch");if(n)return xk(n,t)}};function xk(r,t){for(let e of r)for(let n of e.responseParts){if(n.kind!=="toolCall")continue;let i=n.toolCall;if(i.toolCallId!==t)continue;if(!cl.has(i.toolName)||i.status==="streaming")return;let o=i.toolInput;if(typeof o!="string")return;let s;try{s=JSON.parse(o)}catch{return}let a=Em(s);return a?K_(a.prompt):void 0}}function wk(r){for(let t of r){if(t.type!=="user")continue;let e=Em(t.message);if(!e)continue;let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))for(let i of n){let o=Em(i);if(!o||o.type!=="text")continue;let s=K_(o.text);if(s!==void 0)return s}}}var km=class{constructor(){this.name="native"}async lookup(){}};async function Rk(r,t,e){let n=e.cacheGet(r);if(n)return n;for(let i of e.strategies){if(t.token.isCancellationRequested)return;let o=await i.lookup(r,t);if(o)return e.cacheSet(r,o),o}}function Ek(r,t){return[new Rm(r,t),new Pm(r,t),new km]}async function j_(r,t,e,n,i){let o=Ge(r);if(!o)throw new Error(`getSubagentTranscript: not a subagent URI: ${r.toString()}`);let{parentSession:s,toolCallId:a}=o,l=H.id(s),c=await Rk(a,{parentUri:s,parentSessionId:l,token:i},{strategies:Ek(e,n),cacheGet:d=>t.getSpawn(d)?.agentId,cacheSet:(d,f)=>{t.recordSpawn(d,{agentId:f})}});if(!c)return[];let u;try{u=await e.getSubagentMessages(l,c)}catch(d){return n.warn(`[getSubagentTranscript] getSubagentMessages(${c}) failed: ${d}`),[]}return ll(u,r,n)}async function Am(r,t,e,n){let i=Pk(),o=await es(),s={ANTHROPIC_BASE_URL:t.baseUrl,ANTHROPIC_AUTH_TOKEN:`${t.nonce}.${r.sessionId}`,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",USE_BUILTIN_RIPGREP:"0",PATH:`${de(o)}${qr}${process.env.PATH??""}`};return{cwd:r.workingDirectory.fsPath,executable:process.execPath,env:i,abortController:r.abortController,allowDangerouslySkipPermissions:!0,canUseTool:r.canUseTool,onElicitation:async a=>(n(a.message??""),{action:"cancel"}),disallowedTools:["WebSearch"],includePartialMessages:!0,forwardSubagentText:!0,enableFileCheckpointing:!0,model:r.model?.id,effort:ol(r.model),permissionMode:r.permissionMode,...r.isResume?{resume:r.sessionId}:{sessionId:r.sessionId},...r.mcpServers?{mcpServers:r.mcpServers}:{},...r.plugins&&r.plugins.length>0?{plugins:r.plugins.map(a=>({type:"local",path:a.fsPath}))}:{},...r.agent?{agent:r.agent}:{},settingSources:["user","project","local"],settings:{env:s},systemPrompt:{type:"preset",preset:"claude_code"},stderr:e}}async function Dm(r,t,e){let{tools:n}=r.consume();return!n||n.length===0?void 0:{client:await $_(n,o=>t.register(o),e)}}function Pk(){let r={ELECTRON_RUN_AS_NODE:"1",NODE_OPTIONS:void 0,ANTHROPIC_API_KEY:void 0};for(let t of Object.keys(process.env))t!=="ELECTRON_RUN_AS_NODE"&&(t.startsWith("VSCODE_")||t.startsWith("ELECTRON_"))&&(r[t]=void 0);return r}var kk="claude-client";function G_(r,t){let i={content:(r.content??[]).map((o,s)=>Ak(o,t,s))};return r.structuredContent!==void 0&&(i.structuredContent=r.structuredContent),(!r.success||r.error)&&(i.isError=!0),i}function Ak(r,t,e){switch(r.type){case"text":return{type:"text",text:r.text};case"embeddedResource":return Dk(r,t,e);default:{console.warn(`[Claude] convertToolCallResult: unsupported tool-result block kind '${r.type}'; degrading to text`);let n;try{n=JSON.stringify(r)}catch{n=`[unserializable ${r.type} block]`}return{type:"text",text:n}}}}function Dk(r,t,e){return r.contentType.startsWith("image/")?{type:"image",data:r.data,mimeType:r.contentType}:{type:"resource",resource:{uri:`${kk}://${encodeURIComponent(t)}/${e}`,mimeType:r.contentType,blob:r.data}}}function hs(r,t){return ds(r.getSessionConfigValues(t.toString())?.permissionMode)}var Ok={tools:void 0,clientId:void 0},Om=class{constructor(){this._state=fr({owner:this,equalsFn:Lk},Ok);this.state=this._state}setTools(t,e){let n=this._state.get();this._state.set({tools:t,clientId:e??n.clientId},void 0)}},Pu=class extends T{constructor(){super();this.model=new Om;this._dirty=!1;this._ignoreNextFire=!0;this._register(_n(e=>{if(this.model.state.read(e),this._ignoreNextFire){this._ignoreNextFire=!1;return}this._dirty=!0}))}get hasDifference(){return this._dirty}consume(){let e=this.model.state.get();return this._dirty=!1,e}markDirty(){this._dirty=!0}};function Lk(r,t){return r.clientId===t.clientId&&Mk(r.tools,t.tools)}function Mk(r,t){let e=r??[],n=t??[];if(e.length!==n.length)return!1;let i=new Map;for(let o of e)i.set(o.name,o);for(let o of n){let s=i.get(o.name);if(!s||s.description!==o.description||!Me(s.inputSchema,o.inputSchema))return!1}return!0}var Nk={synced:[],enablement:new Map},Lm=class{constructor(){this._state=fr({owner:this,equalsFn:Uk},Nk);this.state=this._state;this.enabledPluginPaths=la({owner:this,equalsFn:(t,e)=>Vt(t,e,(n,i)=>n.toString()===i.toString())},t=>{let e=this._state.read(t),n=[];for(let i of e.synced)i.pluginDir&&e.enablement.get(i.customization.id)!==!1&&n.push(i.pluginDir);return n})}setSyncedCustomizations(t){let e=this._state.get();this._state.set({synced:t,enablement:e.enablement},void 0)}setEnabled(t,e){let n=this._state.get(),i=n.enablement.get(t);if(i===e||e&&i===void 0)return;let o=new Map(n.enablement);e?o.delete(t):o.set(t,!1),this._state.set({synced:n.synced,enablement:o},void 0)}},ku=class extends T{constructor(){super();this.model=new Lm;this._dirty=!1;this._ignoreNextFire=!0;this.onDidChange=Q.fromObservableLight(this.model.state);this._register(_n(e=>{if(this.model.state.read(e),this._ignoreNextFire){this._ignoreNextFire=!1;return}this._dirty=!0}))}get hasDifference(){return this._dirty}consume(){let e=this.model.enabledPluginPaths.get();return this._dirty=!1,e}markDirty(){this._dirty=!0}};function Uk(r,t){return Fk(r.synced,t.synced)&&$k(r.enablement,t.enablement)}function Fk(r,t){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++){let n=r[e].customization,i=t[e].customization;if(n.id!==i.id||n.uri.toString()!==i.uri.toString()||n.nonce!==i.nonce||n.name!==i.name||n.enabled!==i.enabled||n.load?.kind!==i.load?.kind||Q_(n.load)!==Q_(i.load)||!Wk(n.children,i.children)||r[e].pluginDir?.toString()!==t[e].pluginDir?.toString())return!1}return!0}function Q_(r){return r&&r.message?r.message:void 0}function Wk(r,t){if(r===t)return!0;if(!r||!t||r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(r[e].id!==t[e].id||r[e].name!==t[e].name)return!1;return!0}function $k(r,t){if(r.size!==t.size)return!1;for(let[e,n]of r)if(t.get(e)!==n)return!1;return!0}function Y_(r,t,e){let n=[];for(let i of r){let o=t.get(i.customization.id)??i.customization.enabled;n.push({...i.customization,enabled:o})}return e&&n.push(e),n}var Vk="claude-discovered",Bk=g(1982,null),Hk="claude-discovered",zk="general-purpose",ys=class extends T{constructor(e,n,i){super();this._fileService=n;let o=`claude-${ht(e.toString())}`;this._rootUri=y.joinPath(i.basePath,Hk,o)}async bundle(e){if(e.commands.length===0&&e.agents.length===0)return;let n=[];for(let l of e.agents)n.push(`agent:${l.name}
${l.description}
${l.model??""}`);for(let l of e.commands)n.push(`command:${l.name}
${l.description}
${l.argumentHint??""}`);n.sort();let i=String(ht(n.join(`
`)));if(this._lastNonce!==i){try{await this._fileService.del(this._rootUri,{recursive:!0})}catch{}let l=y.joinPath(this._rootUri,".plugin","plugin.json");await this._fileService.writeFile(l,k.fromString(JSON.stringify({name:Vk,description:"Customizations discovered by the Claude agent"},null,"	")));for(let c of e.agents){let u=y.joinPath(this._rootUri,"agents",`${Au(c.name)}.md`);await this._fileService.writeFile(u,k.fromString(qk(c.name,c.description)))}for(let c of e.commands){let u=Au(c.name),d=y.joinPath(this._rootUri,"skills",u,"SKILL.md");await this._fileService.writeFile(d,k.fromString(Kk(u,c.description,c.argumentHint)))}this._lastNonce=i}let o=e.agents.filter(l=>l.name!==zk).map(l=>{let c=y.joinPath(this._rootUri,"agents",`${Au(l.name)}.md`).toString();return{type:"agent",id:Gt(c),uri:c,name:l.name,description:l.description}}),s=e.commands.map(l=>{let c=Au(l.name),u=y.joinPath(this._rootUri,"skills",c,"SKILL.md").toString();return{type:"skill",id:Gt(u),uri:u,name:c,description:l.description}}),a=this._rootUri.toString();return{type:"plugin",id:Gt(a),uri:a,name:Bk,enabled:!0,load:{kind:"loaded"},children:[...o,...s]}}};ys=w([C(1,Se),C(2,Dn)],ys);function Au(r){return r.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,128)||"unnamed"}function qk(r,t){return`---
name: ${Du(r)}
description: ${Du(X_(t,1024))}
---
`}function Kk(r,t,e){let n=e?`
Usage: \`${e}\`
`:"";return`---
name: ${Du(r)}
description: ${Du(X_(t,1024))}
---
${n}`}function Du(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r?\n/g," ")}"`}function X_(r,t){return r.length<=t?r:`${r.slice(0,t-1)}\u2026`}function Ou(r,t){let e=[{type:"text",text:r}];if(!t?.length)return e;let n=[],i=[];for(let o of t){if(o.type==="simple"){o.modelRepresentation&&i.push(o.modelRepresentation);continue}if(o.type!=="resource")continue;let s=y.parse(o.uri);if(o.displayKind==="selection"){let a=o.selection?`:${o.selection.range.start.line+1}`:"";n.push(`- ${Z_(s)}${a}`)}else n.push(`- ${Z_(s)}`)}return i.length>0&&e.push({type:"text",text:i.join(`

`)}),n.length===0||e.push({type:"text",text:`<system-reminder>
The user provided the following references:
`+n.join(`
`)+`

IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
</system-reminder>`}),e}function Z_(r){return r.scheme==="file"?r.fsPath:r.toString()}var vs=class extends T{constructor(e,n,i,o){super();this._sessionId=e;this._getAbortSignal=n;this._onSteeringYielded=i;this._logService=o;this._toYield=[];this._yielded=[];this._popped=[];this._pendingPromptDeferred=new fe;this.iterable={[Symbol.asyncIterator]:()=>({next:async()=>{for(;;){if(this._getAbortSignal().aborted)return{done:!0,value:void 0};if(this._toYield.length>0){let e=this._toYield.shift();return this._yielded.push(e),this._logService.info(`[Claude:${this._sessionId}] queue yielded sdkUuid=${e.sdkUuid} turnId=${e.turnId}${e.steeringPendingId?` steeringPendingId=${e.steeringPendingId}`:""}`),e.steeringPendingId&&this._onSteeringYielded(e.steeringPendingId),{done:!1,value:e.sdkMessage}}await this._pendingPromptDeferred.p,this._pendingPromptDeferred=new fe}}})}}get isEmpty(){return this._toYield.length===0&&this._yielded.length===0}push(e){return this._toYield.push(e),this._pendingPromptDeferred.complete(),e.deferred.p}peekParent(){return this._yielded[0]??this._toYield[this._toYield.length-1]}settleHead(){let e=this._yielded.shift();if(e){if(this.isEmpty){e.deferred.complete();for(let n of this._popped)n.deferred.isSettled||n.deferred.complete();this._popped=[]}else this._popped.push(e);return e}}failAll(e){let n=i=>{for(let o of i)o.deferred.isSettled||o.deferred.error(e)};n(this._toYield),n(this._yielded),n(this._popped),this._toYield=[],this._yielded=[],this._popped=[]}notifyAborted(){this._pendingPromptDeferred.complete()}resetForRebind(){this._pendingPromptDeferred=new fe}};vs=w([C(3,L)],vs);var bs=class extends T{constructor(e,n,i,o){super();this._logService=i;this._editToolPaths=new Map;this._register(n),this._editTracker=o.createInstance(Mi,e,n.object)}observeAssistant(e){let n=e.message.content;if(Array.isArray(n))for(let i of n){if(i.type!=="tool_use"||!O_(i.name))continue;let o=Fn(i.name,i.input);o&&(this._editToolPaths.set(i.id,o),this._editTracker.trackEditStart(o).catch(s=>this._logService.warn(`[ClaudeFileEditObserver] trackEditStart failed for ${o}: ${s}`)))}}async observeUser(e,n,i){let o=e.message.content;if(Array.isArray(o))for(let s of o){if(s.type!=="tool_result")continue;let a=this._editToolPaths.get(s.tool_use_id);if(a){this._editToolPaths.delete(s.tool_use_id);try{await this._editTracker.completeEdit(a);let l=await this._editTracker.takeCompletedEdit(n,s.tool_use_id,a);l&&i.cacheFileEdit(s.tool_use_id,l)}catch(l){this._logService.warn(`[ClaudeFileEditObserver] file edit tracking failed for ${a}: ${l}`)}}}}};bs=w([C(2,L),C(3,qe)],bs);var Mm=cl;function Lu(r,t,e,n){if(!e)return r;let i=r.map(a=>a.kind==="action"?{...a,parentToolCallId:e}:a.kind==="pending_confirmation"?{...a,parentToolCallId:e}:a),o=n.getSpawn(e);return!o||!o.markAnnounced()?i:[{kind:"subagent_started",session:t,toolCallId:e,agentName:o.subagentType??"subagent",agentDisplayName:o.subagentType??"Subagent",agentDescription:o.description},...i]}function eC(r,t,e){let n=r.subtype;if(n==="task_started"){let i=r.tool_use_id,o=i?e.getSpawn(i):void 0;return o&&(o.background=!0),[]}if(n==="task_notification"){let i=r;if(!i.tool_use_id)return[];let o=i.status;if(o!=="completed"&&o!=="failed"&&o!=="stopped")return[];let s=e.getSpawn(i.tool_use_id);if(!s||!s.markCompleted())return[];let a=i.tool_use_id;return e.removeSpawn(a),[{kind:"subagent_completed",session:t,toolCallId:a}]}return[]}function tC(r,t,e,n){let i=r.input,o=typeof i?.description=="string"?i.description:void 0,s=typeof i?.subagent_type=="string"?i.subagent_type:void 0,a=r.input!==void 0?jk(r.input):void 0;n.recordSpawn(r.id,{subagentType:s,description:o});let l={...Wn(r.name)??{toolKind:"subagent"}};return o&&(l.subagentDescription=o),s&&(l.subagentAgentName=s),{kind:"action",session:t,action:{type:"session/toolCallReady",turnId:e,toolCallId:r.id,invocationMessage:gi(r.name,Wt(r.name),r.input),...a!==void 0?{toolInput:a}:{},confirmed:"not-needed",_meta:l}}}function nC(r,t,e,n,i,o){let s=r.message.id,a=[];for(let l=0;l<r.message.content.length;l++){let c=r.message.content[l];if(c.type==="text"){a.push({kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"markdown",id:`${e}#${s}#${l}`,content:c.text}}});continue}if(c.type==="thinking"){a.push({kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"reasoning",id:`${e}#${s}#${l}`,content:c.thinking}}});continue}if(c.type==="tool_use"){let u=gs(c.name);n.startToolBlock(l,c.id,u,e),n.toolCalls.seedParsedInput(c.id,c.input),o.noteInnerTool(c.id,i);let d=Wt(u),f=Wn(u),m=Ki(u,c.input);a.push({kind:"action",session:t,action:{type:"session/toolCallStart",turnId:e,toolCallId:c.id,toolName:u,displayName:d,...f?{_meta:f}:{}}}),a.push({kind:"action",session:t,action:{type:"session/toolCallReady",turnId:e,toolCallId:c.id,invocationMessage:gi(u,d,c.input),...m!==void 0?{toolInput:m}:{},confirmed:"not-needed"}});continue}}return a}function jk(r){try{return JSON.stringify(r)}catch{return}}var Mu=class{constructor(){this._entries=new Map}begin(t,e,n){this._entries.set(t,{toolName:e,turnId:n,inputBuffer:"",info:void 0})}appendInputDelta(t,e){let n=this._entries.get(t);n&&(n.inputBuffer+=e)}finalize(t){let e=this._entries.get(t);if(!e)return;let n;if(e.inputBuffer.length>0)try{let o=JSON.parse(e.inputBuffer);o!==null&&typeof o=="object"&&(n=o)}catch{}let i=e.inputBuffer.length>0?e.inputBuffer:void 0;this._writeInfo(e,n,i),e.inputBuffer=""}seedParsedInput(t,e){let n=this._entries.get(t);if(!n)return;let i=e!==null&&typeof e=="object"?e:void 0;this._writeInfo(n,i)}_writeInfo(t,e,n){let i=Wt(t.toolName);t.info={toolName:t.toolName,displayName:i,parsedInput:e,invocationMessage:gi(t.toolName,i,e),toolInput:Ki(t.toolName,e)??n}}lookup(t){let e=this._entries.get(t);if(e)return{turnId:e.turnId,toolName:e.toolName,info:e.info}}complete(t){this._entries.delete(t)}clearPending(t){if(this._entries.size!==0){for(let[e,n]of this._entries)t.warn(`[claudeToolCallRegistry] turn ${n.turnId} ended with pending tool_use ${e} (${n.toolName}); dropping cross-message state`);this._entries.clear()}}};var Uu=class{constructor(){this._activeToolBlocks=new Map;this.toolCalls=new Mu;this._completedFileEdits=new Map}resetMessage(t){this._activeToolBlocks.clear(),this._currentMessageId=t}getCurrentMessageId(){return this._currentMessageId}startToolBlock(t,e,n,i){this._activeToolBlocks.set(t,{toolUseId:e,toolName:n}),this.toolCalls.begin(e,n,i)}getActiveToolBlock(t){return this._activeToolBlocks.get(t)}endToolBlock(t){this._activeToolBlocks.delete(t)}appendToolBlockInputDelta(t,e){let n=this._activeToolBlocks.get(t);n&&this.toolCalls.appendInputDelta(n.toolUseId,e)}finalizeToolBlock(t){let e=this._activeToolBlocks.get(t);e&&this.toolCalls.finalize(e.toolUseId)}lookupToolCall(t){let e=this.toolCalls.lookup(t);return e?{turnId:e.turnId,toolName:e.toolName}:void 0}completeToolCall(t){this.toolCalls.complete(t)}cacheFileEdit(t,e){this._completedFileEdits.set(t,e)}takeFileEdit(t){let e=this._completedFileEdits.get(t);return e&&this._completedFileEdits.delete(t),e}clearPendingToolCalls(t){this.toolCalls.clearPending(t)}};function iC(r,t,e,n,i,o,s){if(i.getLevel()<=1)try{let a=JSON.stringify(r,(l,c)=>typeof c=="string"&&c.length>200?c.slice(0,200)+"\u2026":c);i.trace(`[claudeMapSessionEvents] SDK message type=${r.type}: ${a?.slice(0,2e3)??"<unserializable>"}`)}catch{i.trace(`[claudeMapSessionEvents] SDK message type=${r.type} (unserializable)`)}switch(r.type){case"stream_event":return Lu(Zk(r.event,t,e,n,i,r.parent_tool_use_id,o,s),t,r.parent_tool_use_id,o);case"result":return Xk(r,t,e,n,i,o);case"assistant":return Lu(Gk(r,t,e,n,r.parent_tool_use_id,o),t,r.parent_tool_use_id,o);case"user":return Lu(Jk(r,t,n,i,o),t,r.parent_tool_use_id,o);default:return r.type==="system"?eC(r,t,o):[]}}function Gk(r,t,e,n,i,o){if(i===null){let s=[];for(let a of r.message.content)a.type!=="tool_use"||!Mm.has(a.name)||s.push(tC(a,t,e,o));return s}return nC(r,t,e,n,i,o)}function Jk(r,t,e,n,i){let o=r.message.content;if(!Array.isArray(o))return[];let s=[];for(let a of o){if(a.type!=="tool_result")continue;let l=e.lookupToolCall(a.tool_use_id);if(!l){n.warn(`[claudeMapSessionEvents] tool_result for unknown tool_use_id ${a.tool_use_id}`);continue}let c=a.is_error===!0,u=Qk(a.content)??[],d=e.takeFileEdit(a.tool_use_id);d&&u.push(d);let f=e.toolCalls.lookup(a.tool_use_id)?.info,m=f?wu(f.toolName,f.displayName,f.parsedInput,!c):`${Wt(l.toolName)} finished`;s.push({kind:"action",session:t,action:{type:"session/toolCallComplete",turnId:l.turnId,toolCallId:a.tool_use_id,result:{success:!c,pastTenseMessage:m,content:u.length>0?u:void 0}}}),e.completeToolCall(a.tool_use_id);let h=i.getSpawn(a.tool_use_id);h&&!h.background&&h.markCompleted()&&(s.push({kind:"subagent_completed",session:t,toolCallId:a.tool_use_id}),i.removeSpawn(a.tool_use_id))}return s}function Qk(r){if(typeof r=="string")return[{type:"text",text:r}];if(!Array.isArray(r))return;let t=[];for(let e of r)Yk(e)&&t.push({type:"text",text:e.text});return t.length>0?t:void 0}function Yk(r){if(r===null||typeof r!="object")return!1;let t=r;return t.type==="text"&&typeof t.text=="string"}function Xk(r,t,e,n,i,o){let s=[];if(r.subtype==="success"){let a=Object.keys(r.modelUsage)[0];s.push({kind:"action",session:t,action:{type:"session/usage",turnId:e,usage:{inputTokens:r.usage.input_tokens,outputTokens:r.usage.output_tokens,cacheReadTokens:r.usage.cache_read_input_tokens,...a?{model:a}:{}}}})}n.clearPendingToolCalls(i);for(let a of o.drainForegroundSpawns())i.warn(`[claudeMapSessionEvents] turn ended with pending subagent-spawning tool_use ${a.toolUseId} (agentId=${a.agentId??"<unresolved>"}); dropping cross-message state`);return s}function Zk(r,t,e,n,i,o,s,a){switch(r.type){case"message_start":return n.resetMessage(r.message.id),[];case"content_block_start":{let l=r.content_block;if(l.type==="text")return[{kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"markdown",id:Nu(e,n,r.index,i),content:""}}}];if(l.type==="thinking")return[{kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"reasoning",id:Nu(e,n,r.index,i),content:""}}}];if(l.type==="tool_use"){let c=gs(l.name),u=V_(l.name);n.startToolBlock(r.index,l.id,c,e);let d=!u&&Mm.has(c);o===null?d&&s.recordSpawn(l.id):s.noteInnerTool(l.id,o);let f=Wn(c),m=u?a:void 0;return[{kind:"action",session:t,action:{type:"session/toolCallStart",turnId:e,toolCallId:l.id,toolName:c,displayName:Wt(c),...m?{toolClientId:m}:{},...f?{_meta:f}:{}}}]}return[]}case"content_block_delta":{if(r.delta.type==="text_delta")return[{kind:"action",session:t,action:{type:"session/delta",turnId:e,partId:Nu(e,n,r.index,i),content:r.delta.text}}];if(r.delta.type==="thinking_delta")return[{kind:"action",session:t,action:{type:"session/reasoning",turnId:e,partId:Nu(e,n,r.index,i),content:r.delta.thinking}}];if(r.delta.type==="input_json_delta"){let l=n.getActiveToolBlock(r.index);return l?(n.appendToolBlockInputDelta(r.index,r.delta.partial_json),[{kind:"action",session:t,action:{type:"session/toolCallDelta",turnId:e,toolCallId:l.toolUseId,content:r.delta.partial_json}}]):(i.warn(`[claudeMapSessionEvents] input_json_delta for unknown content-block index ${r.index}`),[])}return[]}case"content_block_stop":{let l=n.getActiveToolBlock(r.index);if(n.finalizeToolBlock(r.index),n.endToolBlock(r.index),!l)return[];let u=n.toolCalls.lookup(l.toolUseId)?.info;if(!u)return[];let d=Wn(l.toolName);return[{kind:"action",session:t,action:{type:"session/toolCallReady",turnId:e,toolCallId:l.toolUseId,invocationMessage:u.invocationMessage,...u.toolInput!==void 0?{toolInput:u.toolInput}:{},confirmed:"not-needed",...d?{_meta:d}:{}}}]}case"message_delta":case"message_stop":return[];default:return[]}}function Nu(r,t,e,n){let i=t.getCurrentMessageId();return i===void 0?(n.warn(`[claudeMapSessionEvents] content block at index ${e} arrived before message_start; using turn-scoped id`),`${r}#${e}`):`${r}#${i}#${e}`}var Ss=class extends T{constructor(e,n,i,o=void 0,s,a){super();this._sessionUri=e;this._subagents=i;this._logService=a;this._onDidProduceSignal=this._register(new x);this.onDidProduceSignal=this._onDidProduceSignal.event;this._mapperState=new Uu;this._clientId=o,this._editObserver=this._register(s.createInstance(bs,e.toString(),n))}setClientId(e){this._clientId=e}async handle(e,n){if(e.type==="assistant"?this._editObserver.observeAssistant(e):e.type==="user"&&n!==void 0&&await this._editObserver.observeUser(e,n,this._mapperState),n!==void 0)try{let i=iC(e,this._sessionUri,n,this._mapperState,this._logService,this._subagents,this._clientId);for(let o of i)this._onDidProduceSignal.fire(o)}catch(i){this._logService.warn(`[ClaudeSdkMessageRouter] mapper threw, skipping message: ${i}`)}}};Ss=w([C(4,qe),C(5,L)],Ss);var Is=class extends T{constructor(e,n,i,o,s,a,l=void 0,c,u){super();this.sessionId=e;this.sessionUri=n;this._logService=u;this._isResumed=!1;this._needsRebind=!1;this._consumerLoopRunning=!1;this._onDidProduceSignal=this._register(new x);this.onDidProduceSignal=this._onDidProduceSignal.event;this._warm=i,this._abortController=o,this._wireAbortHandler(o),this._queue=this._register(c.createInstance(vs,e,()=>this._abortController.signal,d=>this._onDidProduceSignal.fire({kind:"steering_consumed",session:this.sessionUri,id:d}))),this._router=this._register(c.createInstance(Ss,n,s,a,l)),this._register(this._router.onDidProduceSignal(d=>this._onDidProduceSignal.fire(d))),this._register(A(()=>this._abortController.abort())),this._register(A(()=>{Promise.resolve(this._warm[Symbol.asyncDispose]()).catch(d=>this._logService.warn(`[ClaudeSdkPipeline] WarmQuery dispose failed: ${d}`))}))}async reloadPlugins(){await(await this._ensureQueryBound()).reloadPlugins()}async snapshotResolvedCustomizations(){let e=await this._ensureQueryBound(),[n,i,o]=await Promise.all([e.supportedCommands(),e.supportedAgents(),e.mcpServerStatus()]);return{commands:n,agents:i,mcpServers:o}}async _ensureQueryBound(){return this._query||(this._query=this._warm.query(this._queue.iterable),await this._replayCurrentConfig()),this._query}get isResumed(){return this._isResumed}get isAborted(){return this._abortController.signal.aborted}rebindForRestart(){return this._rebindQuery("restart")}setClientId(e){this._router.setClientId(e)}attachRematerializer(e){this._rematerializer=e}seedCurrentConfig(e,n,i){this._currentModel=e,this._currentEffort=n,this._currentPermissionMode=i,this._appliedModel=e,this._appliedEffort=n,this._appliedPermissionMode=i}async setModel(e){if(this._currentModel=e,this._query&&e!==this._appliedModel)try{await this._query.setModel(e),this._appliedModel=e}catch(n){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] setModel failed: ${n}`)}}async setEffort(e){if(this._currentEffort=e,this._query&&e!==this._appliedEffort)try{await this._query.applyFlagSettings({effortLevel:e}),this._appliedEffort=e}catch(n){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] setEffort failed: ${n}`)}}async send(e,n){if(this._needsRebind&&await this._rebindQuery("recover"),this._abortController.signal.aborted)throw new re;this._query||(this._query=this._warm.query(this._queue.iterable),await this._replayCurrentConfig()),this._ensureConsumerLoop();let i={sdkMessage:e,sdkUuid:typeof e.uuid=="string"?e.uuid:n,turnId:n,deferred:new fe};return this._queue.push(i)}injectSteering(e,n){if(this._abortController.signal.aborted){this._logService.warn(`[Claude:${this.sessionId}] injectSteering: dropped (controller aborted) id=${n}`);return}let i=this._queue.peekParent();if(!i){this._logService.warn(`[Claude:${this.sessionId}] injectSteering: dropped (no in-flight turn) id=${n}`);return}let o=typeof e.uuid=="string"?e.uuid:n;this._queue.push({sdkMessage:e,sdkUuid:o,turnId:i.turnId,deferred:new fe,steeringPendingId:n}).catch(()=>{}),this._logService.info(`[Claude:${this.sessionId}] injectSteering: enqueued id=${n} sdkUuid=${o}`)}abort(){this._abortController.signal.aborted||(this._abortController.abort(),this._queue.failAll(new re),this._query=void 0,this._needsRebind=!0)}async setPermissionMode(e){this._currentPermissionMode=e,this._query&&e!==this._appliedPermissionMode&&(await this._query.setPermissionMode(e),this._appliedPermissionMode=e)}_wireAbortHandler(e){e.signal.addEventListener("abort",()=>{this._queue.notifyAborted()},{once:!0})}_ensureConsumerLoop(){this._consumerLoopRunning||(this._consumerLoopRunning=!0,this._processMessages().catch(e=>this._logService.error(`[ClaudeSdkPipeline:${this.sessionId}] _processMessages crashed: ${e}`)).finally(()=>{this._consumerLoopRunning=!1}))}async _replayCurrentConfig(){try{this._currentModel!==void 0&&this._currentModel!==this._appliedModel&&(await this._query?.setModel(this._currentModel),this._appliedModel=this._currentModel),this._currentEffort!==void 0&&this._currentEffort!==this._appliedEffort&&(await this._query?.applyFlagSettings({effortLevel:this._currentEffort}),this._appliedEffort=this._currentEffort),this._currentPermissionMode!==void 0&&this._currentPermissionMode!==this._appliedPermissionMode&&(await this._query?.setPermissionMode(this._currentPermissionMode),this._appliedPermissionMode=this._currentPermissionMode)}catch(e){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] _replayCurrentConfig failed: ${e}`)}}async _rebindQuery(e){if(!this._rematerializer)throw new Error(`ClaudeSdkPipeline.rebind: no rematerializer attached (reason=${e})`);let n=this._warm,i=new AbortController;this._abortController=i;let o=await this._rematerializer(e);if(this._store.isDisposed)throw o.abortController.abort(),Promise.resolve(o.warm[Symbol.asyncDispose]()).catch(s=>this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] rebind-after-dispose: warm dispose failed: ${s}`)),new re;if(i.signal.aborted)throw o.abortController.abort(),Promise.resolve(o.warm[Symbol.asyncDispose]()).catch(s=>this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] rebind-aborted: warm dispose failed: ${s}`)),Promise.resolve(n[Symbol.asyncDispose]()).catch(s=>this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] previous WarmQuery dispose failed during aborted rebind: ${s}`)),this._queue.failAll(new re),this._query=void 0,this._needsRebind=!0,new re;Promise.resolve(n[Symbol.asyncDispose]()).catch(s=>this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] previous WarmQuery dispose failed during rebind: ${s}`)),this._warm=o.warm,this._abortController=o.abortController,this._wireAbortHandler(o.abortController),this._queue.resetForRebind(),this._needsRebind=!1,this._appliedModel=void 0,this._appliedEffort=void 0,this._appliedPermissionMode=void 0,this._query=this._warm.query(this._queue.iterable),await this._replayCurrentConfig()}async _processMessages(){let e=this._query;if(!e)throw new Error("ClaudeSdkPipeline._processMessages called before query was bound");try{for await(let n of e){if(this._abortController.signal.aborted)throw new re;n.type==="system"&&n.subtype==="init"&&!this._isResumed&&(this._isResumed=!0);let i=this._queue.peekParent()?.turnId;try{await this._router.handle(n,i)}catch(o){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] router threw, skipping: ${o}`)}if(n.type==="result"){let o=this._queue.settleHead();this._logService.info(`[Claude:${this.sessionId}] result for sdkUuid=${o?.sdkUuid}`),o&&this._queue.isEmpty&&this._onDidProduceSignal.fire({kind:"action",session:this.sessionUri,action:{type:"session/turnComplete",turnId:o.turnId}})}}throw this._abortController.signal.aborted?new re:new Error("Claude SDK stream ended without a result message")}catch(n){let i=n instanceof Error?n:new Error(String(n));if(this._query===e&&(this._queue.failAll(i),this._query=void 0,this._needsRebind=!0),!Xi(i))throw i}}};Is=w([C(7,qe),C(8,L)],Is);function eA(r,t,e){return hs(r,t)??e}var mi=class extends T{constructor(e,n,i,o,s,a,l,c,u,d,f,m,h,v,S,_,b){super();this.sessionId=e;this.sessionUri=n;this.workingDirectory=i;this._pendingClientToolCalls=u;this._permissionModeFallback=f;this._metadataStore=m;this._instantiationService=h;this._configurationService=v;this._sdkService=S;this._sessionDataService=_;this._logService=b;this.subagents=this._register(new Eu);this._pendingPermissions=new qi;this._pendingUserInputs=new qi;this.clientCustomizationsDiff=this._register(new ku);this._onDidSessionProgress=this._register(new x);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidCustomizationsChange=this._register(new x);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this.project=o,this._provisionalModel=s,this._provisionalAgent=a,this.provisionalConfig=l,this.abortController=c,this.toolDiff=this._register(d),this._register(this.clientCustomizationsDiff.onDidChange(()=>this._onDidCustomizationsChange.fire()))}get pendingClientToolCalls(){return this._pendingClientToolCalls}get permissionModeFallback(){return this._permissionModeFallback}static createProvisional(e,n,i,o,s,a,l,c,u,d,f){return f.createInstance(mi,e,n,i,o,s,a,l,new AbortController,c,new Pu,u,d)}async materialize(e){if(this._pipeline)throw new Error("ClaudeAgentSession is already materialized");if(!this.workingDirectory)throw new Error(`Cannot materialize Claude session ${this.sessionId}: workingDirectory is required`);let n=hs(this._configurationService,this.sessionUri)??this._permissionModeFallback,i=await Dm(this.toolDiff,this._pendingClientToolCalls,this._sdkService),o=await Am({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:this.abortController,permissionMode:n,canUseTool:e.canUseTool,isResume:e.isResume,mcpServers:i,plugins:this.clientCustomizationsDiff.consume(),agent:this._resolveAgentName(this._provisionalAgent)},e.proxyHandle,c=>this._logService.error(`[Claude SDK stderr] ${c}`),c=>this._logService.info(`[Claude] declining elicitation from MCP server (Phase 7 stub): ${c}`));this._logService.info(`[Claude] session ${this.sessionId}: enableFileCheckpointing=${o.enableFileCheckpointing} isResume=${e.isResume}`);let s=await this._sdkService.startup({options:o});if(this.abortController.signal.aborted)throw await s[Symbol.asyncDispose](),new re;let a=this._sessionDataService.openDatabase(this.sessionUri),l;try{l=this._register(this._instantiationService.createInstance(Is,this.sessionId,this.sessionUri,s,this.abortController,a,this.subagents,this.toolDiff.model.state.get().clientId))}catch(c){throw a.dispose(),await s[Symbol.asyncDispose](),c}if(this._register(l.onDidProduceSignal(c=>this._onDidSessionProgress.fire(c))),this._pipeline=l,this._sdkBundler=this._register(this._instantiationService.createInstance(ys,this.workingDirectory)),l.seedCurrentConfig(this._provisionalModel?.id,Im(ol(this._provisionalModel)),n),!e.isResume)try{await this._metadataStore.write(this.sessionUri,{customizationDirectory:this.workingDirectory,model:this._provisionalModel,permissionMode:n})}catch(c){throw this._logService.error("[Claude] Failed to persist customization directory; aborting materialize",c),c}if(this.abortController.signal.aborted)throw new re;l.attachRematerializer(async c=>{let u=hs(this._configurationService,this.sessionUri)??this._permissionModeFallback;try{let d=await Dm(this.toolDiff,this._pendingClientToolCalls,this._sdkService),f=new AbortController,m=await Am({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:f,permissionMode:u,canUseTool:e.canUseTool,isResume:!0,mcpServers:d,plugins:this.clientCustomizationsDiff.consume(),agent:this._resolveAgentName(this._provisionalAgent)},e.proxyHandle,v=>this._logService.error(`[Claude SDK stderr] ${v}`),v=>this._logService.info(`[Claude] declining elicitation from MCP server (Phase 7 stub): ${v}`));return this._logService.info(`[Claude] session ${this.sessionId}: resume rebuild agent=${m.agent??"(none)"}`),{warm:await this._sdkService.startup({options:m}),abortController:f}}catch(d){throw this.toolDiff.markDirty(),this.clientCustomizationsDiff.markDirty(),d}}),this._onDidCustomizationsChange.fire()}get isPipelineReady(){return this._pipeline!==void 0}get provisionalModel(){return this._provisionalModel}_requirePipeline(){if(!this._pipeline)throw new Error("ClaudeAgentSession is not materialized");return this._pipeline}get isResumed(){return this._requirePipeline().isResumed}seedBijectiveState(e){this._requirePipeline().seedCurrentConfig(e.model,e.effort,e.permissionMode)}attachRematerializer(e){this._requirePipeline().attachRematerializer(e)}async send(e,n){let i=this._requirePipeline();return this.toolDiff.hasDifference||this.clientCustomizationsDiff.hasDifference?await this._rebindForSyncedState():await i.setPermissionMode(eA(this._configurationService,this.sessionUri,this._permissionModeFallback)),i.send(e,n)}async _rebindForSyncedState(){this._pendingClientToolCalls.rejectAll(new re),await this._requirePipeline().rebindForRestart(),this._onDidCustomizationsChange.fire()}abort(){this._pendingPermissions.denyAll(!1),this._pendingUserInputs.denyAll({response:"cancel"}),this._requirePipeline().abort()}async setModel(e){if(this._provisionalModel=e,this._pipeline){let n=ol(e),i=Im(n);n==="max"&&this._logService.warn(`[Claude:${this.sessionId}] setModel: 'max' effort clamped to 'xhigh' (Copilot CAPI has no 'max' model yet)`),await this._pipeline.setModel(e.id),i!==void 0&&await this._pipeline.setEffort(i)}await this._metadataStore.write(this.sessionUri,{model:e})}get provisionalAgent(){return this._provisionalAgent}async setAgent(e){this._provisionalAgent!==e&&(this._provisionalAgent=e,this._pipeline&&this.clientCustomizationsDiff.markDirty(),await this._metadataStore.write(this.sessionUri,{agent:e??null}))}_resolveAgentName(e){if(!e)return;let o=(y.parse(e.uri).path.split("/").pop()??"").replace(/\.md$/i,"");if(!o){this._logService.warn(`[Claude:${this.sessionId}] _resolveAgentName: could not extract agent name from URI '${e.uri}'`);return}return o}injectSteering(e){let n=this._requirePipeline();if(n.isAborted)return;let o={type:"user",message:{role:"user",content:Ou(e.message.text,e.message.attachments)},session_id:this.sessionId,parent_tool_use_id:null,priority:"now",uuid:e.id};n.injectSteering(o,e.id)}setPermissionMode(e){return this._requirePipeline().setPermissionMode(e)}requestPermission(e){return!this._pipeline||this._pipeline.isAborted?Promise.resolve(!1):this._pendingPermissions.registerAndFire(e.toolUseID,()=>{this._onDidSessionProgress.fire({kind:"pending_confirmation",session:this.sessionUri,state:e.state,permissionKind:e.permissionKind,...e.permissionPath!==void 0?{permissionPath:e.permissionPath}:{},...e.parentToolCallId!==void 0?{parentToolCallId:e.parentToolCallId}:{}})})}respondToPermissionRequest(e,n){return this._pendingPermissions.respond(e,n)}requestUserInput(e,n){return!this._pipeline||this._pipeline.isAborted?Promise.resolve({response:"cancel"}):this._pendingUserInputs.registerAndFire(e.id,()=>{this._onDidSessionProgress.fire({kind:"action",session:this.sessionUri,action:{type:"session/inputRequested",request:e},...n!==void 0?{parentToolCallId:n}:{}})})}respondToUserInputRequest(e,n,i){return this._pendingUserInputs.respond(e,{response:n,answers:i})}setClientTools(e,n){this.toolDiff.model.setTools(e,n),this._pipeline&&this._pipeline.setClientId(this.toolDiff.model.state.get().clientId)}completeClientToolCall(e,n){let i=G_(n,e);return this._pendingClientToolCalls.respond(e,i)}async rebindForClientTools(){await this._rebindForSyncedState()}adoptClientCustomizations(e){this.clientCustomizationsDiff.model.setSyncedCustomizations(e)}setClientCustomizationEnabled(e,n){this.clientCustomizationsDiff.model.setEnabled(e,n)}getClientCustomizations(){return this.clientCustomizationsDiff.model.state.get().synced}async getSessionCustomizations(){let{synced:e,enablement:n}=this.clientCustomizationsDiff.model.state.get(),i;if(this._pipeline&&this._sdkBundler){let o;try{o=await this._pipeline.snapshotResolvedCustomizations()}catch(s){this._logService.warn(`[Claude:${this.sessionId}] snapshotResolvedCustomizations failed`,s)}if(o)try{i=await this._sdkBundler.bundle(o)}catch(s){this._logService.warn(`[Claude:${this.sessionId}] SDK bundle failed`,s)}}return Y_(e,n,i)}dispose(){this._pendingPermissions.denyAll(!1),this._pendingUserInputs.denyAll({response:"cancel"}),this._pendingClientToolCalls.rejectAll(new re),super.dispose()}};mi=w([C(12,qe),C(13,Je),C(14,ps),C(15,vt),C(16,L)],mi);function rC(r,t){let e=typeof r.plan=="string"?r.plan:"";return{status:"pending-confirmation",toolCallId:t,toolName:"ExitPlanMode",displayName:Wt("ExitPlanMode"),invocationMessage:{markdown:e},toolInput:JSON.stringify(r),confirmationTitle:g(1920,null),options:[{id:"approve",label:g(1918,null),kind:"approve"},{id:"deny",label:g(1919,null),kind:"deny"}]}}function oC(r){let t=r;if(t.questions?.length)return{questions:t.questions}}function sC(r,t){return r||`q-${t}`}function aC(r){return r.questions.map((t,e)=>{let n=t.options.map(o=>({id:o.label,label:o.label,...o.description!==void 0?{description:o.description}:{}})),i=sC(t.header,e);return t.multiSelect?{id:i,kind:"multi-select",title:t.header,message:t.question,options:n,allowFreeformInput:t.allowFreeformInput??!1}:{id:i,kind:"single-select",title:t.header,message:t.question,options:n,allowFreeformInput:t.allowFreeformInput??!1}})}function lC(r,t){let e={};for(let n=0;n<r.questions.length;n++){let i=r.questions[n],o=t[sC(i.header,n)];if(!o||o.state==="skipped")continue;let s=[],a=o.value;a.kind==="selected"?(a.value&&s.push(a.value),a.freeformValues&&s.push(...a.freeformValues)):a.kind==="selected-many"?(s.push(...a.value),a.freeformValues&&s.push(...a.freeformValues)):a.kind==="text"&&s.push(a.value),s.length>0&&(e[i.question]=s.join(", "))}return e}async function Um(r,t,e,n,i){let o=r.getSession(t);if(!o)return{behavior:"deny",message:"Session is no longer active"};if(i.signal.aborted)return{behavior:"deny",message:"SDK aborted the tool request"};let s=()=>{o.respondToPermissionRequest(i.toolUseID,!1),o.respondToUserInputRequest(i.toolUseID,"cancel")};i.signal.addEventListener("abort",s);try{return await tA(r,o,e,n,i)}finally{i.signal.removeEventListener("abort",s)}}async function tA(r,t,e,n,i){if(L_.has(e))return nA(r,t,e,n,i);let o=xu(e),s=Wt(e),a=i.blockedPath??Fn(e,n),l=Ki(e,n),c=Wn(e),u={status:"pending-confirmation",toolCallId:i.toolUseID,toolName:e,displayName:s,invocationMessage:gi(e,s,n),toolInput:l,confirmationTitle:M_(e),...c?{_meta:c}:{}},d=Fm(t,i);return await t.requestPermission({toolUseID:i.toolUseID,state:u,permissionKind:o,...a!==void 0?{permissionPath:a}:{},...d!==void 0?{parentToolCallId:d}:{}})?{behavior:"allow",updatedInput:n}:{behavior:"deny",message:"User declined"}}function Fm(r,t){if(!t.agentID)return;let e=r.subagents.getParentSpawn(t.toolUseID);if(e)return e.setAgentId(t.agentID),e.toolUseId}function nA(r,t,e,n,i){switch(e){case"ExitPlanMode":return iA(r,t,n,i);case"AskUserQuestion":return rA(r,t,n,i);default:return Promise.resolve({behavior:"deny",message:`Unsupported interactive tool: ${e}`})}}async function iA(r,t,e,n){let i=n.toolUseID,o=Fm(t,n);return await t.requestPermission({toolUseID:i,state:rC(e,i),permissionKind:xu("ExitPlanMode"),...o!==void 0?{parentToolCallId:o}:{}})?(r.configurationService.updateSessionConfig(t.sessionUri.toString(),{permissionMode:"acceptEdits"}),{behavior:"allow",updatedInput:e}):{behavior:"deny",message:"The user declined the plan, maybe ask why?"}}async function rA(r,t,e,n){let i=n.toolUseID,o=oC(e);if(!o)return{behavior:"deny",message:"AskUserQuestion called without questions"};let s=Fm(t,n),a=await t.requestUserInput({id:i,questions:aC(o)},s);if(a.response!=="accept"||!a.answers)return{behavior:"deny",message:"The user cancelled the question"};let l=lC(o,a.answers);return Object.keys(l).length===0?{behavior:"deny",message:"The user cancelled the question"}:{behavior:"allow",updatedInput:{...e,answers:l}}}var oA=new Map([["opus",new Set(["1m"])]]),Wm=new Map;function _s(r){let t=r.toLowerCase();if(Wm.has(t))return Wm.get(t);let e=aA(t);return Wm.set(t,e),e}var sA=/^(?<base>.*)-(?<date>\d{8})$/;function aA(r){let t="",e=r,n=sA.exec(r);n?.groups&&(e=n.groups.base,t=n.groups.date);let i=e.match(/^claude-(?<name>\w+)-(?<major>\d+)-(?<minor>\d+)(?:-(?<mod>.+))?$/);if(i?.groups)return ul(i.groups.name,i.groups.major,i.groups.minor,dl(i.groups.mod,t));let o=e.match(/^claude-(?<major>\d+)-(?<minor>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(o?.groups)return ul(o.groups.name,o.groups.major,o.groups.minor,dl(o.groups.mod,t));let s=e.match(/^claude-(?<name>\w+)-(?<major>\d+)\.(?<minor>\d+)(?:-(?<mod>.+))?$/);if(s?.groups)return ul(s.groups.name,s.groups.major,s.groups.minor,dl(s.groups.mod,t));let a=e.match(/^claude-(?<name>\w+)-(?<major>\d+)(?:-(?<mod>.+))?$/);if(a?.groups)return ul(a.groups.name,a.groups.major,void 0,dl(a.groups.mod,t));let l=e.match(/^claude-(?<major>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(l?.groups)return ul(l.groups.name,l.groups.major,void 0,dl(l.groups.mod,t));let c=e.match(/^(?<name>\w+)$/);if(c?.groups)return lA(c.groups.name)}function dl(r,t){return r&&t?`${r}-${t}`:r||t}function cC(r,t,e,n,i){let o=e!==void 0?`claude-${r}-${t}${n}${e}`:`claude-${r}-${t}`;return i?`${o}-${i}`:o}function lA(r){return{name:r,version:"",modifiers:"",toSdkModelId:()=>r,toEndpointModelId:()=>r}}function ul(r,t,e,n){let i=e!==void 0?`${t}.${e}`:t,o=cA(r,n);return{name:r,version:i,modifiers:n,toSdkModelId:()=>cC(r,t,e,"-",o),toEndpointModelId:()=>cC(r,t,e,".",o)}}function cA(r,t){if(!t)return"";let e=oA.get(r);if(!e)return"";if(e.has(t))return t;let n=t.split("-")[0];return e.has(n)?n:""}import{once as uA}from"events";var dA=["interleaved-thinking","context-management","advanced-tool-use"];function dC(r){let t=r.split(",").map(e=>e.trim()).filter(e=>e&&dA.some(n=>e.startsWith(n+"-")));return t.length>0?t.join(","):void 0}function $m(r,t){return{type:"error",error:{type:r,message:t},request_id:null}}function on(r,t,e,n){r.writeHead(t,{"Content-Type":"application/json"}),r.end(JSON.stringify($m(e,n)))}function uC(r,t,e){r.writeHead(t,{"Content-Type":"application/json"}),r.end(JSON.stringify(e))}function pC(r){return`event: error
data: ${JSON.stringify(r)}

`}var Vm=Object.freeze({valid:!1,sessionId:void 0});function fC(r,t){let e=r.authorization;if(typeof e!="string"||!e.startsWith("Bearer "))return Vm;let n=e.slice(7),i=n.indexOf(".");if(i===-1)return Vm;let o=n.slice(0,i),s=n.slice(i+1);return o!==t||s.length===0?Vm:{valid:!0,sessionId:s}}var Fu=V("claudeProxyService"),pA=new Set(["anthropic"]),fA="/v1/messages",ji="ClaudeProxyService";function gA(){let r=new Uint8Array(32);crypto.getRandomValues(r);let t="";for(let e=0;e<r.length;e++)t+=r[e].toString(16).padStart(2,"0");return t}var Cs=class{constructor(t,e){this._logService=t;this._copilotApiService=e;this._disposed=!1}async start(t){if(this._disposed)throw new Error("ClaudeProxyService has been disposed");let e=await this._ensureRuntime(t);if(this._disposed||this._runtime!==e)throw new Error("ClaudeProxyService has been disposed");e.githubToken=t,e.refcount++;let n=!1;return{baseUrl:e.baseUrl,nonce:e.nonce,dispose:()=>{n||(n=!0,this._releaseHandle(e))}}}dispose(){this._disposed||(this._disposed=!0,this._teardownRuntime())}_ensureRuntime(t){return this._runtime?Promise.resolve(this._runtime):(this._starting||(this._starting=(async()=>{try{let e=await this._startServer(t);if(this._disposed)throw e.server.closeAllConnections(),e.server.close(),new Error("ClaudeProxyService has been disposed");return this._runtime=e,e}finally{this._starting=void 0}})()),this._starting)}_releaseHandle(t){this._runtime===t&&(t.refcount--,t.refcount===0&&this._teardownRuntime())}_teardownRuntime(){let t=this._runtime;if(t){this._runtime=void 0;for(let e of t.inFlight)e.ac.abort();t.server.closeAllConnections(),t.server.close(e=>{e&&this._logService.warn(`[${ji}] server.close error: ${e.message}`)})}}async _startServer(t){let e=gA(),n=new Set,o=(await import("http")).createServer();await new Promise((c,u)=>{let d=f=>{u(f)};o.once("error",d),o.listen(0,"127.0.0.1",()=>{o.removeListener("error",d),c()})});let s=o.address();if(!s||typeof s=="string")throw o.close(),new Error(`${ji} failed to bind: unexpected address ${String(s)}`);let a=`http://127.0.0.1:${s.port}`;this._logService.info(`[${ji}] listening on ${a}`);let l={server:o,baseUrl:a,nonce:e,inFlight:n,githubToken:t,refcount:0};return o.on("request",(c,u)=>{this._handleRequest(c,u,l).catch(d=>{if(this._logService.error(`[${ji}] unhandled request error: ${pl(d)}`),u.headersSent){if(!u.writableEnded)try{u.end()}catch{}}else try{on(u,500,"api_error","Internal proxy error")}catch{}})}),l}async _handleRequest(t,e,n){let i=t.method??"GET",o=new URL(t.url??"/","http://127.0.0.1").pathname;if(this._logService.trace(`[${ji}] ${i} ${o}`),i==="GET"&&o==="/"){e.writeHead(200,{"Content-Type":"text/plain"}),e.end("ok");return}if(!fC(t.headers,n.nonce).valid){on(e,401,"authentication_error","Invalid authentication");return}if(i==="GET"&&o==="/v1/models"){await this._handleModels(e,n);return}if(i==="POST"&&o==="/v1/messages"){await this._handleMessages(t,e,n);return}if(i==="POST"&&o==="/v1/messages/count_tokens"){on(e,501,"api_error","count_tokens not supported by CAPI");return}on(e,404,"not_found_error",`No route for ${i} ${o}`)}async _handleModels(t,e){let n;try{n=await this._copilotApiService.models(e.githubToken)}catch(s){this._writeUpstreamErrorResponse(t,s);return}let i=[];for(let s of n){if(!mA(s))continue;let a=_s(s.id),l=a?a.toSdkModelId():s.id;i.push({id:l,type:"model",display_name:s.name||l,created_at:"1970-01-01T00:00:00Z",capabilities:null,max_input_tokens:null,max_tokens:null})}let o={data:i,has_more:!1,first_id:i.length>0?i[0].id:null,last_id:i.length>0?i[i.length-1].id:null};t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(o))}async _handleMessages(t,e,n){let i;try{i=await vA(t)}catch(h){on(e,400,"invalid_request_error",`Failed to read request body: ${pl(h)}`);return}let o;try{o=JSON.parse(i)}catch{on(e,400,"invalid_request_error","Request body is not valid JSON");return}if(!o||typeof o!="object"){on(e,400,"invalid_request_error","Request body must be a JSON object");return}let s=o,a=s.model;if(typeof a!="string"||a.length===0){on(e,400,"invalid_request_error","Missing required field: model");return}if(!Array.isArray(s.messages)){on(e,400,"invalid_request_error","Missing required field: messages");return}let l=_s(a);if(!l){on(e,404,"not_found_error",`Unknown model: ${a}`);return}let c=l.toEndpointModelId();s.model=c;let u=s.stream===!0,d=yA(t.headers),f={ac:new AbortController,res:e,clientGone:!1};n.inFlight.add(f);let m=()=>{f.clientGone=!0,f.ac.abort()};e.on("close",m);try{u?await this._streamMessages(s,d,e,f,n,a):await this._sendNonStreamingMessage(s,d,e,f,n,a)}finally{e.removeListener("close",m),n.inFlight.delete(f)}}async _sendNonStreamingMessage(t,e,n,i,o,s){let a={headers:e,signal:i.ac.signal},l;try{l=await this._copilotApiService.messages(o.githubToken,t,a)}catch(d){if(i.ac.signal.aborted){!i.clientGone&&!n.writableEnded&&n.destroy();return}this._writeUpstreamErrorResponse(n,d);return}let c=gC(l.model,this._logService)??s,u={...l,model:c};n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(u))}async _streamMessages(t,e,n,i,o,s){let a={headers:e,signal:i.ac.signal},l;try{l=this._copilotApiService.messages(o.githubToken,t,a)}catch(d){if(i.ac.signal.aborted){!i.clientGone&&!n.writableEnded&&n.destroy();return}this._writeUpstreamErrorResponse(n,d);return}let c;try{c=await l.next()}catch(d){if(i.ac.signal.aborted){!i.clientGone&&!n.writableEnded&&n.destroy();return}this._writeUpstreamErrorResponse(n,d);return}n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),n.flushHeaders(),bA(n);let u=async d=>{let f=hA(d,this._logService),m=`event: ${f.type}
data: ${JSON.stringify(f)}

`;if(!n.write(m))try{await uA(n,"drain",{signal:i.ac.signal})}catch{return!1}return!0};try{if(!c.done&&!await u(c.value))return;for(;;){let d;try{d=await l.next()}catch(m){if(i.ac.signal.aborted){!i.clientGone&&!n.writableEnded&&n.destroy();return}let h=m instanceof kr?m.envelope:$m("api_error",pl(m));if(!n.writableEnded){try{n.write(pC(h))}catch{}try{n.end()}catch{}}return}if(d.done)break;if(!await u(d.value))return}n.writableEnded||n.end()}catch(d){if(this._logService.warn(`[${ji}] stream loop unexpected error: ${pl(d)}`),!n.writableEnded)try{n.end()}catch{}}}_writeUpstreamErrorResponse(t,e){if(t.headersSent){if(this._logService.warn(`[${ji}] cannot write upstream error after headers sent: ${pl(e)}`),!t.writableEnded)try{t.end()}catch{}return}if(e instanceof kr){let n=e.status===Sm?502:e.status;uC(t,n,e.envelope);return}on(t,502,"api_error",e instanceof Error?e.message:String(e))}};Cs=w([C(0,L),C(1,cs)],Cs);function mA(r){return pA.has(r.vendor.toLowerCase())?Array.isArray(r.supported_endpoints)&&r.supported_endpoints.includes(fA):!1}function gC(r,t){let e=_s(r);if(!e){t.warn(`[${ji}] outbound model ID could not be parsed for SDK rewrite: ${r}`);return}return e.toSdkModelId()}function hA(r,t){if(r.type!=="message_start")return r;let e=gC(r.message.model,t);return e===void 0||e===r.message.model?r:{...r,message:{...r.message,model:e}}}function yA(r){let t={},e=r["anthropic-version"];typeof e=="string"&&e.length>0&&(t["anthropic-version"]=e);let n=r["anthropic-beta"];if(typeof n=="string"&&n.length>0){let i=dC(n);i!==void 0&&(t["anthropic-beta"]=i)}return t}function vA(r){return new Promise((t,e)=>{let n=[];r.on("data",i=>n.push(Buffer.isBuffer(i)?i:Buffer.from(i))),r.on("end",()=>t(Buffer.concat(n).toString("utf8"))),r.on("error",e)})}function bA(r){let t=r.socket;if(t&&typeof t.setNoDelay=="function")try{t.setNoDelay(!0)}catch{}}function pl(r){return r instanceof Error?r.message:String(r)}var Tt=class{constructor(t,e){this._provider=t;this._sessionDataService=e}static{this.KEY_CUSTOMIZATION_DIRECTORY="claude.customizationDirectory"}static{this.KEY_MODEL="claude.model"}static{this.KEY_PERMISSION_MODE="claude.permissionMode"}static{this.KEY_AGENT="claude.agent"}async write(t,e){let n=this._sessionDataService.openDatabase(t),i=n.object;try{let o=[];e.customizationDirectory&&o.push(i.setMetadata(Tt.KEY_CUSTOMIZATION_DIRECTORY,e.customizationDirectory.toString())),e.model&&o.push(i.setMetadata(Tt.KEY_MODEL,IA(e.model))),e.permissionMode&&o.push(i.setMetadata(Tt.KEY_PERMISSION_MODE,e.permissionMode)),e.agent!==void 0&&o.push(i.setMetadata(Tt.KEY_AGENT,e.agent===null?"":JSON.stringify({uri:e.agent.uri}))),await Promise.all(o)}finally{n.dispose()}}async read(t){let e=await this._sessionDataService.tryOpenDatabase(t);if(!e)return{};try{let[n,i,o,s]=await Promise.all([e.object.getMetadata(Tt.KEY_CUSTOMIZATION_DIRECTORY),e.object.getMetadata(Tt.KEY_MODEL),e.object.getMetadata(Tt.KEY_PERMISSION_MODE),e.object.getMetadata(Tt.KEY_AGENT)]);return{customizationDirectory:n?y.parse(n):void 0,model:_A(i),permissionMode:ds(o),agent:SA(s)}}finally{e.dispose()}}project(t,e){return{session:H.uri(this._provider,t.sessionId),startTime:t.createdAt??t.lastModified,modifiedTime:t.lastModified,summary:t.customTitle??t.summary,workingDirectory:t.cwd?y.file(t.cwd):void 0,customizationDirectory:e.customizationDirectory,model:e.model,agent:e.agent}}};Tt=w([C(1,vt)],Tt);function SA(r){if(r)try{let t=JSON.parse(r);if(t&&typeof t=="object"&&typeof t.uri=="string")return{uri:t.uri}}catch{}}function IA(r){return JSON.stringify(r)}function _A(r){if(r){try{let t=JSON.parse(r);if(t&&typeof t=="object"&&typeof t.id=="string"){let e={id:t.id};if(t.config&&typeof t.config=="object"){let n={};for(let[i,o]of Object.entries(t.config))typeof o=="string"&&(n[i]=o);Object.keys(n).length>0&&(e.config=n)}return e}}catch{}return{id:r}}}function CA(r){return r.vendor==="Anthropic"&&!!r.supported_endpoints?.includes("/v1/messages")&&!!r.model_picker_enabled&&!!r.capabilities?.supports?.tool_calls&&_s(r.id)!==void 0}function TA(r,t){let e=r.capabilities?.supports,n=(e?.reasoning_effort??[]).filter(A_),i=D_(n),o=r.policy?.state,s=r.billing?.multiplier;return{provider:t,id:r.id,name:r.name,maxContextWindow:r.capabilities?.limits?.max_context_window_tokens,supportsVision:!!e?.vision,...i?{configSchema:i}:{},...o?{policyState:o}:{},...typeof s=="number"?{_meta:{multiplierNumeric:s}}:{}}}var Ts=class extends T{constructor(e,n,i,o,s,a,l,c){super();this._logService=e;this._copilotApiService=n;this._claudeProxyService=i;this._sdkService=o;this._gitService=s;this._configurationService=a;this._instantiationService=l;this._pluginManager=c;this.id="claude";this._onDidSessionProgress=this._register(new x);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidCustomizationsChange=this._register(new x);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this._models=In(this,[]);this.models=this._models;this._sessions=this._register(new We);this._onDidMaterializeSession=this._register(new x);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._disposeSequencer=new Ze;this._sessionSequencer=new Ze;this._metadataStore=l.createInstance(Tt,this.id)}_findAnySession(e){return this._sessions.get(e)?.session}getDescriptor(){return{provider:this.id,displayName:g(1917,null),description:g(1916,null)}}getProtectedResources(){return[lo]}_ensureAuthenticated(){let e=this._proxyHandle;if(!e)throw new N(Io,"Authentication is required to use Claude",this.getProtectedResources());return e}async authenticate(e,n){if(e!==lo.resource)return!1;if(!(this._githubToken!==n))return this._logService.info("[Claude] Auth token unchanged"),!0;let o=await this._claudeProxyService.start(n),s=this._proxyHandle;return this._proxyHandle=o,this._githubToken=n,this._logService.info("[Claude] Auth token updated"),s?.dispose(),this._refreshModels(),!0}async _refreshModels(){let e=this._githubToken;if(!e){this._models.set([],void 0);return}try{let n=await this._copilotApiService.models(e);if(this._githubToken!==e)return;let i=n.filter(CA).sort((o,s)=>Number(s.is_chat_default)-Number(o.is_chat_default)).map(o=>TA(o,this.id));this._models.set(i,void 0)}catch(n){this._logService.error(n,"[Claude] Failed to refresh models"),this._githubToken===e&&this._models.set([],void 0)}}async createSession(e={}){if(this._ensureAuthenticated(),e.fork)throw new Error("TODO: Phase 6.5: fork requires message-UUID lookup via sdk.getSessionMessages");let n=e.session?H.id(e.session):q(),i=H.uri(this.id,n),o=this._findAnySession(n);if(o)return o.isPipelineReady?{session:i,workingDirectory:e.workingDirectory}:{session:o.sessionUri,workingDirectory:o.workingDirectory,provisional:!0,...o.project?{project:o.project}:{}};let s=e.workingDirectory?await fi({cwd:e.workingDirectory.fsPath},this._gitService):void 0,a=this._resolvePermissionMode(e.config),l=mi.createProvisional(n,i,e.workingDirectory,s,e.model,e.agent,e.config,new qi,a,this._metadataStore,this._instantiationService),c=new Wu(l);return c.addDisposable(l.onDidSessionProgress(u=>this._onDidSessionProgress.fire(u))),c.addDisposable(l.onDidCustomizationsChange(()=>this._onDidCustomizationsChange.fire())),this._sessions.set(n,c),{session:i,workingDirectory:e.workingDirectory,provisional:!0,...s?{project:s}:{}}}async _materializeProvisional(e){let n=this._findAnySession(e);if(!n)throw new Error(`Cannot materialize unknown provisional session: ${e}`);let i=this._ensureAuthenticated(),o=(s,a,l)=>Um({getSession:c=>this._findAnySession(c),configurationService:this._configurationService},e,s,a,l);try{await n.materialize({proxyHandle:i,canUseTool:o,isResume:!1})}catch(s){throw this._sessions.deleteAndDispose(e),s}return this._onDidMaterializeSession.fire({session:n.sessionUri,workingDirectory:n.workingDirectory,project:n.project}),n}async _resumeSession(e,n){this._logService.info(`[Claude:${e}] _resumeSession \u2014 no in-memory state, rebuilding from disk`);let i=this._ensureAuthenticated(),o=await this._sdkService.getSessionInfo(e);if(!o)throw new Error(`Cannot resume unknown session: ${e} (not present in SDK transcript store)`);let s=o.cwd?y.file(o.cwd):void 0;if(!s)throw new Error(`Cannot resume session ${e}: workingDirectory missing from SDK transcript`);let a={};try{a=await this._metadataStore.read(n)}catch(m){this._logService.warn(`[Claude:${e}] overlay read failed during resume; continuing with defaults`,m)}let l=hs(this._configurationService,n)??a.permissionMode??"default",c;try{c=await fi({cwd:s.fsPath},this._gitService)}catch(m){this._logService.warn(`[Claude:${e}] project resolution failed during resume; continuing without project`,m)}let u=mi.createProvisional(e,n,s,c,a.model,a.agent,void 0,new qi,l,this._metadataStore,this._instantiationService),d=new Wu(u);d.addDisposable(u.onDidSessionProgress(m=>this._onDidSessionProgress.fire(m))),d.addDisposable(u.onDidCustomizationsChange(()=>this._onDidCustomizationsChange.fire())),this._sessions.set(e,d);let f=(m,h,v)=>Um({getSession:S=>this._findAnySession(S),configurationService:this._configurationService},e,m,h,v);try{await u.materialize({proxyHandle:i,canUseTool:f,isResume:!0})}catch(m){throw this._sessions.deleteAndDispose(e),m}return this._onDidMaterializeSession.fire({session:n,workingDirectory:s,project:c}),u}_resolvePermissionMode(e){return ds(e?.permissionMode)??"default"}disposeSession(e){let n=H.id(e);return this._disposeSequencer.queue(n,async()=>{let i=this._findAnySession(n);i&&!i.isPipelineReady&&i.abortController.abort(),this._sessions.deleteAndDispose(n)})}getSessionForTesting(e){let n=this._sessions.get(H.id(e))?.session;return n?.isPipelineReady?n:void 0}async getSessionMessages(e){let n=H.id(e),i=this._findAnySession(n);if(i&&!i.isPipelineReady)return[];if(Lc(e)){let l=Ge(e),c=l?this._sessions.get(H.id(l.parentSession))?.session:void 0;if(!c)return this._logService.warn(`[Claude] getSessionMessages: parent session not found for subagent ${e.toString()} (registry unavailable)`),[];try{return await j_(e,c.subagents,this._sdkService,this._logService,ze.None)}catch(u){return this._logService.warn(`[Claude] getSubagentTranscript threw for ${e.toString()}`,u),[]}}let o=this._sessions.get(n)?.session,s;try{s=await this._sdkService.getSessionMessages(n,{includeSystemMessages:!0})}catch(l){return this._logService.warn(`[Claude] getSessionMessages SDK fetch failed for ${n}`,l),[]}let a;try{a=ll(s,e,this._logService)}catch(l){return this._logService.warn(`[Claude] replay mapper threw for ${n}`,l),[]}try{o?.subagents.primeFromTranscript(a)}catch(l){this._logService.warn(`[Claude] primeFromTranscript threw for ${n}`,l)}return a}async listSessions(){let e;try{e=await this._sdkService.listSessions()}catch(n){return this._logService.warn("[Claude] SDK listSessions failed; surfacing empty list",n),[]}return Promise.all(e.map(async n=>{try{let i=H.uri(this.id,n.sessionId),o=await this._metadataStore.read(i);return this._metadataStore.project(n,o)}catch(i){this._logService.warn(`[Claude] Overlay read failed for session ${n.sessionId}`,i)}return this._metadataStore.project(n,{})}))}async getSessionMetadata(e){let n=H.id(e),i=await this._sdkService.getSessionInfo(n);if(!i)return;let o={};try{o=await this._metadataStore.read(e)}catch(s){this._logService.warn(`[Claude] Overlay read failed for session ${n}`,s)}return this._metadataStore.project(i,o)}resolveSessionConfig(e){let n=wn({permissionMode:bt({type:"string",title:g(1902,null),description:g(1915,null),enum:["default","acceptEdits","bypassPermissions","plan","dontAsk","auto"],enumLabels:[g(1909,null),g(1903,null),g(1907,null),g(1913,null),g(1911,null),g(1905,null)],enumDescriptions:[g(1910,null),g(1904,null),g(1908,null),g(1914,null),g(1912,null),g(1906,null)],default:"default",sessionMutable:!0}),permissions:Mt.definition.permissions}),i=n.validateOrDefault(e.config,{permissionMode:"default"});return Promise.resolve({schema:n.toProtocol(),values:i})}sessionConfigCompletions(e){return Promise.resolve({items:[]})}shutdown(){return this._shutdownPromise??=(async()=>{for(let n of this._sessions.values())n.session.isPipelineReady||n.session.abortController.abort();let e=[...this._sessions.keys()];await Promise.all(e.map(n=>this._disposeSequencer.queue(n,async()=>{this._sessions.deleteAndDispose(n)})))})()}async sendMessage(e,n,i,o){let s=H.id(e),a=o??q();return this._sessionSequencer.queue(s,async()=>{let l=this._findAnySession(s),c;l?.isPipelineReady?c=l:l?c=await this._materializeProvisional(s):c=await this._resumeSession(s,e);let d={type:"user",message:{role:"user",content:Ou(n,i)},session_id:s,parent_tool_use_id:null,uuid:a};await c.send(d,a)})}respondToPermissionRequest(e,n){for(let i of this._sessions.values())if(i.session.respondToPermissionRequest(e,n))return}respondToUserInputRequest(e,n,i){for(let o of this._sessions.values())if(o.session.respondToUserInputRequest(e,n,i))return}async abortSession(e){let n=H.id(e),i=this._findAnySession(n);if(i){if(!i.isPipelineReady){i.abortController.abort();return}i.abort()}}setPendingMessages(e,n,i){let o=H.id(e);this._logService.info(`[Claude:${o}] setPendingMessages called: steering=${n?.id??"none"} queued=${i.length}`);let s=this._sessions.get(o);if(!s){this._logService.warn(`[Claude:${o}] setPendingMessages: session not found`);return}n&&s.session.injectSteering(n)}async changeModel(e,n){let i=H.id(e);await this._sessionSequencer.queue(i,async()=>{let o=this._findAnySession(i);o?await o.setModel(n):await this._metadataStore.write(e,{model:n})})}async changeAgent(e,n){let i=H.id(e);await this._sessionSequencer.queue(i,async()=>{let o=this._findAnySession(i);o?await o.setAgent(n):await this._metadataStore.write(e,{agent:n??null})})}setClientTools(e,n,i){let o=H.id(e);this._logService.info(`[Claude:${o}] setClientTools clientId=${n} tools=[${i.map(a=>a.name).join(", ")||"(none)"}]`);let s=this._findAnySession(o);s&&s.setClientTools(i,n)}onClientToolCallComplete(e,n,i){let o=e,s;for(;s=Ge(o);)o=s.parentSession;let a=H.id(o);this._sessions.get(a)?.session.completeClientToolCall(n,i)}async setClientCustomizations(e,n,i){let o=H.id(e),s=this._findAnySession(o);return s?this._sessionSequencer.queue(o,async()=>{let a=await this._pluginManager.syncCustomizations(n,i,l=>this._fireCustomizationUpdated(e,{customization:l}));return s.adoptClientCustomizations(a),a}):(this._logService.warn(`[Claude:${o}] setClientCustomizations: session not found`),[])}_fireCustomizationUpdated(e,n){this._onDidSessionProgress.fire({kind:"action",session:e,action:{type:"session/customizationUpdated",customization:n.customization}})}setCustomizationEnabled(e,n){for(let i of this._sessions.values())i.session.setClientCustomizationEnabled(e,n)}getCustomizations(){return[]}async getSessionCustomizations(e){let n=this._findAnySession(H.id(e));return n?await n.getSessionCustomizations():[]}dispose(){for(let e of this._sessions.values())e.session.isPipelineReady||e.session.abortController.abort();super.dispose(),this._proxyHandle?.dispose(),this._proxyHandle=void 0,this._githubToken=void 0,this._models.set([],void 0)}};Ts=w([C(0,L),C(1,cs),C(2,Fu),C(3,ps),C(4,Nt),C(5,Je),C(6,qe),C(7,Dn)],Ts);var Wu=class extends T{constructor(t){super(),this.session=this._register(t)}addDisposable(t){this._register(t)}};import{mkdir as HA}from"fs/promises";var xA=/^[0-9a-fA-F]+$/,wA="00000000000000000000000000000000",mC="0000000000000000";function hC(r){if(!r||!Array.isArray(r.resourceSpans))return{spans:[],rejected:0,errors:[]};let t=[],e=[],n=0;for(let i of r.resourceSpans){if(!i)continue;let o=kA(i.resource?.attributes);for(let s of i.scopeSpans??[])if(s)for(let a of s.spans??[])try{let l=RA(a,o);l?t.push(l):n++}catch(l){n++,e.push(l instanceof Error?l.message:String(l))}}return{spans:t,rejected:n,errors:e}}function RA(r,t){if(!r)return;let e=(r.traceId??"").toLowerCase(),n=(r.spanId??"").toLowerCase();if(!Bm(e,32)||e===wA)throw new Error(`invalid traceId: ${r.traceId}`);if(!Bm(n,16)||n===mC)throw new Error(`invalid spanId: ${r.spanId}`);let i;if(r.parentSpanId){let u=r.parentSpanId.toLowerCase();Bm(u,16)&&u!==mC&&(i=u)}let o=zm(r.startTimeUnixNano),s=zm(r.endTimeUnixNano);if(o===void 0||s===void 0)throw new Error("missing span time bounds");let a={...t};for(let u of r.attributes??[])qm(a,u);let l=[];for(let u of r.events??[]){let d=EA(u);d&&l.push(d)}let c=PA(r.status?.code,r.status?.message);return{name:r.name??"",traceId:e,spanId:n,parentSpanId:i,startTime:o,endTime:s,status:c,attributes:a,events:l}}function EA(r){if(!r)return;let t=zm(r.timeUnixNano);if(t===void 0)return;let e={};for(let n of r.attributes??[])qm(e,n);return{name:r.name??"",timestamp:t,attributes:Object.keys(e).length>0?e:void 0}}function PA(r,t){switch(r){case 1:return{code:1,message:t};case 2:return{code:2,message:t};case 0:default:return{code:0,message:t}}}function kA(r){let t={};if(!r)return t;for(let e of r)qm(t,e);return t}function qm(r,t){if(!t||typeof t.key!="string"||t.key.length===0)return;let e=Hm(t.value);e!==void 0&&(r[t.key]=e)}function Hm(r){if(r){if(typeof r.stringValue=="string")return r.stringValue;if(typeof r.boolValue=="boolean")return r.boolValue;if(r.intValue!==void 0){let t=typeof r.intValue=="string"?Number(r.intValue):r.intValue;return Number.isFinite(t)?t:void 0}if(typeof r.doubleValue=="number")return r.doubleValue;if(r.arrayValue?.values){let t=r.arrayValue.values.map(Hm);return t.every(e=>typeof e=="string")?t:JSON.stringify(t)}if(r.kvlistValue?.values){let t={};for(let e of r.kvlistValue.values)e&&typeof e.key=="string"&&(t[e.key]=Hm(e.value));return JSON.stringify(t)}if(typeof r.bytesValue=="string")return r.bytesValue}}function zm(r){if(r===void 0||r===""||r==="0")return;let t=r.length<=6?"0":r.slice(0,-6),e=Number(t);return Number.isFinite(e)?e:void 0}function Bm(r,t){return r.length===t&&xA.test(r)}var AA="/v1/traces",DA=64*1024*1024;async function yC(r,t,e={}){let n=e.maxBodyBytes??DA,o=(await import("http")).createServer();o.on("request",(u,d)=>{OA(u,d,r,t,n).catch(f=>{if(t.error(`[agentHost-otel] receiver: unhandled error: ${f instanceof Error?f.message:String(f)}`),!d.headersSent)Gi(d,500,"internal error");else if(!d.writableEnded)try{d.end()}catch{}})}),await new Promise((u,d)=>{let f=m=>d(m);o.once("error",f),o.listen(0,"127.0.0.1",()=>{o.removeListener("error",f),u()})});let s=o.address();if(!s||typeof s=="string")throw o.close(),new Error(`local OTLP receiver failed to bind: unexpected address ${String(s)}`);let a=s.port,l=`http://127.0.0.1:${a}`;t.info(`[agentHost-otel] receiver listening on ${l}`);let c=A(()=>{o.closeAllConnections(),o.close(u=>{u&&t.warn(`[agentHost-otel] receiver close error: ${u.message}`)})});return Object.assign(c,{baseUrl:l,port:a})}async function OA(r,t,e,n,i){if((r.url??"").split("?",1)[0]!==AA){Gi(t,404,"not found");return}if(r.method!=="POST"){t.setHeader("allow","POST"),Gi(t,405,"method not allowed");return}let a=(r.headers["content-type"]??"").toString().toLowerCase();if(!a.includes("application/json")){Gi(t,415,"unsupported content-type; this receiver only accepts application/json");return}let l=(r.headers["content-encoding"]??"").toString().toLowerCase();if(l&&l!=="identity"){Gi(t,415,`unsupported content-encoding: ${l}`);return}let c;try{c=await LA(r,i)}catch(m){m instanceof $u?Gi(t,413,"payload too large"):Gi(t,400,"failed to read body");return}if(e.onForward)try{e.onForward(c,a)}catch(m){n.warn(`[agentHost-otel] forward callback threw: ${m instanceof Error?m.message:String(m)}`)}let u;try{u=JSON.parse(c.toString("utf8"))}catch(m){Gi(t,400,`invalid json: ${m instanceof Error?m.message:String(m)}`);return}let d=hC(u);try{e.onSpans(d)}catch(m){n.warn(`[agentHost-otel] onSpans handler threw: ${m instanceof Error?m.message:String(m)}`)}let f=d.rejected>0?{partialSuccess:{rejectedSpans:d.rejected,errorMessage:d.errors.join("; ").slice(0,1024)}}:{};t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify(f))}var $u=class extends Error{};function LA(r,t){return new Promise((e,n)=>{let i=[],o=0,s=u=>{if(o+=u.length,o>t){c(),n(new $u(`body exceeds ${t} bytes`));return}i.push(u)},a=()=>{c(),e(Buffer.concat(i))},l=u=>{c(),n(u)},c=()=>{r.removeListener("data",s),r.removeListener("end",a),r.removeListener("error",l)};r.on("data",s),r.on("end",a),r.on("error",l)})}function Gi(r,t,e){r.statusCode=t,r.setHeader("content-type","text/plain; charset=utf-8"),r.end(e)}import{URL as vC}from"url";import{promises as MA}from"fs";function NA(r){try{let t=new vC(r);return t.pathname===""||t.pathname==="/"?(t.pathname="/v1/traces",t.toString()):r}catch{return r}}var Vu=class extends T{constructor(e,n){super();this._options=e;this._logService=n;this._queue=new xi;this._disposed=!1;this._resolvedEndpoint=NA(e.endpoint),this._register(A(()=>{this._disposed=!0}))}forwardRaw(e,n){this._disposed||this._queue.queue(()=>this._sendOnce(e,n))}async flush(){try{await this._queue.queue(()=>Promise.resolve())}catch{}}async _sendOnce(e,n){try{let i=new vC(this._resolvedEndpoint),o=i.protocol==="https:",s=o?await import("https"):await import("http"),a={"content-type":n,"content-length":String(e.length),...this._options.headers??{}};await UA(s,{host:i.hostname,port:i.port?Number(i.port):o?443:80,path:i.pathname+(i.search??""),method:"POST",headers:a,timeoutMs:this._options.timeoutMs??1e4},e)}catch(i){this._logService.warn(`[agentHost-otel] forward to ${this._resolvedEndpoint} failed: ${i instanceof Error?i.message:String(i)}`)}}};function UA(r,t,e){return new Promise((n,i)=>{let o=r.request({host:t.host,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:t.timeoutMs}),s=a=>{o.destroy(),i(a)};o.on("error",s),o.on("timeout",()=>s(new Error(`request timeout after ${t.timeoutMs}ms`))),o.on("response",a=>{a.resume(),a.on("end",()=>{let l=a.statusCode??0;l>=200&&l<300?n():i(new Error(`upstream returned HTTP ${l}`))}),a.on("error",s)}),o.end(e)})}var Bu=class extends T{constructor(e,n){super();this._options=e;this._logService=n;this._queue=new xi;this._disposed=!1;this._register(A(()=>{this._disposed=!0}))}forwardSpans(e){if(this._disposed||e.spans.length===0)return;let n=e.spans.map(i=>JSON.stringify(i)).join(`
`)+`
`;this._queue.queue(()=>this._append(n))}async flush(){try{await this._queue.queue(()=>Promise.resolve())}catch{}}async _append(e){try{await MA.appendFile(this._options.filePath,e,{encoding:"utf8"})}catch(n){this._logService.warn(`[agentHost-otel] file forward to ${this._options.filePath} failed: ${n instanceof Error?n.message:String(n)}`)}}},Hu=class extends T{constructor(e){super();this._logService=e;this._disposed=!1;this._register(A(()=>{this._disposed=!0}))}forwardSpans(e){if(!this._disposed)for(let n of e.spans)this._logService.info(`[agentHost-otel] span ${FA(n)}`)}async flush(){}};function FA(r){let t=Math.max(0,r.endTime-r.startTime),e=r.attributes["gen_ai.operation.name"],n=r.attributes["gen_ai.request.model"]??r.attributes["gen_ai.response.model"],i=[e&&`op=${e}`,n&&`model=${n}`].filter(Boolean).join(" ");return`${r.name} (${t}ms) trace=${r.traceId} span=${r.spanId}${i?" "+i:""}`}var zu=class extends T{constructor(t){super(),this._children=t;for(let e of t)this._register(e)}forwardRaw(t,e){for(let n of this._children)n.forwardRaw?.(t,e)}forwardSpans(t){for(let e of this._children)e.forwardSpans?.(t)}async flush(){await Promise.all(this._children.map(t=>t.flush()))}};import{mkdirSync as WA}from"fs";import{createRequire as $A}from"module";var $t={OPERATION_NAME:"gen_ai.operation.name",PROVIDER_NAME:"gen_ai.provider.name",REQUEST_MODEL:"gen_ai.request.model",RESPONSE_MODEL:"gen_ai.response.model",RESPONSE_ID:"gen_ai.response.id",RESPONSE_FINISH_REASONS:"gen_ai.response.finish_reasons",USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",USAGE_CACHE_READ_INPUT_TOKENS:"gen_ai.usage.cache_read.input_tokens",USAGE_CACHE_CREATION_INPUT_TOKENS:"gen_ai.usage.cache_creation.input_tokens",USAGE_REASONING_TOKENS:"gen_ai.usage.reasoning_tokens",CONVERSATION_ID:"gen_ai.conversation.id",TOKEN_TYPE:"gen_ai.token.type",AGENT_NAME:"gen_ai.agent.name",TOOL_NAME:"gen_ai.tool.name",TOOL_TYPE:"gen_ai.tool.type",TOOL_CALL_ID:"gen_ai.tool.call.id"},fl={TURN_INDEX:"copilot_chat.turn.index",TIME_TO_FIRST_TOKEN:"copilot_chat.time_to_first_token",CHAT_SESSION_ID:"copilot_chat.chat_session_id",HOOK_TYPE:"copilot_chat.hook_type",HOOK_INPUT:"copilot_chat.hook_input",HOOK_OUTPUT:"copilot_chat.hook_output",HOOK_RESULT_KIND:"copilot_chat.hook_result_kind"};var VA=$A(import.meta.url);function BA(){return VA("node:sqlite")}var bC=1,SC=10080*60*1e3,IC=100,xt={operation_name:$t.OPERATION_NAME,provider_name:$t.PROVIDER_NAME,agent_name:$t.AGENT_NAME,conversation_id:$t.CONVERSATION_ID,request_model:$t.REQUEST_MODEL,response_model:$t.RESPONSE_MODEL,input_tokens:$t.USAGE_INPUT_TOKENS,output_tokens:$t.USAGE_OUTPUT_TOKENS,cached_tokens:$t.USAGE_CACHE_READ_INPUT_TOKENS,reasoning_tokens:$t.USAGE_REASONING_TOKENS,tool_name:$t.TOOL_NAME,tool_call_id:$t.TOOL_CALL_ID,tool_type:$t.TOOL_TYPE,chat_session_id:fl.CHAT_SESSION_ID,turn_index:fl.TURN_INDEX,ttft_ms:fl.TIME_TO_FIRST_TOKEN},Kse=V("otelSqliteStore"),qu=class{constructor(t){this._db=null;this._insertSpanStmt=null;this._insertAttrStmt=null;this._insertEventStmt=null;this._beginTx=null;this._commitTx=null;this._rollbackTx=null;this._dbPath=t}get dbPath(){return this._dbPath}insertSpan(t){this._ensureDb();try{this._beginTx.run(),this._insertSpanStmt.run(t.spanId,t.traceId,t.parentSpanId??null,t.name,t.startTime,t.endTime,t.status.code,t.status.message??null,this._attr(t,xt.operation_name),this._attr(t,xt.provider_name),this._attr(t,xt.agent_name),this._attr(t,xt.conversation_id),this._attr(t,xt.request_model),this._attr(t,xt.response_model),this._attr(t,xt.input_tokens),this._attr(t,xt.output_tokens),this._attr(t,xt.cached_tokens),this._attr(t,xt.reasoning_tokens),this._attr(t,xt.tool_name),this._attr(t,xt.tool_call_id),this._attr(t,xt.tool_type),this._attr(t,xt.chat_session_id),this._attr(t,xt.turn_index),this._ttftMs(t));for(let[e,n]of Object.entries(t.attributes)){let i=Array.isArray(n)?JSON.stringify(n):String(n);this._insertAttrStmt.run(t.spanId,e,i)}for(let e of t.events){let n=e.attributes?JSON.stringify(e.attributes):null;this._insertEventStmt.run(t.spanId,e.name,e.timestamp,n)}this._commitTx.run()}catch(e){try{this._rollbackTx.run()}catch{}throw e}}getSpansByTraceId(t){return this._ensureDb().prepare("SELECT * FROM spans WHERE trace_id = ? ORDER BY start_time_ms").all(t)}getSpansByConversationId(t){return this._ensureDb().prepare("SELECT * FROM spans WHERE conversation_id = ? OR chat_session_id = ? ORDER BY start_time_ms").all(t,t)}getSpanAttributes(t){return this._ensureDb().prepare("SELECT key, value FROM span_attributes WHERE span_id = ?").all(t)}getSpanAttribute(t,e){return this._ensureDb().prepare("SELECT value FROM span_attributes WHERE span_id = ? AND key = ?").get(t,e)?.value??null}getSpanEvents(t){return this._ensureDb().prepare("SELECT * FROM span_events WHERE span_id = ? ORDER BY timestamp_ms").all(t)}getTraceIds(t){let e=this._ensureDb();return t?e.prepare("SELECT DISTINCT trace_id FROM spans WHERE conversation_id = ? OR chat_session_id = ?").all(t,t).map(i=>i.trace_id):e.prepare("SELECT DISTINCT trace_id FROM spans").all().map(n=>n.trace_id)}getSessions(t){let e=t?"SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?":"SELECT * FROM sessions ORDER BY started_at DESC";return t?this._ensureDb().prepare(e).all(t):this._ensureDb().prepare(e).all()}getSessionsSince(t){return this._ensureDb().prepare("SELECT * FROM sessions WHERE started_at >= ? ORDER BY started_at DESC").all(t)}cleanup(t=SC){let e=Date.now()-t,n=this._ensureDb().prepare("DELETE FROM spans WHERE start_time_ms < ?").run(e);return Number(n.changes)}checkpoint(){this._ensureDb().exec("PRAGMA wal_checkpoint(TRUNCATE)")}close(){this._db&&(this._db.close(),this._db=null,this._insertSpanStmt=null,this._insertAttrStmt=null,this._insertEventStmt=null,this._beginTx=null,this._commitTx=null,this._rollbackTx=null)}_attr(t,e){let n=t.attributes[e];return n===void 0?null:Array.isArray(n)?JSON.stringify(n):typeof n=="boolean"?n?1:0:n}_ttftMs(t){let e=this._attr(t,fl.TIME_TO_FIRST_TOKEN);if(e!==null)return e;let n=t.attributes["gen_ai.response.time_to_first_chunk"]??t.attributes["github.copilot.time_to_first_chunk"];if(n===void 0)return null;let i=typeof n=="number"?n:parseFloat(String(n));return isNaN(i)?null:Math.round(i*1e3)}_ensureDb(){if(this._db)return this._db;this._dbPath!==":memory:"&&WA(de(this._dbPath),{recursive:!0});let{DatabaseSync:t}=BA(),e=new t(this._dbPath);try{e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 3000"),e.exec("PRAGMA foreign_keys = ON"),this._db=e,this._ensureSchema(),this._prepareStatements(e),this._cleanupOnStartup(e)}catch(n){throw e.close(),this._db=null,n}return this._db}_prepareStatements(t){this._insertSpanStmt=t.prepare(`
			INSERT OR REPLACE INTO spans (
				span_id, trace_id, parent_span_id, name,
				start_time_ms, end_time_ms, status_code, status_message,
				operation_name, provider_name, agent_name, conversation_id,
				request_model, response_model,
				input_tokens, output_tokens, cached_tokens, reasoning_tokens,
				tool_name, tool_call_id, tool_type,
				chat_session_id, turn_index, ttft_ms
			) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		`),this._insertAttrStmt=t.prepare("INSERT OR REPLACE INTO span_attributes (span_id, key, value) VALUES (?, ?, ?)"),this._insertEventStmt=t.prepare("INSERT INTO span_events (span_id, name, timestamp_ms, attributes) VALUES (?, ?, ?, ?)"),this._beginTx=t.prepare("BEGIN"),this._commitTx=t.prepare("COMMIT"),this._rollbackTx=t.prepare("ROLLBACK")}_ensureSchema(){let t=this._db;((()=>{try{return t.prepare("SELECT version FROM schema_version LIMIT 1").get()}catch{return}})()?.version??0)>=bC||t.exec(`
			CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
			INSERT OR REPLACE INTO schema_version (version) VALUES (${bC});

			CREATE TABLE IF NOT EXISTS spans (
				span_id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, parent_span_id TEXT,
				name TEXT NOT NULL, start_time_ms INTEGER NOT NULL, end_time_ms INTEGER NOT NULL,
				status_code INTEGER NOT NULL DEFAULT 0, status_message TEXT,
				operation_name TEXT, provider_name TEXT, agent_name TEXT, conversation_id TEXT,
				request_model TEXT, response_model TEXT,
				input_tokens INTEGER, output_tokens INTEGER, cached_tokens INTEGER, reasoning_tokens INTEGER,
				tool_name TEXT, tool_call_id TEXT, tool_type TEXT,
				chat_session_id TEXT, turn_index INTEGER, ttft_ms REAL
			);

			CREATE TABLE IF NOT EXISTS span_attributes (
				span_id TEXT NOT NULL REFERENCES spans(span_id) ON DELETE CASCADE,
				key TEXT NOT NULL, value TEXT,
				PRIMARY KEY (span_id, key)
			);

			CREATE TABLE IF NOT EXISTS span_events (
				id INTEGER PRIMARY KEY AUTOINCREMENT,
				span_id TEXT NOT NULL REFERENCES spans(span_id) ON DELETE CASCADE,
				name TEXT NOT NULL, timestamp_ms INTEGER NOT NULL, attributes TEXT
			);

			CREATE INDEX IF NOT EXISTS idx_spans_trace ON spans(trace_id);
			CREATE INDEX IF NOT EXISTS idx_spans_conversation ON spans(conversation_id);
			CREATE INDEX IF NOT EXISTS idx_spans_chat_session ON spans(chat_session_id);
			CREATE INDEX IF NOT EXISTS idx_spans_operation ON spans(operation_name);
			CREATE INDEX IF NOT EXISTS idx_spans_start_time ON spans(start_time_ms);
			CREATE INDEX IF NOT EXISTS idx_span_events_span ON span_events(span_id);

			-- Session view: derives session boundaries from span data.
			-- No separate sessions table needed \u2014 invoke_agent spans define session lifecycle.
			CREATE VIEW IF NOT EXISTS sessions AS
			SELECT
				COALESCE(conversation_id, chat_session_id) AS session_id,
				agent_name,
				response_model AS model,
				MIN(start_time_ms) AS started_at,
				MAX(end_time_ms) AS ended_at,
				MAX(end_time_ms) - MIN(start_time_ms) AS duration_ms,
				COUNT(*) AS span_count,
				SUM(CASE WHEN operation_name = 'chat' THEN 1 ELSE 0 END) AS llm_calls,
				SUM(CASE WHEN operation_name = 'execute_tool' THEN 1 ELSE 0 END) AS tool_calls,
				SUM(CASE WHEN operation_name = 'chat' THEN input_tokens ELSE 0 END) AS total_input_tokens,
				SUM(CASE WHEN operation_name = 'chat' THEN output_tokens ELSE 0 END) AS total_output_tokens,
				SUM(CASE WHEN operation_name = 'chat' THEN cached_tokens ELSE 0 END) AS total_cached_tokens
			FROM spans
			WHERE COALESCE(conversation_id, chat_session_id) IS NOT NULL
			GROUP BY COALESCE(conversation_id, chat_session_id);
		`)}_cleanupOnStartup(t){let e=Date.now()-SC;t.prepare("DELETE FROM spans WHERE start_time_ms < ?").run(e);let n=t.prepare(`
			SELECT MIN(max_start) AS cutoff_ms FROM (
				SELECT MAX(start_time_ms) AS max_start
				FROM spans
				WHERE COALESCE(conversation_id, chat_session_id) IS NOT NULL
				GROUP BY COALESCE(conversation_id, chat_session_id)
				ORDER BY max_start DESC
				LIMIT ?
			)
		`).get(IC);n?.cutoff_ms&&t.prepare(`
				DELETE FROM spans
				WHERE start_time_ms < ?
				AND COALESCE(conversation_id, chat_session_id) NOT IN (
					SELECT COALESCE(conversation_id, chat_session_id)
					FROM spans
					WHERE COALESCE(conversation_id, chat_session_id) IS NOT NULL
					GROUP BY COALESCE(conversation_id, chat_session_id)
					ORDER BY MAX(start_time_ms) DESC
					LIMIT ?
				)
			`).run(n.cutoff_ms,IC)}};var zA=dv;function Km(r){if(!r)return!1;let t=r.trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}function qA(r){if(!r)return;let t={};for(let e of r.split(",")){let n=e.indexOf("=");if(n<=0)continue;let i=e.slice(0,n).trim(),o=e.slice(n+1).trim();i&&(t[i]=o)}return Object.keys(t).length?t:void 0}function KA(r){let t=Km(r.COPILOT_OTEL_DB_SPAN_EXPORTER_ENABLED),e=r.OTEL_EXPORTER_OTLP_ENDPOINT??r.COPILOT_OTEL_ENDPOINT,n=r.COPILOT_OTEL_FILE_EXPORTER_PATH,o=Km(r.COPILOT_OTEL_ENABLED)||t||!!e||!!n,s=(r.COPILOT_OTEL_EXPORTER_TYPE??"").trim().toLowerCase(),a=(r.OTEL_EXPORTER_OTLP_PROTOCOL??r.COPILOT_OTEL_PROTOCOL??"").trim().toLowerCase(),l="otlp-http";return s==="console"||s==="file"||s==="otlp-grpc"||s==="otlp-http"?l=s:n&&(l="file"),(a==="grpc"||a==="http/grpc")&&(l="otlp-grpc"),{enabled:o,dbSpanExporter:t,exporterType:l,otlpEndpoint:e,filePath:n,sourceName:r.COPILOT_OTEL_SOURCE_NAME,captureContent:r.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT===void 0?void 0:Km(r.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT),headers:qA(r.OTEL_EXPORTER_OTLP_HEADERS)}}var xs=class extends T{constructor(e,n){super();this._logService=e;this._config=KA(process.env),this._spansDbPath=B(n.userDataPath,zA)}async getSdkTelemetryConfig(){if(this._config.enabled){if(this._config.dbSpanExporter){if(await this._ensureStarted(),this._receiver)return this._buildLoopbackConfig();if(!this._config.otlpEndpoint&&this._config.exporterType!=="console"&&!this._config.filePath)return}return this._buildPassthroughConfig()}}getSpansDbPath(){return this._config.dbSpanExporter?y.file(this._spansDbPath):void 0}async flush(){await this._startPromise,this._forwarder&&await this._forwarder.flush()}_buildLoopbackConfig(){return{exporterType:"otlp-http",otlpEndpoint:this._receiver.baseUrl,sourceName:this._config.sourceName,captureContent:this._config.captureContent}}_buildPassthroughConfig(){return{exporterType:this._config.exporterType,otlpEndpoint:this._config.otlpEndpoint,filePath:this._config.filePath,sourceName:this._config.sourceName,captureContent:this._config.captureContent}}_ensureStarted(){return this._startPromise||(this._startPromise=this._start().catch(e=>{this._logService.error("[agentHost.otel] failed to start loopback OTel pipeline",e),this._receiver=void 0,this._forwarder=void 0})),this._startPromise}async _start(){await HA(de(this._spansDbPath),{recursive:!0});let e=new qu(this._spansDbPath);this._register(A(()=>e.close())),this._forwarder=this._buildOutboundForwarder();let n=await yC({onSpans:i=>{for(let o of i.spans)try{e.insertSpan(o)}catch(s){this._logService.warn("[agentHost.otel] failed to insert span",s)}this._forwarder?.forwardSpans?.(i)},onForward:this._forwarder?(i,o)=>{this._forwarder.forwardRaw?.(i,o)}:void 0},this._logService);this._receiver=n,this._register(n),this._forwarder&&this._register(this._forwarder),this._logService.info(`[agentHost.otel] loopback receiver at ${n.baseUrl}, db ${this._spansDbPath}`)}_buildOutboundForwarder(){let e=[];switch(this._config.exporterType){case"otlp-http":case"otlp-grpc":this._config.otlpEndpoint&&e.push(new Vu({endpoint:this._config.otlpEndpoint,headers:this._config.headers},this._logService));break;case"file":this._config.filePath&&e.push(new Bu({filePath:this._config.filePath},this._logService));break;case"console":e.push(new Hu(this._logService));break}if(e.length)return e.length===1?e[0]:new zu(e)}};xs=w([C(0,L),C(1,Ui)],xs);var Ku=class extends Error{constructor(e,n,i){super(n);this.code=e;this.data=i}},_C=class r extends T{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,i){if(this._store.isDisposed)return Promise.reject(new re);let o=this._nextRequestId++,s=new fe,a=new Xe;this._pendingRequests.set(o,{promise:s,cts:a});let l=n.onCancellationRequested(()=>{s.isSettled||(this._pendingRequests.delete(o),a.cancel(),i?.(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 i=[];for(let o of e){let s=await this._handleMessage(o);s&&i.push(s)}return i}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(jm(e)){Le(e,{result:!0})?this._handleResult(e):this._handleError(e);return}if(jA(e))return this._handleRequest(e);GA(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 Ku(e.error.code,e.error.message,e.error.data)),n.cts.dispose(!0))}async _handleRequest(e){if(!this._handlers.handleRequest){let i={jsonrpc:"2.0",id:e.id,error:{code:r.MethodNotFound,message:`Method not found: ${e.method}`}};return this._send(i),i}let n=new Xe;this._register(A(()=>n.dispose(!0)));try{let i=this._handlers.handleRequest(e,n.token),o=JA(i)?await i:i,s={jsonrpc:"2.0",id:e.id,result:o};return this._send(s),s}catch(i){let o;return i instanceof Ku?o={jsonrpc:"2.0",id:e.id,error:{code:i.code,message:i.message,data:i.data}}:o={jsonrpc:"2.0",id:e.id,error:{code:r.InternalError,message:i instanceof Error?i.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:r.ParseError,message:e,data:n}}}};function jA(r){return"method"in r&&"id"in r&&(typeof r.id=="string"||typeof r.id=="number")}function jm(r){return Le(r,{id:!0,result:!0})||Le(r,{id:!0,error:!0})}function GA(r){return Le(r,{method:!0})&&!Le(r,{id:!0})}function JA(r){return typeof r=="object"&&r!==null&&"then"in r&&typeof r.then=="function"}var ws="0.3.0",fae=Object.freeze(["0.3.0"]);function CC(r){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(r);if(!t)throw new Error(`Invalid protocol version: ${r}`);return[Number(t[1]),Number(t[2]),Number(t[3])]}function Gm(r,t){let[e,n,i]=CC(r),[o,s,a]=CC(t);return e-o||n-s||i-a}var gae={"root/agentsChanged":"0.1.0","root/activeSessionsChanged":"0.1.0","session/ready":"0.1.0","session/creationFailed":"0.1.0","session/turnStarted":"0.1.0","session/delta":"0.1.0","session/responsePart":"0.1.0","session/toolCallStart":"0.1.0","session/toolCallDelta":"0.1.0","session/toolCallReady":"0.1.0","session/toolCallConfirmed":"0.1.0","session/toolCallComplete":"0.1.0","session/toolCallResultConfirmed":"0.1.0","session/toolCallContentChanged":"0.1.0","session/turnComplete":"0.1.0","session/turnCancelled":"0.1.0","session/error":"0.1.0","session/titleChanged":"0.1.0","session/usage":"0.1.0","session/reasoning":"0.1.0","session/modelChanged":"0.1.0","session/agentChanged":"0.2.0","session/serverToolsChanged":"0.1.0","session/activeClientChanged":"0.1.0","session/activeClientToolsChanged":"0.1.0","session/pendingMessageSet":"0.1.0","session/pendingMessageRemoved":"0.1.0","session/queuedMessagesReordered":"0.1.0","session/inputRequested":"0.1.0","session/inputAnswerChanged":"0.1.0","session/inputCompleted":"0.1.0","session/customizationsChanged":"0.1.0","session/customizationToggled":"0.1.0","session/customizationUpdated":"0.1.0","session/customizationRemoved":"0.2.0","session/truncated":"0.1.0","session/isReadChanged":"0.1.0","session/isArchivedChanged":"0.1.0","session/activityChanged":"0.1.0","session/changesetsChanged":"0.2.0","session/configChanged":"0.1.0","session/metaChanged":"0.1.0","changeset/statusChanged":"0.2.0","changeset/fileSet":"0.2.0","changeset/fileRemoved":"0.2.0","changeset/operationsChanged":"0.2.0","changeset/cleared":"0.2.0","root/terminalsChanged":"0.1.0","root/configChanged":"0.1.0","terminal/data":"0.1.0","terminal/input":"0.1.0","terminal/resized":"0.1.0","terminal/claimed":"0.1.0","terminal/titleChanged":"0.1.0","terminal/cwdChanged":"0.1.0","terminal/exited":"0.1.0","terminal/cleared":"0.1.0","terminal/commandDetectionAvailable":"0.1.0","terminal/commandExecuted":"0.1.0","terminal/commandFinished":"0.1.0","resourceWatch/changed":"0.2.0"};function TC(r){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(r);if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}function QA(r,t){let e=TC(r),n=TC(t);return!e||!n||e[0]!==n[0]||e[0]===0&&e[1]!==n[1]?!1:Gm(r,t)<=0}function xC(r,t){let e;for(let n of r)QA(n,t)&&(e===void 0||Gm(n,e)>0)&&(e=n);return e}var Jm="_vscodeUpgrade";var wC="VSCODE_AGENT_HOST_MANAGEMENT_SOCKET";function ju(){let r=process.env[wC];return r&&r.length>0?r:void 0}async function RC(r=ju()){let t=await import("http");return r?new Promise((e,n)=>{let i=t.request({socketPath:r,method:"POST",path:"/upgrade",headers:{"content-length":"0"}},o=>{let s=[];o.on("data",a=>s.push(a)),o.on("end",()=>{let a=Buffer.concat(s).toString("utf8"),l=o.statusCode??0,c;try{c=a?JSON.parse(a):void 0}catch{}if(l>=200&&l<300&&c&&c.ok!==!1)e(c);else{let u=c?.error||a||`HTTP ${l}`;n(new Error(`Agent host upgrade request failed: ${u}`))}}),o.on("error",n)});i.once("error",n),i.end()}):Promise.reject(new Error(`Cannot request upgrade: ${wC} is not set.`))}var EC="ahp-otlp://logs/{level}",PC="ahp-otlp",YA=["trace","debug","info","warn","error","fatal"];function kC(r){switch(r){case"trace":return 1;case"debug":return 5;case"info":return 9;case"warn":return 13;case"error":return 17;case"fatal":return 21}}function XA(r){let t=r.toLowerCase();return YA.includes(t)?t:void 0}function ZA(r){switch(r){case 1:return{severityNumber:1,severityText:"trace"};case 2:return{severityNumber:5,severityText:"debug"};case 3:return{severityNumber:9,severityText:"info"};case 4:return{severityNumber:13,severityText:"warn"};case 5:return{severityNumber:17,severityText:"error"};case 0:return{severityNumber:0,severityText:"trace"}}}var Gu=class extends T{constructor(){super(...arguments);this._onDidLog=this._register(new x);this.onDidLog=this._onDidLog.event}emit(e){this._onDidLog.fire(e)}},Ju=class extends br{constructor(e,n=1){super();this._emitter=e;this.setLevel(n)}log(e,n){if(e===0)return;let{severityNumber:i,severityText:o}=ZA(e);this._emitter.emit({timeUnixNano:tD(Date.now()),severityNumber:i,severityText:o,body:n})}};function AC(r){return eD([r])}function eD(r){return{resourceLogs:[{resource:{attributes:[]},scopeLogs:[{scope:{name:"vscode.agentHost"},logRecords:r.map(t=>({timeUnixNano:t.timeUnixNano,observedTimeUnixNano:t.timeUnixNano,severityNumber:t.severityNumber,severityText:t.severityText,body:{stringValue:t.body}}))}]}]}}function tD(r){return`${r}000000`}function DC(r){let t=/^ahp-otlp:\/\/logs\/([^/?#]+)/i.exec(r);if(t)return XA(t[1])}function OC(r){return`ahp-otlp://logs/${r}`}var nD=1e3,iD=3e4;function Rs(r,t){return{jsonrpc:"2.0",id:r,result:t}}function Yu(r,t,e,n){return{jsonrpc:"2.0",id:r,error:{code:t,message:e,...n!==void 0?{data:n}:{}}}}function Es(r,t){if(t instanceof N)return Yu(r,t.code,t.message,t.data);let e=t instanceof Error?t.stack??t.message:String(t);return Yu(r,So,e)}function Qu(r){if(r.toLowerCase().startsWith(`${PC}:`)){let t=DC(r);return t?{kind:"otlp-logs",uri:OC(t),level:t}:void 0}return yb(r)?{kind:"resource-watch",uri:r}:{kind:"state",uri:r}}var Ar=class extends T{constructor(e,n,i,o,s,a){super();this._agentService=e;this._stateManager=n;this._server=i;this._config=o;this._clientFileSystemProvider=s;this._logService=a;this._clients=new Map;this._replayBuffer=[];this._clientToolCallDisconnectTimeouts=new Map;this._onDidChangeConnectionCount=this._register(new x);this.onDidChangeConnectionCount=this._onDidChangeConnectionCount.event;this._requestHandlers={subscribe:async(e,n)=>{let i=Qu(n.channel);if(!i)return{};if(i.kind==="otlp-logs")return this._config.otlpLogEmitter?(e.subscriptions.set(i.uri,i),{}):(this._logService.warn(`[ProtocolServer] Ignoring OTLP subscribe for ${n.channel}: no OTLP emitter configured.`),{});if(i.kind==="resource-watch"){let o=this._agentService.onResourceWatchSubscribed(i.uri);if(!o)throw new N(xn,`Resource watch not found: ${n.channel}`);return e.subscriptions.set(i.uri,i),{snapshot:{resource:i.uri,state:o,fromSeq:this._stateManager.serverSeq}}}try{let o=await this._agentService.subscribe(y.parse(n.channel),e.clientId);return e.subscriptions.set(i.uri,i),this._clearClientToolCallDisconnectTimeout(e.clientId,i.uri),{snapshot:o}}catch(o){throw o instanceof N?o:new N(xn,`Resource not found: ${n.channel}`)}},createSession:async(e,n)=>{let i,o;if(n.fork){let s=this._stateManager.getSessionState(n.fork.session);if(!s)throw new N(xn,`Fork source session not found: ${n.fork.session}`);let a=s.turns.findIndex(l=>l.id===n.fork.turnId);if(a<0)throw new N(xn,`Fork turn ID ${n.fork.turnId} not found in session ${n.fork.session}`);o={session:y.parse(n.fork.session),turnIndex:a,turnId:n.fork.turnId}}if(n.activeClient&&n.activeClient.clientId!==e.clientId)throw new N(nn.InvalidParams,"createSession.activeClient.clientId must match the connection's clientId");try{i=await this._agentService.createSession({provider:n.provider,model:n.model,agent:n.agent,workingDirectory:n.workingDirectory?y.parse(n.workingDirectory):void 0,session:y.parse(n.channel),fork:o,config:n.config,activeClient:n.activeClient})}catch(s){throw s instanceof N?s:new N(sb,s instanceof Error?s.message:String(s))}return i.toString()!==y.parse(n.channel).toString()&&this._logService.warn(`[ProtocolServer] createSession: provider returned URI ${i.toString()} but client requested ${n.channel}`),null},disposeSession:async(e,n)=>(await this._agentService.disposeSession(y.parse(n.channel)),null),resourceWrite:async(e,n)=>this._agentService.resourceWrite(n),listSessions:async()=>({items:(await this._agentService.listSessions()).map(i=>{let o=H.provider(i.session);if(!o)throw new Error(`Agent session URI has no provider scheme: ${i.session.toString()}`);let s=i.status??1;return i.isRead&&(s|=32),i.isArchived&&(s|=64),{resource:i.session.toString(),provider:o,title:i.summary??"Session",status:s,activity:i.activity,createdAt:i.startTime,modifiedAt:i.modifiedTime,...i.project?{project:{uri:i.project.uri.toString(),displayName:i.project.displayName}}:{},model:i.model,workingDirectory:i.workingDirectory?.toString(),changesets:i.changesets?[...i.changesets]:void 0}})}),resolveSessionConfig:async(e,n)=>this._agentService.resolveSessionConfig({provider:n.provider,workingDirectory:n.workingDirectory?y.parse(n.workingDirectory):void 0,config:n.config}),sessionConfigCompletions:async(e,n)=>this._agentService.sessionConfigCompletions({provider:n.provider,workingDirectory:n.workingDirectory?y.parse(n.workingDirectory):void 0,config:n.config,property:n.property,query:n.query}),completions:async(e,n)=>this._agentService.completions(n),fetchTurns:async(e,n)=>{let i=this._stateManager.getSessionState(n.channel);if(!i)throw new N(xn,`Session not found: ${n.channel}`);let o=i.turns,s=Math.min(n.limit??50,100),a=o.length;if(n.before){let c=o.findIndex(u=>u.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(y.parse(n.uri)),resourceRead:async(e,n)=>this._agentService.resourceRead(y.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),resourceResolve:async(e,n)=>this._agentService.resourceResolve(n),resourceMkdir:async(e,n)=>this._agentService.resourceMkdir(n),createResourceWatch:async(e,n)=>this._agentService.createResourceWatch(n),resourceRequest:async(e,n)=>({}),authenticate:async(e,n)=>{if(!(await this._agentService.authenticate(n)).authenticated)throw new N(Io,`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(y.parse(n.channel)),null),invokeChangesetOperation:async(e,n)=>{let i=this._stateManager.getChangesetState(n.channel);if(!i)throw new N(xn,`Changeset not found: ${n.channel}`);let o=i.operations?.find(a=>a.id===n.operationId);if(!o)throw new N(nn.InvalidParams,`Unknown operation '${n.operationId}' on changeset ${n.channel}`);let s=n.target?.kind==="resource"?"resource":n.target?.kind==="range"?"range":"changeset";throw o.scopes.includes(s)?new N(nn.InternalError,`No operation handler registered for '${n.operationId}' on changeset ${n.channel}`):new N(nn.InvalidParams,`Operation '${n.operationId}' does not support scope '${s}' (allowed: ${o.scopes.join(", ")})`)}};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>nD&&this._replayBuffer.shift(),this._broadcastAction(l)})),this._register(this._stateManager.onDidEmitNotification(l=>{this._broadcastNotification(l)})),this._config.otlpLogEmitter&&this._register(this._config.otlpLogEmitter.onDidLog(l=>this._broadcastOtlpLog(l)))}_handleNewConnection(e){let n=new z,i;n.add(e.onMessage(o=>{if(lb(o)){if(this._logService.trace(`[ProtocolServer] request: method=${o.method} id=${o.id}`),o.method==="ping"){e.send(Rs(o.id,null));return}if(!i&&o.method==="initialize"){try{let s=this._handleInitialize(o.params,e,n);i=s.client,e.send(Rs(o.id,s.response))}catch(s){e.send(Es(o.id,s))}return}if(!i&&o.method==="reconnect"){let s;try{let a=this._handleReconnect(o.params,e,n);i=a.client,s=a.responsePromise}catch(a){e.send(Es(o.id,a));return}s.then(a=>e.send(Rs(o.id,a)),a=>e.send(Es(o.id,a)));return}if(o.method===Jm){this._handleVscodeUpgrade(o.id,e);return}if(!i)return;this._handleRequest(i,o.method,o.params,o.id)}else if(cb(o))switch(this._logService.trace(`[ProtocolServer] notification: method=${o.method}`),o.method){case"unsubscribe":i&&this._removeSubscription(i,o.params.channel);break;case"dispatchAction":if(i){this._logService.trace(`[ProtocolServer] dispatchAction: ${JSON.stringify(o.params.action.type)}`);let s=o.params.action,a=o.params.channel;(Pc(s)||kc(s)||s.type==="root/configChanged")&&this._agentService.dispatchAction(a,s,i.clientId,o.params.clientSeq)}break}else if(jm(o)){let s=this._pendingReverseRequests.get(o.id);s&&(this._pendingReverseRequests.delete(o.id),Le(o,{error:!0})?s.reject(new N(o.error?.code??-32e3,o.error?.message??"Reverse RPC error",o.error?.data)):s.resolve(o.result))}})),n.add(e.onClose(()=>{if(i&&this._clients.get(i.clientId)===i){this._logService.info(`[ProtocolServer] Client disconnected: ${i.clientId}, subscriptions=${i.subscriptions.size}`);for(let o of i.subscriptions.values())o.kind==="state"?this._agentService.unsubscribe(y.parse(o.uri),i.clientId):o.kind==="resource-watch"&&this._agentService.onResourceWatchUnsubscribed(o.uri);i.subscriptions.clear(),this._clients.delete(i.clientId),this._rejectPendingReverseRequests(i.clientId),this._handleClientDisconnected(i.clientId),this._onDidChangeConnectionCount.fire(this._clients.size)}n.dispose()})),n.add(e)}_handleInitialize(e,n,i){let o=Array.isArray(e.protocolVersions)?e.protocolVersions:[];this._logService.info(`[ProtocolServer] Initialize: clientId=${e.clientId}, protocolVersions=[${o.join(", ")}]`);let s=xC(o,ws);if(!s){let c={supportedVersions:[`^${ws}`],_meta:ju()?{vscodeUpgradeMethod:Jm}:void 0};throw new N(ab,`Client offered protocol versions [${o.join(", ")}], none of which are compatible with this server's version ${ws} (server accepts ^${ws}).`,c)}let a={clientId:e.clientId,protocolVersion:s,transport:n,subscriptions:new Map,disposables:i};this._clients.set(e.clientId,a),this._onDidChangeConnectionCount.fire(this._clients.size),this._registerClientFileSystemAuthority(e.clientId,i);let l=[];if(e.initialSubscriptions)for(let c of e.initialSubscriptions){let u=this._addInitialSubscription(a,c.toString());u&&l.push(u)}return{client:a,response:{protocolVersion:s,serverSeq:this._stateManager.serverSeq,snapshots:l,defaultDirectory:this._config.defaultDirectory,completionTriggerCharacters:this._config.completionTriggerCharacters,telemetry:this._config.otlpLogEmitter?{logs:EC}:void 0}}}_addInitialSubscription(e,n){let i=Qu(n);if(!i)return;if(i.kind==="otlp-logs"){if(!this._config.otlpLogEmitter){this._logService.warn(`[ProtocolServer] Ignoring OTLP initialSubscription ${n}: no OTLP emitter configured.`);return}e.subscriptions.set(i.uri,i);return}let o=this._stateManager.getSnapshot(n);if(o)return e.subscriptions.set(i.uri,i),this._agentService.addSubscriber(y.parse(i.uri),e.clientId),this._clearClientToolCallDisconnectTimeout(e.clientId,i.uri),o}_handleVscodeUpgrade(e,n){let i=ju();if(!i){n.send(Yu(e,nn.MethodNotFound,"No upgrade supervisor is available for this agent host."));return}RC(i).then(o=>n.send(Rs(e,o)),o=>{this._logService.warn(`[ProtocolServer] vscodeUpgrade signal failed: ${o instanceof Error?o.message:String(o)}`),n.send(Es(e,o))})}_handleReconnect(e,n,i){this._logService.info(`[ProtocolServer] Reconnect: clientId=${e.clientId}, lastSeenSeq=${e.lastSeenServerSeq}`);let o={clientId:e.clientId,protocolVersion:ws,transport:n,subscriptions:new Map,disposables:i};this._clients.set(e.clientId,o),this._onDidChangeConnectionCount.fire(this._clients.size),this._registerClientFileSystemAuthority(e.clientId,i);let s=this._replayBuffer.length>0?this._replayBuffer[0].serverSeq:this._stateManager.serverSeq,a=e.lastSeenServerSeq>=s,l=this._restoreReconnectSubscriptions(o,e,a);return{client:o,responsePromise:l}}_registerClientFileSystemAuthority(e,n){n.add(this._clientFileSystemProvider.registerAuthority(e,{resourceList:i=>this._sendReverseRequest(e,"resourceList",{uri:i.toString()}),resourceRead:i=>this._sendReverseRequest(e,"resourceRead",{uri:i.toString()}),resourceWrite:i=>this._sendReverseRequest(e,"resourceWrite",i),resourceCopy:i=>this._sendReverseRequest(e,"resourceCopy",i),resourceDelete:i=>this._sendReverseRequest(e,"resourceDelete",i),resourceMove:i=>this._sendReverseRequest(e,"resourceMove",i),resourceRequest:i=>this._sendReverseRequest(e,"resourceRequest",i),resourceResolve:i=>this._sendReverseRequest(e,"resourceResolve",i),resourceMkdir:i=>this._sendReverseRequest(e,"resourceMkdir",i)}))}async _restoreReconnectSubscriptions(e,n,i){let o=[],s=await Promise.all(n.subscriptions.map(async a=>{let l=a.toString(),c=Qu(l);if(c){if(c.kind==="otlp-logs"){if(!this._config.otlpLogEmitter){this._logService.warn(`[ProtocolServer] Reconnect: dropping OTLP subscription ${l}: no OTLP emitter configured.`);return}e.subscriptions.set(c.uri,c);return}if(c.kind==="resource-watch"){let u=this._agentService.onResourceWatchSubscribed(c.uri);if(!u){this._logService.info(`[ProtocolServer] Reconnect: resource watch ${l} no longer parses`),o.push(a);return}return e.subscriptions.set(c.uri,c),{resource:c.uri,state:u,fromSeq:this._stateManager.serverSeq}}try{let u=await this._agentService.subscribe(y.parse(l),e.clientId);return e.subscriptions.set(c.uri,c),this._clearClientToolCallDisconnectTimeout(e.clientId,c.uri),u}catch(u){this._logService.info(`[ProtocolServer] Reconnect: failed to restore subscription ${l}: ${u instanceof Error?u.message:String(u)}`),o.push(a);return}}}));if(i){let a=[];for(let l of this._replayBuffer)l.serverSeq>n.lastSeenServerSeq&&this._isRelevantToClient(e,l)&&a.push(l);return{type:"replay",actions:a,missing:o}}return{type:"snapshot",snapshots:s.filter(a=>a!==void 0)}}_handleClientDisconnected(e){for(let n of this._stateManager.getSessionUris()){let i=this._stateManager.getSessionState(n),o=i?this._hasPendingClientToolCall(i,e):!1;i?.activeClient?.clientId===e&&this._stateManager.dispatchServerAction(n,{type:"session/activeClientChanged",activeClient:null}),(i?.activeClient?.clientId===e||o)&&this._startClientToolCallDisconnectTimeout(e,n)}}_hasPendingClientToolCall(e,n){let i=e?.activeTurn;return i?i.responseParts.some(o=>o.kind==="toolCall"&&o.toolCall.toolClientId===n&&(o.toolCall.status==="streaming"||o.toolCall.status==="running"||o.toolCall.status==="pending-confirmation")):!1}_hasReplacementActiveClientTool(e,n,i){let o=e.activeClient;return o!==void 0&&o.clientId!==n&&o.tools.some(s=>s.name===i)}_startClientToolCallDisconnectTimeout(e,n){this._clearClientToolCallDisconnectTimeout(e,n);let i=this._clientToolCallDisconnectTimeoutKey(e,n);this._clientToolCallDisconnectTimeouts.set(i,setTimeout(()=>{this._clientToolCallDisconnectTimeouts.delete(i),this._completeDisconnectedClientToolCalls(e,n)},iD))}_clearClientToolCallDisconnectTimeout(e,n){let i=this._clientToolCallDisconnectTimeoutKey(e,n),o=this._clientToolCallDisconnectTimeouts.get(i);o&&(clearTimeout(o),this._clientToolCallDisconnectTimeouts.delete(i))}_clientToolCallDisconnectTimeoutKey(e,n){return`${e}
${n}`}_completeDisconnectedClientToolCalls(e,n){let i=this._stateManager.getSessionState(n),o=i?.activeTurn;if(o)for(let s of o.responseParts){if(s.kind!=="toolCall")continue;let a=s.toolCall;if(a.toolClientId===e&&(a.status==="streaming"||a.status==="running"||a.status==="pending-confirmation")){let l=this._hasReplacementActiveClientTool(i,e,a.toolName);a.status==="streaming"&&this._stateManager.dispatchServerAction(n,{type:"session/toolCallReady",turnId:o.id,toolCallId:a.toolCallId,invocationMessage:a.invocationMessage??a.displayName,confirmed:"not-needed"}),this._stateManager.dispatchServerAction(n,{type:"session/toolCallComplete",turnId:o.id,toolCallId:a.toolCallId,result:{success:!1,pastTenseMessage:`${a.displayName} failed`,...l?{content:[{type:"text",text:`The client that was running ${a.displayName} disconnected, but another active client now provides ${a.displayName}. You may try calling the tool again.`}]}:{},error:{message:`Client ${e} disconnected before completing ${a.displayName}`}}})}}}_sendReverseRequest(e,n,i){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:i};o.transport.send(c)})}_rejectPendingReverseRequests(e){for(let[n,i]of this._pendingReverseRequests)i.clientId===e&&(this._pendingReverseRequests.delete(n),i.reject(new Error(`Client ${e} disconnected`)))}_handleRequest(e,n,i,o){let s=this._requestHandlers.hasOwnProperty(n)?this._requestHandlers[n]:void 0;if(s){s(e,i).then(l=>{this._logService.trace(`[ProtocolServer] Request '${n}' id=${o} succeeded`),e.transport.send(Rs(o,l??null))}).catch(l=>{this._logService.error(`[ProtocolServer] Request '${n}' failed`,l),e.transport.send(Es(o,l))});return}let a=this._handleExtensionRequest(n,i);if(a){a.then(l=>{e.transport.send(Rs(o,l??null))}).catch(l=>{this._logService.error(`[ProtocolServer] Extension request '${n}' failed`,l),e.transport.send(Es(o,l))});return}e.transport.send(Yu(o,So,`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 i of this._clients.values())this._isRelevantToClient(i,e)&&i.transport.send(n)}_broadcastNotification(e){let{type:n,...i}=e,o={jsonrpc:"2.0",method:n,params:i};for(let s of this._clients.values())s.transport.send(o)}_removeSubscription(e,n){let i=Qu(n);if(!i)return;let o=e.subscriptions.get(i.uri);o&&(e.subscriptions.delete(i.uri),o.kind==="state"?this._agentService.unsubscribe(y.parse(o.uri),e.clientId):o.kind==="resource-watch"&&this._agentService.onResourceWatchUnsubscribed(o.uri))}_broadcastOtlpLog(e){let n=AC(e);for(let i of this._clients.values())for(let o of i.subscriptions.values()){if(o.kind!=="otlp-logs"||e.severityNumber<kC(o.level))continue;let s={jsonrpc:"2.0",method:"otlp/exportLogs",params:{channel:o.uri,payload:n}};i.transport.send(s)}}_isRelevantToClient(e,n){if(xa(n.channel)){for(let o of e.subscriptions.values())if(o.kind==="state"&&xa(o.uri))return!0;return!1}let i=e.subscriptions.get(n.channel);return i?.kind==="state"||i?.kind==="resource-watch"}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();for(let e of this._clientToolCallDisconnectTimeouts.values())clearTimeout(e);this._clientToolCallDisconnectTimeouts.clear(),this._replayBuffer.length=0,super.dispose()}};Ar=w([C(5,L)],Ar);var rD="ahp",oD=75*1024*1024,sD=5,aD=1024*1024,Ps=class extends T{constructor(e,n,i){super();this._options=e;this._fileService=n;this._logService=i;this._currentSize=0;this._segment=0;this._queue=Promise.resolve();this._pending=[];this._drainScheduled=!1;this._directory=ee(this._options.logsHome,rD);let o=uD(this._options.connectionId).slice(0,64);this._baseName=`ahp-${dD(new Date)}-${o}.jsonl`,this._maxFileSizeBytes=this._options.maxFileSizeBytes??oD,this._maxFiles=this._options.maxFiles??sD,this._currentFile=ee(this._directory,this._baseName)}get resource(){return this._currentFile}log(e,n,i){let o={...e,_ahpLog:{ts:new Date().toISOString(),dir:n,connectionId:this._options.connectionId,transport:this._options.transport,...typeof i=="number"?{byteLength:i}:{}}},s=`${lD(o)}
`;this._pending.push(k.fromString(s)),this._scheduleDrain()}async flush(){await this._queue}_scheduleDrain(){this._drainScheduled||(this._drainScheduled=!0,this._queue=this._queue.then(()=>this._drainPending()).catch(e=>{this._logService.error("[AHPLog] Failed to write transport log",e)}))}async _drainPending(){if(this._drainScheduled=!1,this._pending.length===0)return;let e=this._pending;this._pending=[],this._folderCreated||(this._folderCreated=this._fileService.createFolder(this._directory)),await this._folderCreated,this._currentSize===0&&(this._currentSize=await this._getFileSize(this._currentFile));let n=[],i=0,o=async()=>{if(n.length===0)return;let s=n.length===1?n[0]:k.concat(n,i);await this._fileService.writeFile(this._currentFile,s,{append:!0}),this._currentSize+=s.byteLength,n=[],i=0};for(let s of e){let a=this._currentSize+i;a>0&&a+s.byteLength>this._maxFileSizeBytes?(await o(),await this._rotate()):i>0&&i+s.byteLength>aD&&await o(),n.push(s),i+=s.byteLength}await o()}async _rotate(){this._segment++;let e=this._segment-this._maxFiles;e>=0&&await this._fileService.del(this._resourceForSegment(e)).catch(n=>{this._logService.trace("[AHPLog] Failed to delete old transport log",n)}),this._currentFile=this._resourceForSegment(this._segment),this._currentSize=await this._getFileSize(this._currentFile)}_resourceForSegment(e){if(e===0)return ee(this._directory,this._baseName);let n=this._baseName.slice(0,-6);return ee(this._directory,`${n}.${e}.jsonl`)}async _getFileSize(e){try{return(await this._fileService.resolve(e)).size??0}catch{return 0}}};Ps=w([C(1,Se),C(2,L)],Ps);function Qm(r){return k.fromString(r).byteLength}function lD(r){return JSON.stringify(r,cD)}function cD(r,t){return t&&typeof t=="object"&&t.$mid===1&&Iy(t)?y.revive(t).toString():t}function dD(r){return r.toISOString().replace(/[:.]/g,"-")}function uD(r){return r.replace(/[\\/:\*\?"<>\|\s]+/g,"-").replace(/^-+|-+$/g,"")||"connection"}var Ym=class extends T{constructor(e,n,i){super();this._ws=e;this._WebSocket=n;this._ahpLogger=i;this._onMessage=this._register(new x);this.onMessage=this._onMessage.event;this._onClose=this._register(new x);this.onClose=this._onClose.event;this._ahpLogger&&this._register(this._ahpLogger),this._ws.on("message",o=>{try{let s=typeof o=="string"?o:o.toString("utf-8"),a=JSON.parse(s);this._ahpLogger?.log(a,"c2s",Qm(s)),this._onMessage.fire(a)}catch{this.send({jsonrpc:"2.0",id:null,error:{code:ob,message:"Parse error"}})}}),this._ws.on("close",()=>{this._onClose.fire()}),this._ws.on("error",()=>{this._onClose.fire()})}send(e){if(this._ws.readyState===this._WebSocket.OPEN){let n=JSON.stringify(e);this._ahpLogger?.log(e,"s2c",Qm(n)),this._ws.send(n)}}dispose(){this._ws.close(),super.dispose()}},gl=class r extends T{constructor(e,n,i,o,s,a){super();this._logService=n;this._ahpLogOptions=i;this._connectionCount=0;this._onConnection=this._register(new x);this.onConnection=this._onConnection.event;this._WebSocket=o.WebSocket;let l=typeof e=="number"?{port:e}:e,c=l.host??"127.0.0.1",u=l.connectionTokenValidate?(d,f)=>{let h=a.parse(d.req.url??"",!0).query[Yp];if(!l.connectionTokenValidate(h)){this._logService.warn("[WebSocketProtocol] Connection rejected: invalid connection token"),f(!1,403,"Forbidden");return}f(!0)}:void 0;if(l.socketPath){this._httpServer=s.createServer(),this._wss=new o.WebSocketServer({server:this._httpServer,verifyClient:u});let d=this._httpServer;this.whenListening=new Promise((f,m)=>{d.once("listening",()=>{this._logService.info(`[WebSocketProtocol] Server listening on socket ${l.socketPath}`),f()}),d.once("error",m)}),this._httpServer.listen(l.socketPath)}else{this._wss=new o.WebSocketServer({port:l.port,host:c,verifyClient:u});let d=this._wss;this.whenListening=new Promise((f,m)=>{d.once("listening",()=>{let h=d.address(),v=!h||typeof h=="string"?`${c}:${l.port}`:`${h.address}:${h.port}`;this._logService.info(`[WebSocketProtocol] Server listening on ${v}`),f()}),d.once("error",m)})}this._wss.on("connection",d=>{this._logService.trace("[WebSocketProtocol] New client connection");let f=new Ym(d,this._WebSocket,this._createAhpLogger());this._onConnection.fire(f)}),this._wss.on("error",d=>{this._logService.error("[WebSocketProtocol] Server error",d)})}get address(){let e=this._wss.address();return!e||typeof e=="string"?e??void 0:`${e.address}:${e.port}`}get boundPort(){let e=this._wss.address();if(!(!e||typeof e=="string"))return e.port}static async create(e,n,i){let[o,s,a]=await Promise.all([import("ws"),import("http"),import("url")]);return new r(e,n,i,o,s,a)}_createAhpLogger(){if(this._ahpLogOptions)return this._ahpLogOptions.instantiationService.createInstance(Ps,{logsHome:this._ahpLogOptions.logsHome,connectionId:`agent-host-${++this._connectionCount}-${q()}`,transport:"websocket"})}dispose(){this._wss.close(),this._httpServer?.close(),super.dispose()}};import{homedir as vD,tmpdir as bD}from"os";var LC=/^([^.]+\..+)[:=](.+)$/,le=class{constructor(t,e,n){this._args=t;this.paths=e;this.productService=n}get appRoot(){return de(rt.asFileUri("").fsPath)}get userHome(){return y.file(this.paths.homeDir)}get userDataPath(){return this.paths.userDataDir}get appSettingsHome(){return y.file(B(this.userDataPath,"User"))}get tmpDir(){return y.file(this.paths.tmpDir)}get cacheHome(){return y.file(this.userDataPath)}get stateResource(){return ee(this.appSettingsHome,"globalStorage","storage.json")}get userRoamingDataHome(){return this.appSettingsHome.with({scheme:oe.vscodeUserData})}get userDataSyncHome(){return ee(this.appSettingsHome,"sync")}get logsHome(){if(!this.args.logsPath){let t=aI(new Date).replace(/-|:|\.\d+Z$/g,"");this.args.logsPath=B(this.userDataPath,"logs",t)}return y.file(this.args.logsPath)}get sync(){return this.args.sync}get workspaceStorageHome(){return ee(this.appSettingsHome,"workspaceStorage")}get localHistoryHome(){return ee(this.appSettingsHome,"History")}get keyboardLayoutResource(){return ee(this.userRoamingDataHome,"keyboardLayout.json")}get argvResource(){let t=ke.VSCODE_PORTABLE;return t?y.file(B(t,"argv.json")):ee(this.appSettingsHome,"argv.json")}get isExtensionDevelopment(){return!!this.args.extensionDevelopmentPath}get untitledWorkspacesHome(){return y.file(B(this.userDataPath,"Workspaces"))}get builtinExtensionsPath(){let t=this.args["builtin-extensions-dir"];return t?an(t):Qt(B(rt.asFileUri("").fsPath,"..","extensions"))}get extensionsDownloadLocation(){let t=this.args["extensions-download-dir"];return t?y.file(an(t)):y.file(B(this.userDataPath,"CachedExtensionVSIXs"))}get extensionsPath(){let t=this.args["extensions-dir"];if(t)return an(t);let e=ke.VSCODE_EXTENSIONS;if(e)return e;let n=ke.VSCODE_PORTABLE;return n?B(n,"extensions"):ee(this.userHome,this.productService.dataFolderName,"extensions").fsPath}get appSharedDataHome(){let t=this.args["shared-data-dir"];if(t)return y.file(an(t));let e=ke.VSCODE_PORTABLE;return e?y.file(B(e,"shared-data")):ee(this.userHome,this.productService.sharedDataFolderName)}get extensionDevelopmentLocationURI(){let t=this.args.extensionDevelopmentPath;if(Array.isArray(t))return t.map(e=>/^[^:/?#]+?:\/\//.test(e)?y.parse(e):y.file(Qt(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)?y.parse(t):y.file(Qt(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=ke.VSCODE_SKIP_BUILTIN_EXTENSIONS;return t?t.split(",").map(e=>e.trim()).filter(e=>e):[]}get debugExtensionHost(){return pD(this.args,this.isBuilt)}get debugRenderer(){return!!this.args.debugRenderer}get isBuilt(){return!ke.VSCODE_DEV}get verbose(){return!!this.args.verbose}get logLevel(){return this.args.log?.find(t=>!LC.test(t))}get extensionLogLevel(){let t=[];for(let e of this.args.log||[]){let n=LC.exec(e);n?.[1]&&n[2]&&t.push([n[1],n[2]])}return t.length?t:void 0}get serviceMachineIdResource(){return ee(y.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=ke.VSCODE_PORTABLE;return t?y.file(B(t,"policy.json")):ee(this.userHome,this.productService.dataFolderName,"policy.json")}}get agentSessionsWorkspace(){return ee(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}};w([ce],le.prototype,"appRoot",1),w([ce],le.prototype,"userHome",1),w([ce],le.prototype,"userDataPath",1),w([ce],le.prototype,"appSettingsHome",1),w([ce],le.prototype,"tmpDir",1),w([ce],le.prototype,"cacheHome",1),w([ce],le.prototype,"stateResource",1),w([ce],le.prototype,"userRoamingDataHome",1),w([ce],le.prototype,"userDataSyncHome",1),w([ce],le.prototype,"sync",1),w([ce],le.prototype,"workspaceStorageHome",1),w([ce],le.prototype,"localHistoryHome",1),w([ce],le.prototype,"keyboardLayoutResource",1),w([ce],le.prototype,"argvResource",1),w([ce],le.prototype,"isExtensionDevelopment",1),w([ce],le.prototype,"untitledWorkspacesHome",1),w([ce],le.prototype,"builtinExtensionsPath",1),w([ce],le.prototype,"extensionsDownloadLocation",1),w([ce],le.prototype,"extensionsPath",1),w([ce],le.prototype,"appSharedDataHome",1),w([ce],le.prototype,"extensionDevelopmentLocationURI",1),w([ce],le.prototype,"extensionDevelopmentKind",1),w([ce],le.prototype,"extensionTestsLocationURI",1),w([ce],le.prototype,"debugExtensionHost",1),w([ce],le.prototype,"logLevel",1),w([ce],le.prototype,"extensionLogLevel",1),w([ce],le.prototype,"serviceMachineIdResource",1),w([ce],le.prototype,"disableTelemetry",1),w([ce],le.prototype,"disableExperiments",1),w([ce],le.prototype,"disableWorkspaceTrust",1),w([ce],le.prototype,"useInMemorySecretStorage",1),w([ce],le.prototype,"policyFile",1),w([ce],le.prototype,"agentSessionsWorkspace",1);function pD(r,t){return MC(r["inspect-extensions"],r["inspect-brk-extensions"],5870,t,r.debugId,r.extensionEnvironment)}function MC(r,t,e,n,i,o){let a=Number(t||r)||(n?null:e),l=a?!!t:!1,c;if(o)try{c=JSON.parse(o)}catch{}return{port:a,break:l,debugId:i,env:c}}import{homedir as NC}from"os";import{resolve as fD,isAbsolute as gD,join as ks}from"path";var mD=process.env.VSCODE_CWD||process.cwd();function UC(r,t){let e=hD(r,t),n=[e];return gD(e)||n.unshift(mD),fD(...n)}function hD(r,t){process.env.VSCODE_DEV&&(t="code-oss-dev");let e=process.env.VSCODE_PORTABLE;if(e)return ks(e,"user-data");let n=process.env.VSCODE_APPDATA;if(n)return ks(n,t);let i=r["user-data-dir"];return i||yD(t)}function yD(r){let t;switch(process.platform){case"win32":if(t=process.env.APPDATA,!t){let e=process.env.USERPROFILE;if(typeof e!="string")throw new Error("Windows: Unexpected undefined %USERPROFILE% environment variable");t=ks(e,"AppData","Roaming")}break;case"darwin":t=ks(NC(),"Library","Application Support");break;case"linux":t=process.env.XDG_CONFIG_HOME||ks(NC(),".config");break;default:throw new Error("Platform not supported")}return ks(t,r)}var Xu=class extends le{constructor(t,e){let n=vD();super(t,{homeDir:n,tmpDir:bD(),userDataDir:UC(t,e.nameShort)},e)}};import SD from"minimist";var Ple={o:g(2213,null),e:g(2197,null),t:g(2227,null),m:g(2208,null)};var FC={chat:{type:"subcommand",description:"Pass in a prompt to run in a chat session in the current working directory.",options:{_:{type:"string[]",description:g(2217,null)},mode:{type:"string",cat:"o",alias:"m",args:"mode",description:g(2184,null)},"add-file":{type:"string[]",cat:"o",alias:"a",args:"path",description:g(2179,null)},maximize:{type:"boolean",cat:"o",description:g(2183,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:g(2220,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:g(2211,null)},profile:{type:"string",cat:"o",args:"profileName",description:g(2216,null)},help:{type:"boolean",alias:"h",description:g(2199,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(2185,null)},"disable-telemetry":{type:"boolean"},"telemetry-level":{type:"string"}}},agent:{type:"subcommand",description:"Start and interact with AI agent hosts.",options:{"cli-data-dir":{type:"string",args:"dir",description:g(2185,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(2185,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(2189,null)},merge:{type:"boolean",cat:"o",alias:"m",args:["path1","path2","base","result"],description:g(2209,null)},add:{type:"boolean",cat:"o",alias:"a",args:"folder",description:g(2178,null)},remove:{type:"boolean",cat:"o",args:"folder",description:g(2218,null)},goto:{type:"boolean",cat:"o",alias:"g",args:"file:line[:character]",description:g(2198,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:g(2210,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:g(2219,null)},agents:{type:"boolean",cat:"o",deprecates:["sessions"],description:g(2181,null)},wait:{type:"boolean",cat:"o",alias:"w",description:g(2237,null)},waitMarkerFilePath:{type:"string"},locale:{type:"string",cat:"o",args:"locale",description:g(2205,null)},"user-data-dir":{type:"string",cat:"o",args:"dir",description:g(2234,null)},profile:{type:"string",cat:"o",args:"profileName",description:g(2216,null)},help:{type:"boolean",cat:"o",alias:"h",description:g(2199,null)},"stdin-to-clipboard":{type:"boolean",cat:"o",alias:"c",description:g(2186,null)},"extensions-dir":{type:"string",deprecates:["extensionHomePath"],cat:"e",args:"dir",description:g(2196,null)},"extensions-download-dir":{type:"string"},"builtin-extensions-dir":{type:"string"},"shared-data-dir":{type:"string"},"list-extensions":{type:"boolean",cat:"e",description:g(2204,null)},"agent-plugins-dir":{type:"string"},"agents-user-data-dir":{type:"string"},"agents-extensions-dir":{type:"string"},"show-versions":{type:"boolean",cat:"e",description:g(2221,null)},category:{type:"string",allowEmptyValue:!0,cat:"e",description:g(2182,null),args:"category"},"install-extension":{type:"string[]",cat:"e",args:"ext-id | path",description:g(2203,null)},"pre-release":{type:"boolean",cat:"e",description:g(2202,null)},"uninstall-extension":{type:"string[]",cat:"e",args:"ext-id",description:g(2229,null)},"update-extensions":{type:"boolean",cat:"e",description:g(2232,null)},"enable-proposed-api":{type:"string[]",allowEmptyValue:!0,cat:"e",args:"ext-id",description:g(2195,null)},"add-mcp":{type:"string[]",cat:"m",args:"json",description:g(2180,null)},version:{type:"boolean",cat:"t",alias:"v",description:g(2236,null)},verbose:{type:"boolean",cat:"t",global:!0,description:g(2235,null)},log:{type:"string[]",cat:"t",args:"level",global:!0,description:g(2207,null)},status:{type:"boolean",alias:"s",cat:"t",description:g(2222,null)},"prof-startup":{type:"boolean",cat:"t",description:g(2215,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(2192,null)},"disable-extension":{type:"string[]",cat:"t",args:"ext-id",description:g(2191,null)},sync:{type:"string",cat:"t",description:g(2228,null),args:["on | off"]},"inspect-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugPluginHost"],args:"port",cat:"t",description:g(2201,null)},"inspect-brk-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugBrkPluginHost"],args:"port",cat:"t",description:g(2200,null)},"disable-lcd-text":{type:"boolean",cat:"t",description:g(2194,null)},"disable-gpu":{type:"boolean",cat:"t",description:g(2193,null)},"disable-chromium-sandbox":{type:"boolean",cat:"t",description:g(2190,null)},sandbox:{type:"boolean"},"locate-shell-integration-path":{type:"string",cat:"t",args:["shell"],description:g(2206,null)},telemetry:{type:"boolean",cat:"t",description:g(2225,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-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(2226,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[]"}},ID={onUnknownOption:()=>{},onMultipleValues:()=>{},onEmptyValue:()=>{},onDeprecatedOption:()=>{}};function Xm(r,t,e=ID){let n=r.find((f,m)=>f.length>0&&f[0]!=="-"&&t.hasOwnProperty(f)&&t[f].type==="subcommand"),i={},o=["_"],s=[],a={},l;for(let f in t){let m=t[f];m.type==="subcommand"?f===n&&(l=m):(m.alias&&(i[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 S in l.options)f[S]=l.options[S];let m=r.filter(S=>S!==n),h=e.getSubcommandReporter?e.getSubcommandReporter(n):void 0,v=Xm(m,f,h);return{[n]:v,_:[]}}let c=SD(r,{string:o,boolean:s,alias:i}),u={},d=c;u._=c._.map(f=>String(f)).filter(f=>f.length>0),delete d._;for(let f in t){let m=t[f];if(m.type==="subcommand")continue;m.alias&&delete d[m.alias];let h=d[f];if(m.deprecates)for(let v of m.deprecates)d.hasOwnProperty(v)&&(h||(h=d[v],h&&e.onDeprecatedOption(v,m.deprecationMessage||g(2188,null,f))),delete d[v]);if(typeof h<"u"){if(m.type==="string[]"){if(Array.isArray(h)||(h=[h]),!m.allowEmptyValue){let v=h.filter(S=>S.length>0);v.length!==h.length&&(e.onEmptyValue(f),h=v.length>0?v:void 0)}}else m.type==="string"&&(Array.isArray(h)?(h=h.pop(),e.onMultipleValues(f,h)):!h&&!m.allowEmptyValue&&(e.onEmptyValue(f),h=void 0));u[f]=h,m.deprecationMessage&&e.onDeprecatedOption(f,m.deprecationMessage)}delete d[f]}for(let f in d)e.onUnknownOption(f);return u}var Zu=class extends T{constructor(t,e=[]){super(),this.logger=new wc([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 _D(r,t,e,n,i){try{let o=await import("@vscode/spdlog");o.setFlushOn(0);let s=await o.createAsyncRotatingLogger(r,t,e,n);return i?s.clearFormatters():s.setPattern("%Y-%m-%d %H:%M:%S.%e [%l] %v"),s}catch(o){console.error(o)}return null}function WC(r,t,e){switch(t){case 1:r.trace(e);break;case 2:r.debug(e);break;case 3:r.info(e);break;case 4:r.warn(e);break;case 5:r.error(e);break;case 0:break;default:throw new Error(`Invalid log level ${t}`)}}function $C(r,t){switch(t){case 1:r.setLevel(0);break;case 2:r.setLevel(1);break;case 3:r.setLevel(2);break;case 4:r.setLevel(3);break;case 5:r.setLevel(4);break;case 0:r.setLevel(6);break;default:throw new Error(`Invalid log level ${t}`)}}var ep=class extends br{constructor(e,n,i,o,s){super();this.buffer=[];this.setLevel(s),this._loggerCreationPromise=this._createSpdLogLogger(e,n,i,o),this._register(this.onDidChangeLogLevel(a=>{this._logger&&$C(this._logger,a)}))}async _createSpdLogLogger(e,n,i,o){let s=i?6:1,a=30/s*mc.MB,l=await _D(e,n,a,s,o);if(l){this._logger=l,$C(this._logger,this.getLevel());for(let{level:c,message:u}of this.buffer)WC(this._logger,c,u);this.buffer=[]}}log(e,n){this._logger?WC(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 tp=class extends _a{doCreateLogger(t,e,n){return new ep(q(),t.fsPath,!n?.donotRotate,!!n?.donotUseFormatters,e)}};var np=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,i=>({added:[...i.added].map(o=>this.transformLogger(o,n)),removed:[...i.removed].map(o=>this.transformLogger(o,n))}));case"onDidChangeVisibility":return Q.map(this.loggerService.onDidChangeVisibility,i=>[n.transformOutgoingURI(i[0]),i[1]]);case"onDidChangeLogLevel":return Q.map(this.loggerService.onDidChangeLogLevel,i=>Vf(i)?i:[n.transformOutgoingURI(i[0]),i[1]])}throw new Error(`Event not found: ${e}`)}async call(t,e,n){let i=this.getUriTransformer(t);switch(e){case"setLogLevel":return Vf(n[0])?this.loggerService.setLogLevel(n[0]):this.loggerService.setLogLevel(y.revive(i.transformIncoming(n[0][0])),n[0][1]);case"getRegisteredLoggers":return Promise.resolve([...this.loggerService.getRegisteredLoggers()].map(o=>this.transformLogger(o,i)))}throw new Error(`Call not found: ${e}`)}transformLogger(t,e){return{...t,resource:e.transformOutgoingURI(t.resource)}}};var VC=new class{transformIncoming(r){return r}transformOutgoing(r){return r}transformOutgoingURI(r){return r}transformOutgoingScheme(r){return r}};function Zm(r){let t=[];typeof r=="number"&&t.push("code/timeOrigin",r);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 i(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:i}}function CD(){if(typeof performance=="object"&&typeof performance.mark=="function"&&!performance.nodeTiming)return typeof performance.timeOrigin!="number"&&!performance.timing?Zm():{mark(r,t){performance.mark(r,t)},clearMarks(r){performance.clearMarks(r)},getMarks(){let r=performance.timeOrigin;typeof r!="number"&&(r=(performance.timing.navigationStart||performance.timing.redirectStart||performance.timing.fetchStart)??0);let t=[{name:"code/timeOrigin",startTime:Math.round(r)}];for(let e of performance.getEntriesByType("mark"))t.push({name:e.name,startTime:Math.round(r+e.startTime)});return t}};if(typeof process=="object"){let r=performance?.timeOrigin;return Zm(r)}else return console.trace("perf-util loaded in UNKNOWN environment"),Zm()}function TD(r){return r.MonacoPerformanceMarks||(r.MonacoPerformanceMarks=CD()),r.MonacoPerformanceMarks}var eh=TD(globalThis),BC=eh.mark,fce=eh.clearMarks,gce=eh.getMarks;async function ip(r,t,e,n,i,o){let s;try{await xD(r,t,e,n,i,o)}catch(a){s=a}finally{s&&i.errorTransformer&&(s=i.errorTransformer(s)),typeof s<"u"&&e.error(s),e.end()}}async function xD(r,t,e,n,i,o){th(o);let s=await r.open(t,{create:!1});try{th(o);let a=0,l=0,c=i&&typeof i.length=="number"?i.length:void 0,u=k.alloc(Math.min(i.bufferSize,typeof c=="number"?c:i.bufferSize)),d=i&&typeof i.position=="number"?i.position:0,f=0;do l=await r.read(s,d,u.buffer,f,u.byteLength-f),d+=l,f+=l,a+=l,typeof c=="number"&&(c-=l),f===u.byteLength&&(await e.write(n(u)),u=k.alloc(Math.min(i.bufferSize,typeof c=="number"?c:i.bufferSize)),f=0);while(l>0&&(typeof c!="number"||c>0)&&th(o)&&wD(a,i));if(f>0){let m=f;typeof c=="number"&&(m=Math.min(f,c)),e.write(n(u.slice(0,m)))}}catch(a){throw si(a)}finally{await r.close(s)}}function th(r){if(r.isCancellationRequested)throw vl();return!0}function wD(r,t){if(typeof t?.limits?.size=="number"&&r>t.limits.size)throw he(g(2399,null),"EntryTooLarge");return!0}var Ji=class extends T{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 Jr)}registerProvider(e,n){if(this.provider.has(e))throw new Error(`A filesystem provider for the scheme '${e}' is already registered.`);BC(`code/registerFilesystem/${e}`);let i=new z;return this.provider.set(e,n),this._onDidChangeFileSystemProviderRegistrations.fire({added:!0,scheme:e,provider:n}),i.add(n.onDidChangeFile(o=>{let s=new gc(o,!this.isPathCaseSensitive(n));this.internalOnDidFilesChange.fire(s),s.hasCorrelation()||this._onDidUncorrelatedFilesChange.fire(s)})),typeof n.onDidWatchError=="function"&&i.add(n.onDidWatchError(o=>this._onDidWatchError.fire(new Error(o)))),i.add(n.onDidChangeCapabilities(()=>this._onDidChangeFileSystemProviderCapabilities.fire({provider:n,scheme:e}))),A(()=>{this._onDidChangeFileSystemProviderRegistrations.fire({added:!1,scheme:e,provider:n}),this.provider.delete(e),gt(i)})}getProvider(e){return this.provider.get(e)}async activateProvider(e){let n=[];this._onWillActivateFileSystemProvider.fire({scheme:e,join(i){n.push(i)}}),!this.provider.has(e)&&await cr.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 i=this.provider.get(e.scheme);return!!(i&&i.capabilities&n)}listCapabilities(){return Ur.map(this.provider,([e,n])=>({scheme:e,capabilities:n.capabilities}))}async withProvider(e){if(!Py(e))throw new je(g(2388,null,this.resourceForError(e)),8);await this.activateProvider(e.scheme);let n=this.provider.get(e.scheme);if(!n){let i=new mn;throw i.message=g(2390,null,e.toString()),i}return n}async withReadProvider(e){let n=await this.withProvider(e);if(oi(n)||qt(n)||hc(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(oi(n)||qt(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(i){throw Dt(i)==="EntryNotFound"?new je(g(2385,null,this.resourceForError(e)),1):si(i)}}async doResolveFile(e,n){let i=await this.withProvider(e),o=this.isPathCaseSensitive(i),s=n?.resolveTo,a=n?.resolveSingleChildDescendants,l=n?.resolveMetadata,c=await i.stat(e),u;return this.toFileStat(i,e,c,void 0,!!l,(d,f)=>(u||(u=Cn.forUris(()=>!o),u.set(e,!0),s&&u.fill(!0,s)),u.get(d.resource)||u.findSuperstr(d.resource.with({query:null,fragment:null}))?!0:d.isDirectory&&a?f===1:!1))}async toFileStat(e,n,i,o,s,a){let{providerExtUri:l}=this.getExtUri(e),c={resource:n,name:l.basename(n),isFile:(i.type&1)!==0,isDirectory:(i.type&2)!==0,isSymbolicLink:(i.type&64)!==0,mtime:i.mtime,ctime:i.ctime,size:i.size,readonly:!!((i.permissions??0)&1)||!!(e.capabilities&2048),locked:!!((i.permissions??0)&2),executable:!!((i.permissions??0)&4),etag:Of({mtime:i.mtime,size:i.size}),children:void 0};if(c.isDirectory&&a(c,o)){try{let u=await e.readdir(n),d=await cr.settled(u.map(async([f,m])=>{try{let h=l.joinPath(n,f),v=s?await e.stat(h):{type:m};return await this.toFileStat(e,h,v,u.length,s,a)}catch(h){return this.logService.trace(h),null}}));c.children=Or(d)}catch(u){this.logService.trace(u),c.children=[]}return c}return c}async resolveAll(e){return cr.settled(e.map(async n=>{try{return{stat:await this.doResolveFile(n.resource,n.options),success:!0}}catch(i){return this.logService.trace(i),{stat:void 0,success:!1}}}))}async stat(e){let n=await this.withProvider(e),i=await n.stat(e);return this.toFileStat(n,e,i,void 0,!0,()=>!1)}async realpath(e){let n=await this.withProvider(e);if(Nv(n)){let i=await n.realpath(e);return e.with({path:i})}}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(i){return i}return!0}async doValidateCreateFile(e,n){if(!n?.overwrite&&await this.exists(e))throw new je(g(2381,null,this.resourceForError(e)),3,n)}async createFile(e,n=k.fromString(""),i){await this.doValidateCreateFile(e,i);let o=await this.writeFile(e,n);return this._onDidRunOperation.fire(new ii(e,0,o)),o}async writeFile(e,n,i){let o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),{providerExtUri:s}=this.getExtUri(o),a=i;if(Af(o)&&!a?.atomic){let l=o.enforceAtomicWriteFile?.(e);l&&(a={...i,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)),!oi(o)||qt(o)&&c instanceof k||qt(o)&&Af(o)&&a?.atomic?await this.doWriteUnbuffered(o,e,a,c):await this.doWriteBuffered(o,e,a,c instanceof k?By(c):c),this._onDidRunOperation.fire(new ii(e,4))}catch(l){throw new je(g(2380,null,this.resourceForError(e),si(l).toString()),Df(l),a)}return this.resolve(e,{resolveMetadata:!0})}async peekBufferForWriting(e,n){let i;if(qt(e)&&!(n instanceof k))if(Js(n)){let o=await Uy(n,3);o.ended?i=k.concat(o.buffer):i=o}else i=Ny(n,o=>k.concat(o),3);else i=n;return i}async validateWriteFile(e,n,i,o){let s=!!o?.unlock;if(s&&!(e.capabilities&8192))throw new Error(g(2398,null,this.resourceForError(n)));if(o?.append&&!Lv(e))throw new je(g(2377,null,this.resourceForError(n)),6);if(!!o?.atomic){if(!(e.capabilities&32768))throw new Error(g(2396,null,this.resourceForError(n)));if(!(e.capabilities&2))throw new Error(g(2397,null,this.resourceForError(n)));if(s)throw new Error(g(2395,null,this.resourceForError(n)))}let l;try{l=await e.stat(n)}catch{return Object.create(null)}if((l.type&2)!==0)throw new je(g(2383,null,this.resourceForError(n)),0,o);this.throwIfFileIsReadonly(n,l);let c;if(typeof o?.mtime=="number"&&typeof o.etag=="string"&&o.etag!==vc&&typeof l.mtime=="number"&&typeof l.size=="number"&&o.mtime<l.mtime&&o.etag!==Of({mtime:o.mtime,size:l.size})){if(c=await this.peekBufferForWriting(e,i),c instanceof k&&c.byteLength===l.size)try{let{value:u}=await this.readFile(n,{limits:{size:l.size}});if(c.equals(u))return{stat:l,buffer:c}}catch{}throw new je(g(2384,null),3,o)}return{stat:l,buffer:c}}async readFile(e,n,i){let o=await this.withReadProvider(e);return n?.atomic?this.doReadFileAtomic(o,e,n,i):this.doReadFile(o,e,n,i)}async doReadFileAtomic(e,n,i,o){return new Promise((s,a)=>{this.writeQueue.queueFor(n,async()=>{try{let l=await this.doReadFile(e,n,i,o);s(l)}catch(l){a(l)}},this.getExtUri(e).providerExtUri)})}async doReadFile(e,n,i,o){let s=await this.doReadFileStream(e,n,{...i,preferUnbuffered:!0},o);return{...s,value:await Ei(s.value)}}async readFileStream(e,n,i){let o=await this.withReadProvider(e);return this.doReadFileStream(o,e,n,i)}async doReadFileStream(e,n,i,o){let s=new Xe(o),a=i;yc(e)&&e.enforceAtomicReadFile?.(n)&&(a={...i,atomic:!0});let l=this.validateReadFile(n,a).then(u=>u,u=>{throw s.dispose(!0),u}),c;try{return typeof a?.etag=="string"&&a.etag!==vc&&await l,a?.atomic&&yc(e)||!(oi(e)||hc(e))||qt(e)&&a?.preferUnbuffered?c=this.readFileUnbuffered(e,n,a):hc(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(u){throw c&&await jl(c),this.restoreReadError(u,n,a)}}restoreReadError(e,n,i){let o=g(2378,null,this.resourceForError(n),si(e).toString());return e instanceof ho?new ho(o,e.stat,i):e instanceof mo?new mo(o,e.fileOperationResult,e.size,e.options):new je(o,Df(e),i)}readFileStreamed(e,n,i,o=Object.create(null)){let s=e.readFileStream(n,o,i);return af(s,{data:a=>a instanceof k?a:k.wrap(a),error:a=>this.restoreReadError(a,n,o)},a=>k.concat(a))}readFileBuffered(e,n,i,o=Object.create(null)){let s=zy();return ip(e,n,s,a=>a,{...o,bufferSize:this.BUFFER_SIZE,errorTransformer:a=>this.restoreReadError(a,n,o)},i),s}readFileUnbuffered(e,n,i){let o=Zn(s=>k.concat(s));return(async()=>{try{let s;i?.atomic&&yc(e)?s=await e.readFile(n,{atomic:!0}):s=await e.readFile(n),typeof i?.position=="number"&&(s=s.slice(i.position)),typeof i?.length=="number"&&(s=s.slice(0,i.length)),this.validateReadFileLimits(n,s.byteLength,i),o.end(k.wrap(s))}catch(s){o.error(s),o.end()}})(),o}async validateReadFile(e,n){let i=await this.resolve(e,{resolveMetadata:!0});if(i.isDirectory)throw new je(g(2382,null,this.resourceForError(e)),0,n);if(typeof n?.etag=="string"&&n.etag!==vc&&n.etag===i.etag)throw new ho(g(2386,null),i,n);return this.validateReadFileLimits(e,i.size,n),i}validateReadFileLimits(e,n,i){if(typeof i?.limits?.size=="number"&&n>i.limits.size)throw new mo(g(2387,null,this.resourceForError(e)),7,n,i)}async canMove(e,n,i){return this.doCanMoveCopy(e,n,"move",i)}async canCopy(e,n,i){return this.doCanMoveCopy(e,n,"copy",i)}async doCanMoveCopy(e,n,i,o){if(e.toString()!==n.toString())try{let s=i==="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,i,o)}catch(s){return s}return!0}async move(e,n,i){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",!!i),l=await this.resolve(n,{resolveMetadata:!0});return this._onDidRunOperation.fire(new ii(e,a==="move"?2:3,l)),l}async copy(e,n,i){let o=await this.withReadProvider(e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n),a=await this.doMoveCopy(o,e,s,n,"copy",!!i),l=await this.resolve(n,{resolveMetadata:!0});return this._onDidRunOperation.fire(new ii(e,a==="copy"?3:2,l)),l}async doMoveCopy(e,n,i,o,s,a){if(n.toString()===o.toString())return s;let{exists:l,isSameResourceWithDifferentPathCase:c}=await this.doValidateMoveCopy(e,n,i,o,s,a);if(l&&!c&&a&&await this.del(o,{recursive:!0}),await this.mkdirp(i,this.getExtUri(i).providerExtUri.dirname(o)),s==="copy"){if(e===i&&kf(e))await e.copy(n,o,{overwrite:a});else{let u=await this.resolve(n);u.isDirectory?await this.doCopyFolder(e,u,i,o):await this.doCopyFile(e,n,i,o)}return s}else return e===i?(await e.rename(n,o,{overwrite:a}),s):(await this.doMoveCopy(e,n,i,o,"copy",a),await this.del(n,{recursive:!0}),"copy")}async doCopyFile(e,n,i,o){if(oi(e)&&oi(i))return this.doPipeBuffered(e,n,i,o);if(oi(e)&&qt(i))return this.doPipeBufferedToUnbuffered(e,n,i,o);if(qt(e)&&oi(i))return this.doPipeUnbufferedToBuffered(e,n,i,o);if(qt(e)&&qt(i))return this.doPipeUnbuffered(e,n,i,o)}async doCopyFolder(e,n,i,o){await i.mkdir(o),Array.isArray(n.children)&&await cr.settled(n.children.map(async s=>{let a=this.getExtUri(i).providerExtUri.joinPath(o,s.name);return s.isDirectory?this.doCopyFolder(e,await this.resolve(s.resource),i,a):this.doCopyFile(e,s.resource,i,a)}))}async doValidateMoveCopy(e,n,i,o,s,a){let l=!1;if(e===i){let{providerExtUri:u,isPathCaseSensitive:d}=this.getExtUri(e);if(d||(l=u.isEqual(n,o)),l&&s==="copy")throw new Error(g(2391,null,this.resourceForError(n),this.resourceForError(o)));if(!l&&u.isEqualOrParent(o,n))throw new Error(g(2392,null,this.resourceForError(n),this.resourceForError(o)))}let c=await this.exists(o);if(c&&!l){if(!a)throw new je(g(2393,null,this.resourceForError(n),this.resourceForError(o)),4);if(e===i){let{providerExtUri:u}=this.getExtUri(e);if(u.isEqualOrParent(n,o))throw new Error(g(2394,null,this.resourceForError(n),this.resourceForError(o)))}}return{exists:c,isSameResourceWithDifferentPathCase:l}}getExtUri(e){let n=this.isPathCaseSensitive(e);return{providerExtUri:n?se:Zp,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 i=await this.resolve(e,{resolveMetadata:!0});return this._onDidRunOperation.fire(new ii(e,0,i)),i}async mkdirp(e,n){let i=[],{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(2389,null,this.resourceForError(n)));break}catch(s){if(Dt(s)!=="EntryNotFound")throw s;i.push(o.basename(n)),n=o.dirname(n)}for(let s=i.length-1;s>=0;s--){n=o.joinPath(n,i[s]);try{await e.mkdir(n)}catch(a){if(Dt(a)!=="EntryExists")throw a}}}async canDelete(e,n){try{await this.doValidateDelete(e,n)}catch(i){return i}return!0}async doValidateDelete(e,n){let i=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e),o=!!n?.useTrash;if(o&&!(i.capabilities&4096))throw new Error(g(2376,null,this.resourceForError(e)));let s=n?.atomic;if(s&&!(i.capabilities&65536))throw new Error(g(2372,null,this.resourceForError(e)));if(o&&s)throw new Error(g(2375,null,this.resourceForError(e)));let a;try{a=await i.stat(e)}catch{}if(a)this.throwIfFileIsReadonly(e,a);else throw new je(g(2374,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(2373,null,this.resourceForError(e)))}return i}async del(e,n){let i=await this.doValidateDelete(e,n),o=n;if(Uv(i)&&!o?.atomic){let c=i.enforceAtomicDelete?.(e);c&&(o={...n,atomic:c})}let s=!!o?.useTrash,a=!!o?.recursive,l=o?.atomic??!1;await i.delete(e,{recursive:a,useTrash:s,atomic:l}),this._onDidRunOperation.fire(new ii(e,1))}async cloneFile(e,n){let i=await this.withProvider(e),o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n);if(!(i===o&&this.getExtUri(i).providerExtUri.isEqual(e,n)))return i===o&&Mv(i)?i.cloneFile(e,n):(await this.mkdirp(o,this.getExtUri(o).providerExtUri.dirname(n)),i===o&&kf(i)?this.writeQueue.queueFor(e,()=>i.copy(e,n,{overwrite:!0}),this.getExtUri(i).providerExtUri):this.writeQueue.queueFor(e,()=>this.doCopyFile(i,e,o,n),this.getExtUri(i).providerExtUri))}static{this.WATCHER_CORRELATION_IDS=0}createWatcher(e,n){return this.watch(e,{...n,correlationId:Ji.WATCHER_CORRELATION_IDS++})}watch(e,n={recursive:!1,excludes:[]}){let i=new z,o=!1,s=()=>{o=!0};i.add(A(()=>s())),(async()=>{try{let l=await this.doWatch(e,n);o?gt(l):s=()=>gt(l)}catch(l){this.logService.error(l)}})();let a=n.correlationId;if(typeof a=="number"){let l=i.add(new x);return i.add(this.internalOnDidFilesChange.event(u=>{u.correlates(a)&&l.fire(u)})),{onDidChange:l.event,dispose:()=>i.dispose()}}return i}async doWatch(e,n){let i=await this.withProvider(e),o=ht([this.getExtUri(i).providerExtUri.getComparisonKey(e),n]),s=this.activeWatchers.get(o);return s||(s={count:0,disposable:i.watch(e,n)},this.activeWatchers.set(o,s)),s.count+=1,A(()=>{s&&(s.count--,s.count===0&&(gt(s.disposable),this.activeWatchers.delete(o)))})}dispose(){super.dispose();for(let[,e]of this.activeWatchers)gt(e.disposable);this.activeWatchers.clear()}async doWriteBuffered(e,n,i,o){return this.writeQueue.queueFor(n,async()=>{let s=await e.open(n,{create:!0,unlock:i?.unlock??!1,append:i?.append??!1});try{Js(o)||Kl(o)?await this.doWriteStreamBufferedQueued(e,s,o):await this.doWriteReadableBufferedQueued(e,s,o)}catch(a){throw si(a)}finally{await e.close(s)}},this.getExtUri(e).providerExtUri)}async doWriteStreamBufferedQueued(e,n,i){let o=0,s;if(Kl(i)){if(i.buffer.length>0){let a=k.concat(i.buffer);await this.doWriteBuffer(e,n,a,a.byteLength,o,0),o+=a.byteLength}if(i.ended)return;s=i.stream}else s=i;return new Promise((a,l)=>{Gl(s,{onData:async c=>{s.pause();try{await this.doWriteBuffer(e,n,c,c.byteLength,o,0)}catch(u){return l(u)}o+=c.byteLength,setTimeout(()=>s.resume())},onError:c=>l(c),onEnd:()=>a()})})}async doWriteReadableBufferedQueued(e,n,i){let o=0,s;for(;(s=i.read())!==null;)await this.doWriteBuffer(e,n,s,s.byteLength,o,0),o+=s.byteLength}async doWriteBuffer(e,n,i,o,s,a){let l=0;for(;l<o;){let c=await e.write(n,s+l,i.buffer,a+l,o-l);l+=c}}async doWriteUnbuffered(e,n,i,o){return this.writeQueue.queueFor(n,()=>this.doWriteUnbufferedQueued(e,n,i,o),this.getExtUri(e).providerExtUri)}async doWriteUnbufferedQueued(e,n,i,o){let s;o instanceof k?s=o:Js(o)?s=await Ei(o):Kl(o)?s=await Hy(o):s=Vy(o),await e.writeFile(n,s.buffer,{create:!0,overwrite:!0,unlock:i?.unlock??!1,atomic:i?.atomic??!1,append:i?.append??!1})}async doPipeBuffered(e,n,i,o){return this.writeQueue.queueFor(o,()=>this.doPipeBufferedQueued(e,n,i,o),this.getExtUri(i).providerExtUri)}async doPipeBufferedQueued(e,n,i,o){let s,a;try{s=await e.open(n,{create:!1}),a=await i.open(o,{create:!0,unlock:!1});let l=k.alloc(this.BUFFER_SIZE),c=0,u=0,d=0;do d=await e.read(s,c,l.buffer,u,l.byteLength-u),await this.doWriteBuffer(i,a,l,d,c,u),c+=d,u+=d,u===l.byteLength&&(u=0);while(d>0)}catch(l){throw si(l)}finally{await cr.settled([typeof s=="number"?e.close(s):Promise.resolve(),typeof a=="number"?i.close(a):Promise.resolve()])}}async doPipeUnbuffered(e,n,i,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedQueued(e,n,i,o),this.getExtUri(i).providerExtUri)}async doPipeUnbufferedQueued(e,n,i,o){return i.writeFile(o,await e.readFile(n),{create:!0,overwrite:!0,unlock:!1,atomic:!1})}async doPipeUnbufferedToBuffered(e,n,i,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedToBufferedQueued(e,n,i,o),this.getExtUri(i).providerExtUri)}async doPipeUnbufferedToBufferedQueued(e,n,i,o){let s=await i.open(o,{create:!0,unlock:!1});try{let a=await e.readFile(n);await this.doWriteBuffer(i,s,k.wrap(a),a.byteLength,0,0)}catch(a){throw si(a)}finally{await i.close(s)}}async doPipeBufferedToUnbuffered(e,n,i,o){let s=await Ei(this.readFileBuffered(e,n,ze.None));await this.doWriteUnbuffered(i,o,void 0,s)}throwIfFileSystemIsReadonly(e,n){if(e.capabilities&2048)throw new je(g(2379,null,this.resourceForError(n)),6);return e}throwIfFileIsReadonly(e,n){if((n.permissions??0)&1)throw new je(g(2379,null,this.resourceForError(e)),6)}resourceForError(e){return e.scheme===oe.file?e.fsPath:e.toString(!0)}};Ji=w([C(0,L)],Ji);import{constants as oh,promises as Dr}from"fs";function ap(r){return typeof r.correlationId=="number"}function zC(r){return r.recursive===!0}var rp=class r extends T{constructor(e,n,i,o){super();this.onFileChanges=e;this.onLogMessage=n;this.verboseLogging=i;this.options=o;this.watcherDisposables=this._register(new Rt);this.requests=void 0;this.restartCounter=0}static{this.MAX_RESTARTS=5}init(){let e=new z;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<r.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()}},op=class extends rp{constructor(t,e,n){super(t,e,n,{type:"node.js",restartOnError:!1})}},sp=class extends rp{constructor(t,e,n){super(t,e,n,{type:"universal",restartOnError:!0})}};function ih(r){return r.map(t=>({type:t.type,resource:y.revive(t.resource),cId:t.cId}))}function qC(r){let t=new nh;for(let e of r)t.processEvent(e);return t.coalesce()}function RD(r,t){return typeof t=="string"&&!t.startsWith(Uo)&&!Yt(t)?{base:r,pattern:t}:t}function rh(r,t,e){let n=[];for(let i of t)n.push($a(RD(r,i),{ignoreCase:e}));return n}var nh=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 i=e.type,o=t.type;e.resource.fsPath!==t.resource.fsPath&&(t.type===2||t.type===1)?n=!0:i===1&&o===2?(this.mapPathToChange.delete(this.toKey(t)),this.coalesced.delete(e)):i===2&&o===1?e.type=0:i===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,i)=>n.resource.fsPath.length-i.resource.fsPath.length).filter(n=>e.some(i=>Fv(n.resource.fsPath,i,!ve))?!1:(e.push(n.resource.fsPath),!0)).concat(t)}};function KC(r,t){if(typeof t=="number")switch(r.type){case 1:return(t&4)===0;case 2:return(t&8)===0;case 0:return(t&2)===0}return!1}function jC(r){if(typeof r=="number"){let t=[];return r&4&&t.push("Added"),r&8&&t.push("Deleted"),r&2&&t.push("Updated"),t.length===0?"<all>":`[${t.join(", ")}]`}return"<none>"}var lp=class extends T{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 lr(this.getRefreshWatchersDelay(this.universalWatchRequests.length)));this.nonRecursiveWatchRequests=[];this.nonRecursiveWatchRequestDelayer=this._register(new lr(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 i=this.toWatchRequest(e,n),o=_p(this.universalWatchRequests,i);return this.refreshUniversalWatchers(),A(()=>{o(),this.refreshUniversalWatchers()})}toWatchRequest(e,n){let i={path:this.toWatchPath(e),excludes:n.excludes,includes:n.includes,recursive:n.recursive,filter:n.filter,correlationId:n.correlationId};if(zC(i)){let o=this.options?.watcher?.recursive?.usePolling;o===!0?i.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3:Array.isArray(o)&&o.includes(i.path)&&(i.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3)}return i}refreshUniversalWatchers(){this.universalWatchRequestDelayer.trigger(()=>this.doRefreshUniversalWatchers(),this.getRefreshWatchersDelay(this.universalWatchRequests.length)).catch(e=>Ue(e))}doRefreshUniversalWatchers(){return this.universalWatcher||(this.universalWatcher=this._register(this.createUniversalWatcher(e=>this._onDidChangeFile.fire(ih(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 i={path:this.toWatchPath(e),excludes:n.excludes,includes:n.includes,recursive:!1,filter:n.filter,correlationId:n.correlationId},o=_p(this.nonRecursiveWatchRequests,i);return this.refreshNonRecursiveWatchers(),A(()=>{o(),this.refreshNonRecursiveWatchers()})}refreshNonRecursiveWatchers(){this.nonRecursiveWatchRequestDelayer.trigger(()=>this.doRefreshNonRecursiveWatchers(),this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)).catch(e=>Ue(e))}doRefreshNonRecursiveWatchers(){return this.nonRecursiveWatcher||(this.nonRecursiveWatcher=this._register(this.createNonRecursiveWatcher(e=>this._onDidChangeFile.fire(ih(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 Qt(e.fsPath)}toWatchPath(e){let n=this.toFilePath(e);return hy(n)}};var cp=class extends sp{constructor(t,e,n){super(t,e,n),this.init()}createWatcher(t){let e=t.add(new tc(rt.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:i})=>this.onError(`terminated by itself with code ${n}, signal: ${i} (ETERM)`))),oo.toService(Ky(e.getChannel("watcher")))}};import{watchFile as ED,unwatchFile as PD}from"fs";var dp=class extends T{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 We);this.suspendedWatchRequestsWithPolling=new Set;this.updateWatchersDelayer=this._register(new lr(this.getUpdateWatchersDelay()));this.suspendedWatchRequestPollingInterval=5007;this.joinWatch=new fe;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 ap(e)}computeId(e){return this.isCorrelated(e)?e.correlationId:ht(e)}async watch(e){this.joinWatch.isSettled||this.joinWatch.complete(),this.joinWatch=new fe;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[i,o]of[...this.nonCorrelatedWatchRequests,...this.correlatedWatchRequests])this.suspendedWatchRequests.has(i)||n.push(o);return this.updateWatchersDelayer.trigger(()=>this.doWatch(n),e?this.getUpdateWatchersDelay():0).catch(i=>Ue(i))}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 z;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 i=this.recursiveWatcher?.subscribe(e.path,(o,s)=>{n.isDisposed||(o?this.monitorSuspendedWatchRequest(e,n):s?.type===1&&this.onMonitoredPathAdded(e))});return i?(n.add(i),!0):!1}doMonitorWithNodeJS(e,n){let i=!1,o=(s,a)=>{if(n.isDisposed)return;let l=this.isPathNotFound(s),c=this.isPathNotFound(a),u=i;i=l,!l&&(c||u)&&this.onMonitoredPathAdded(e)};this.trace(`starting fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{ED(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(A(()=>{this.trace(`stopping fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{PD(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:y.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 i=` >> normalized ${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`;this.traceWithCorrelation(i,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: ${jC(e.filter)}, correlationId: ${typeof e.correlationId=="number"?e.correlationId:"<none>"})`}async setVerboseLogging(e){this.verboseLogging=e}};import{watch as kD,promises as AD}from"fs";var up=class r extends T{constructor(e,n,i,o,s,a){super();this.request=e;this.recursiveWatcher=n;this.onDidFilesChange=i;this.onDidWatchFail=o;this.onLogMessage=s;this.verboseLogging=a;this.throttledFileChangesEmitter=this._register(new Qr({maxWorkChunkSize:100,throttleDelay:200,maxBufferedWork:1e4},e=>this.onDidFilesChange(e)));this.fileChangesAggregator=this._register(new Hl(e=>this.handleFileChanges(e),r.FILE_CHANGES_HANDLER_DELAY));this.cts=new Xe;this.realPath=new Ee(async()=>{let e=this.request.path;try{e=await xe.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=rh(this.request.path,this.request.excludes,l),this.includes=this.request.includes?rh(this.request.path,this.request.includes,l):void 0,this.filter=ap(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 AD.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 z;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 i=y.file(this.request.path),o=this.recursiveWatcher?.subscribe(this.request.path,async(s,a)=>{n.isDisposed||(s?await Ah(this.doWatch(e),n):a&&(typeof a.cId=="number"||typeof this.request.correlationId=="number")&&this.onFileChange({resource:i,type:a.type,cId:this.request.correlationId},!0))});return o?(n.add(o),!0):!1}async doWatchWithNodeJS(e,n){let i=await this.realPath.value;if(this.cts.token.isCancellationRequested)return;if(Ye&&Qn(i,"/Volumes/",!0)){this.error(`Refusing to watch ${i} for changes using fs.watch() for possibly being a network share where watching is unreliable and unstable.`);return}let o=new Xe(this.cts.token);n.add(A(()=>o.dispose(!0)));let s=new z;n.add(s);try{let a=y.file(this.request.path),l=_e(i),c=kD(i);s.add(A(()=>{c.removeAllListeners(),c.close()})),this.trace(`Started watching: '${i}'`);let u=new Set;if(e)try{for(let f of await xe.readdir(i))u.add(f)}catch(f){this.error(f)}if(o.token.isCancellationRequested)return;let d=new Map;s.add(A(()=>{for(let[,f]of d)f.dispose();d.clear()})),c.on("error",(f,m)=>{o.token.isCancellationRequested||(this.error(`Failed to watch ${i} 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 h="";if(m&&(h=m.toString(),Ye&&(h=na(h))),!(!h||f!=="change"&&f!=="rename"))if(e)if(f==="rename"){d.get(h)?.dispose();let v=setTimeout(async()=>{if(d.delete(h),jr(h,l,!ve)&&!await xe.exists(i)){this.onWatchedPathDeleted(a);return}if(o.token.isCancellationRequested)return;let S=await this.existsChildStrictCase(B(i,h));if(o.token.isCancellationRequested)return;let _;S?u.has(h)?_=0:(_=1,u.add(h)):(u.delete(h),_=2),this.onFileChange({resource:ee(a,h),type:_,cId:this.request.correlationId})},r.FILE_DELETE_HANDLER_DELAY);d.set(h,A(()=>clearTimeout(v)))}else{let v;u.has(h)?v=0:(v=1,u.add(h)),this.onFileChange({resource:ee(a,h),type:v,cId:this.request.correlationId})}else if(f==="rename"||!jr(h,l,!ve)){let v=setTimeout(async()=>{let S=await xe.exists(i);o.token.isCancellationRequested||(S?(this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0),s.add(await this.doWatch(!1))):this.onWatchedPathDeleted(a))},r.FILE_DELETE_HANDLER_DELAY);s.clear(),s.add(A(()=>clearTimeout(v)))}else this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0)})}catch(a){if(o.token.isCancellationRequested)return;this.error(`Failed to watch ${i} 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(i=>i(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (excluded) ${e.resource.fsPath}`):!n&&this.includes&&this.includes.length>0&&!this.includes.some(i=>i(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (not included) ${e.resource.fsPath}`):this.fileChangesAggregator.work(e))}handleFileChanges(e){let n=qC(e),i=[];for(let s of n){if(KC(s,this.filter)){this.verboseLogging&&this.traceWithCorrelation(` >> ignored (filtered) ${s.resource.fsPath}`);continue}i.push(s)}if(i.length===0)return;if(this.verboseLogging)for(let s of i)this.traceWithCorrelation(` >> normalized ${s.type===1?"[ADDED]":s.type===2?"[DELETED]":"[CHANGED]"} ${s.resource.fsPath}`);this.throttledFileChangesEmitter.work(i)?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: ${i[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: ${i.length}, most recent change: ${i[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 xe.exists(e);try{let n=_e(e);return(await xe.readdir(de(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 pp=class extends dp{constructor(e){super();this.recursiveWatcher=e;this.onDidError=Q.None;this._watchers=new Map;this.worker=this._register(new Rt)}get watchers(){return this._watchers.values()}async doWatch(e){e=this.removeDuplicateRequests(e);let n=[],i=new Set(Array.from(this.watchers));for(let o of e){let s=this._watchers.get(this.requestToWatcherKey(o));s&&Cg(s.request.excludes,o.excludes)&&Cg(s.request.includes,o.includes)?i.delete(s):n.push(o)}n.length&&this.trace(`Request to start watching: ${n.map(o=>this.requestToString(o)).join(",")}`),i.size&&this.trace(`Request to stop watching: ${Array.from(i).map(o=>this.requestToString(o.request)).join(",")}`),this.worker.clear();for(let o of i)this.stopWatching(o);this.createWatchWorker().work(n)}createWatchWorker(){return this.worker.value=new Qr({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 up(e,this.recursiveWatcher,o=>this._onDidChangeFile.fire(o),()=>this._onDidWatchFail.fire(e),o=>this._onDidLogMessage.fire(o),this.verboseLogging),i={request:e,instance:n};this._watchers.set(this.requestToWatcherKey(e),i)}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 i of e){let o=n.get(i.correlationId);o||(o=new Map,n.set(i.correlationId,o));let s=this.pathToWatcherKey(i.path);o.has(s)&&this.trace(`ignoring a request for watching who's path is already watched: ${this.requestToString(i)}`),o.set(s,i)}return Array.from(n.values()).flatMap(i=>Array.from(i.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 fp=class extends op{constructor(t,e,n){super(t,e,n),this.init()}createWatcher(t){return t.add(new pp(void 0))}};var gp=class r extends lp{constructor(){super(...arguments);this.onDidChangeCapabilities=Q.None;this.resourceLocks=new Fe(e=>Ve.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:i}=await _t.stat(this.toFilePath(e)),o;return(n.mode&128)===0&&(o=2),(n.mode&oh.S_IXUSR||n.mode&oh.S_IXGRP||n.mode&oh.S_IXOTH)&&(o=(o??0)|4),{type:this.toType(n,i),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 xe.realpath(n)}async readdir(e){try{let n=await xe.readdir(this.toFilePath(e),{withFileTypes:!0}),i=[];return await Promise.all(n.map(async o=>{try{let s;o.isSymbolicLink()?s=(await this.stat(ee(e,o.name))).type:s=this.toType(o),i.push([o.name,s])}catch(s){this.logService.trace(s)}})),i}catch(n){throw this.toFileSystemProviderError(n)}}toType(e,n){let i;return n?.dangling?i=0:e.isFile()?i=1:e.isDirectory()?i=2:i=0,n&&(i|=64),i}async createResourceLock(e){let n=this.toFilePath(e);this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - request to acquire resource lock (${n})`);let i;for(;i=this.resourceLocks.get(e);)this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - waiting for resource lock to be released (${n})`),await i.wait();let o=new Bl;return this.resourceLocks.set(e,o),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${n})`),A(()=>{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 i;try{n?.atomic&&(this.traceLock(`[Disk FileSystemProvider]: atomic read operation started (${this.toFilePath(e)})`),i=await this.createResourceLock(e));let o=this.toFilePath(e);return await Dr.readFile(o)}catch(o){throw this.toFileSystemProviderError(o)}finally{i?.dispose()}}traceLock(e){r.TRACE_LOG_RESOURCE_LOCKS&&this.logService.trace(e)}readFileStream(e,n,i){let o=Zn(s=>k.concat(s.map(a=>k.wrap(a))).buffer);return ip(this,e,o,s=>s.buffer,{...n,bufferSize:256*1024},i),o}async writeFile(e,n,i){return i?.atomic!==!1&&i?.atomic?.postfix&&await this.canWriteFileAtomic(e)?this.doWriteFileAtomic(e,ee(vn(e),`${pe(e)}${i.atomic.postfix}`),n,i):this.doWriteFile(e,n,i)}async canWriteFileAtomic(e){try{let n=this.toFilePath(e),{symbolicLink:i}=await _t.stat(n);if(i)return!1}catch{}return!0}async doWriteFileAtomic(e,n,i,o){let s=new z;try{s.add(await this.createResourceLock(e)),s.add(await this.createResourceLock(n)),await this.doWriteFile(n,i,{...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,i,o){let s;try{let a=this.toFilePath(e);if(!i.create||!i.overwrite){if(await xe.exists(a)){if(!i.overwrite)throw he(g(2402,null),"EntryExists")}else if(!i.create)throw he(g(2405,null),"EntryNotFound")}s=await this.open(e,{create:!0,append:i.append,unlock:i.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){r.canFlush=e}async open(e,n,i){let o=this.toFilePath(e),s;ri(n)&&!i&&(s=await this.createResourceLock(e));let a;try{if(ri(n)&&n.unlock)try{let{stat:l}=await _t.stat(o);l.mode&128||await Dr.chmod(o,l.mode|128)}catch(l){l.code!=="ENOENT"&&this.logService.trace(l)}if(K&&ri(n)&&!n.append)try{a=await xe.open(o,"r+"),await xe.ftruncate(a,0)}catch(l){if(l.code!=="ENOENT"&&this.logService.trace(l),typeof a=="number"){try{await xe.close(a)}catch(c){this.logService.trace(c)}a=void 0}}typeof a!="number"&&(a=await xe.open(o,ri(n)?n.append?"a":"w":"r"))}catch(l){throw s?.dispose(),ri(n)?await this.toFileSystemProviderWriteError(e,l):this.toFileSystemProviderError(l)}if(this.mapHandleToPos.set(a,0),ri(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)&&r.canFlush)try{await xe.fdatasync(e)}catch(i){r.configureFlushOnWrite(!1),this.logService.error(i)}return await xe.close(e)}catch(i){throw this.toFileSystemProviderError(i)}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,i,o,s){let a=this.normalizePos(e,n),l=null;try{l=(await xe.read(e,i,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,i){let o=this.mapHandleToPos.get(e);typeof o=="number"&&(typeof n=="number"||(typeof i=="number"?this.mapHandleToPos.set(e,o+i):this.mapHandleToPos.delete(e)))}async write(e,n,i,o,s){return Ly(()=>this.doWrite(e,n,i,o,s),100,3)}async doWrite(e,n,i,o,s){let a=this.normalizePos(e,n),l=null;try{l=(await xe.write(e,i,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 Dr.mkdir(this.toFilePath(e))}catch(n){throw this.toFileSystemProviderError(n)}}async delete(e,n){try{let i=this.toFilePath(e);if(n.recursive){let o;n?.atomic!==!1&&n.atomic.postfix&&(o=B(de(i),`${_e(i)}${n.atomic.postfix}`)),await xe.rm(i,1,o)}else try{await Dr.unlink(i)}catch(o){if(o.code==="EPERM"||o.code==="EISDIR"){let s=!1;try{let{stat:a,symbolicLink:l}=await _t.stat(i);s=a.isDirectory()&&!l}catch{}if(s)await Dr.rmdir(i);else throw o}else throw o}}catch(i){throw this.toFileSystemProviderError(i)}}async rename(e,n,i){let o=this.toFilePath(e),s=this.toFilePath(n);if(o!==s)try{await this.validateMoveCopy(e,n,"move",i.overwrite),await xe.rename(o,s)}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(g(2406,null,_e(o),_e(de(s)),a.toString()))),this.toFileSystemProviderError(a)}}async copy(e,n,i){let o=this.toFilePath(e),s=this.toFilePath(n);if(o!==s)try{await this.validateMoveCopy(e,n,"copy",i.overwrite),await xe.copy(o,s,{preserveSymlinks:!0})}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(g(2400,null,_e(o),_e(de(s)),a.toString()))),this.toFileSystemProviderError(a)}}async validateMoveCopy(e,n,i,o){let s=this.toFilePath(e),a=this.toFilePath(n),l=!1;if(this.capabilities&1024||(l=jr(s,a,!0)),l){if(i==="copy")throw he(g(2401,null),"EntryExists");if(i==="move")return}let u=await this.statIgnoreError(e);if(!u)throw he(g(2404,null),"EntryNotFound");let d=await this.statIgnoreError(n);if(d){if(!o)throw he(g(2403,null),"EntryExists");(u.type&1)!==0&&(d.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,i){let o=this.toFilePath(e),s=this.toFilePath(n),a=!!(this.capabilities&1024);if(jr(o,s,!a))return;let l=new z;try{l.add(await this.createResourceLock(e)),l.add(await this.createResourceLock(n)),i&&await Dr.mkdir(de(s),{recursive:!0}),await Dr.copyFile(o,s)}catch(c){if(c.code==="ENOENT"&&!i)return this.doCloneFile(e,n,!0);throw this.toFileSystemProviderError(c)}finally{l.dispose()}}createUniversalWatcher(e,n,i){return new cp(o=>e(o),o=>n(o),i)}createNonRecursiveWatcher(e,n,i){return new fp(o=>e(o),o=>n(o),i)}toFileSystemProviderError(e){if(e instanceof go)return e;let n=e,i;switch(e.code){case"ENOENT":i="EntryNotFound";break;case"EISDIR":i="EntryIsADirectory";break;case"ENOTDIR":i="EntryNotADirectory";break;case"EEXIST":i="EntryExists";break;case"EPERM":case"EACCES":i="NoPermissions";break;case"ERR_UNC_HOST_NOT_ALLOWED":n=`${e.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`,i="Unknown";break;default:i="Unknown"}return he(n,i)}async toFileSystemProviderWriteError(e,n){let i=this.toFileSystemProviderError(n);if(e&&i.code==="NoPermissions")try{let{stat:o}=await _t.stat(this.toFilePath(e));o.mode&128||(i=he(n,"EntryWriteLocked"))}catch(o){this.logService.trace(o)}return i}};import*as QC from"fs";var GC=[{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(`;
`)},{version:5,sql:"ALTER TABLE turns ADD COLUMN checkpoint_ref TEXT"}];function gn(r,t){return new Promise((e,n)=>{r.exec(t,i=>i?n(i):e())})}function wt(r,t,e){return new Promise((n,i)=>{r.run(t,e,function(o){if(o)return i(o);n({changes:this.changes,lastID:this.lastID})})})}function Qi(r,t,e){return new Promise((n,i)=>{r.get(t,e,(o,s)=>{if(o)return i(o);n(s)})})}function As(r,t,e){return new Promise((n,i)=>{r.all(t,e,(o,s)=>{if(o)return i(o);n(s)})})}function sh(r){return new Promise((t,e)=>{r.close(n=>n?e(n):t())})}function DD(r){return new Promise((t,e)=>{import("@vscode/sqlite3").then(n=>{let i=new n.default.Database(r,o=>{if(o)return e(o);t(i)})},e)})}async function OD(r,t){await gn(r,"PRAGMA foreign_keys = ON");let n=(await Qi(r,"PRAGMA user_version",[]))?.user_version??0,i=t.filter(o=>o.version>n).sort((o,s)=>o.version-s.version);if(i.length!==0){await gn(r,"BEGIN TRANSACTION");try{for(let o of i)await gn(r,o.sql),await gn(r,`PRAGMA user_version = ${o.version}`);await gn(r,"COMMIT")}catch(o){throw await gn(r,"ROLLBACK"),o}}}var mp=class r{constructor(t,e=GC){this._path=t;this._migrations=e;this._fileEditSequencer=new Ze;this._metadataSequencer=new Ze;this._pendingWrites=new Set}static async open(t,e=GC){let n=new r(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 QC.promises.mkdir(de(this._path),{recursive:!0});let t=await DD(this._path);try{await OD(t,this._migrations)}catch(e){throw await sh(t),this._dbPromise=void 0,e}if(this._closed)throw await sh(t),new Error("SessionDatabase has been disposed");return t})()),this._dbPromise)}async getAllTables(){let t=await this._ensureDb();return(await As(t,"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name",[])).map(n=>n.name)}createTurn(t){return this._track(async()=>{let e=await this._ensureDb();await wt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t])})}deleteTurn(t){return this._track(async()=>{let e=await this._ensureDb();await wt(e,"DELETE FROM turns WHERE id = ?",[t])})}setTurnEventId(t,e){return this._track(async()=>{let n=await this._ensureDb();await wt(n,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t]),await wt(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 Qi(e,"SELECT event_id FROM turns WHERE id = ?",[t]))?.event_id??void 0}async getNextTurnEventId(t){let e=await this._ensureDb();return(await Qi(e,`SELECT event_id FROM turns
				WHERE rowid > (
					SELECT rowid FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1
				)
				ORDER BY rowid LIMIT 1`,[t]))?.event_id??void 0}async getFirstTurnEventId(){let t=await this._ensureDb();return(await Qi(t,"SELECT event_id FROM turns ORDER BY rowid LIMIT 1",[]))?.event_id??void 0}setTurnCheckpointRef(t,e){return this._track(async()=>{let n=await this._ensureDb();await wt(n,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t]),await wt(n,"UPDATE turns SET checkpoint_ref = ? WHERE id = ?",[e,t])})}async getTurnCheckpointRef(t){let e=await this._ensureDb();return(await Qi(e,"SELECT checkpoint_ref FROM turns WHERE id = ?",[t]))?.checkpoint_ref??void 0}async getPreviousCheckpointRef(t){let e=await this._ensureDb();return(await Qi(e,`SELECT checkpoint_ref FROM turns
				WHERE rowid < (SELECT rowid FROM turns WHERE id = ?)
					AND checkpoint_ref IS NOT NULL
				ORDER BY rowid DESC LIMIT 1`,[t]))?.checkpoint_ref??void 0}async getAllCheckpointRefs(){let t=await this._ensureDb();return(await As(t,"SELECT checkpoint_ref FROM turns WHERE checkpoint_ref IS NOT NULL ORDER BY rowid",[])).map(n=>n.checkpoint_ref)}truncateFromTurn(t){return this._track(async()=>{let e=await this._ensureDb();await wt(e,"DELETE FROM turns WHERE rowid >= (SELECT rowid FROM turns WHERE id = ?)",[t])})}deleteTurnsAfter(t){return this._track(async()=>{let e=await this._ensureDb();await wt(e,"DELETE FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?)",[t])})}deleteAllTurns(){return this._track(async()=>{let t=await this._ensureDb();await gn(t,"DELETE FROM turns")})}storeFileEdit(t){return this._track(()=>this._fileEditSequencer.queue(t.filePath,async()=>{let e=await this._ensureDb();await wt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t.turnId]),await wt(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 As(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 As(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 As(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(i=>({turnId:i.turn_id,toolCallId:i.tool_call_id,filePath:i.file_path,kind:i.edit_type??"edit",originalPath:i.original_path??void 0,addedLines:i.added_lines??void 0,removedLines:i.removed_lines??void 0}))}async readFileEditContent(t,e){return this._fileEditSequencer.queue(e,async()=>{let n=await this._ensureDb(),i=await Qi(n,`SELECT before_content, after_content
					FROM file_edits
					WHERE tool_call_id = ? AND file_path = ?`,[t,e]);if(i)return{beforeContent:i.before_content?JC(i.before_content):void 0,afterContent:i.after_content?JC(i.after_content):void 0}})}async getMetadata(t){let e=await this._ensureDb();return(await Qi(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 i=await this._ensureDb(),o=e.map(()=>"?").join(","),s=await As(i,`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}setMetadata(t,e){return this._track(()=>this._metadataSequencer.queue(t,async()=>{let n=await this._ensureDb();await wt(n,"INSERT OR REPLACE INTO session_metadata (key, value) VALUES (?, ?)",[t,e])}))}remapTurnIds(t){return this._track(async()=>{let e=await this._ensureDb();await gn(e,"PRAGMA defer_foreign_keys = ON"),await gn(e,"BEGIN TRANSACTION");try{let n=[...t.keys()];if(n.length>0){let i=n.map(()=>"?").join(",");await wt(e,`DELETE FROM turns WHERE id NOT IN (${i})`,n)}for(let[i,o]of t)await wt(e,"UPDATE turns SET id = ? WHERE id = ?",[o,i]),await wt(e,"UPDATE file_edits SET turn_id = ? WHERE turn_id = ?",[o,i]);await gn(e,"COMMIT")}catch(n){throw await gn(e,"ROLLBACK"),n}})}async whenIdle(){for(;this._pendingWrites.size>0;)await Promise.allSettled([...this._pendingWrites])}async vacuumInto(t){let e=await this._ensureDb();await wt(e,"VACUUM INTO ?",[t])}_track(t){let e=t();this._pendingWrites.add(e);let n=()=>{this._pendingWrites.delete(e)};return e.then(n,n),e}async close(){await(this._closed??=this._dbPromise?.then(t=>sh(t)).catch(()=>{})||!0)}dispose(){this.close()}};function JC(r){return r instanceof Buffer?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r instanceof Uint8Array?r:typeof r=="string"?new TextEncoder().encode(r):new Uint8Array(0)}var ah=class extends Wr{constructor(e,n){super();this._getDbPath=e;this._logService=n;this.liveDatabases=new Set}createReferencedObject(e){let n=this._getDbPath(e);this._logService.trace(`[SessionDataService] Opening database: ${n}`);let i=new mp(n);return this.liveDatabases.add(i),i}destroyReferencedObject(e,n){this.liveDatabases.delete(n),n.dispose()}},Ds=class{constructor(t,e,n,i){this._fileService=e;this._logService=n;this._onWillDeleteSessionData=new x;this._basePath=y.joinPath(t,"agentSessionData"),this._databases=new ah(i??(o=>y.joinPath(this._basePath,o,Ca).fsPath),this._logService)}get onWillDeleteSessionData(){return this._onWillDeleteSessionData.event}getSessionDataDir(t){return this.getSessionDataDirById(H.id(t))}getSessionDataDirById(t){let e=t.replace(/[^a-zA-Z0-9_.-]/g,"-");return y.joinPath(this._basePath,e)}_sanitizedSessionKey(t){return H.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=y.joinPath(this._basePath,e,Ca);if(await this._fileService.exists(n))return this._databases.acquire(e)}async deleteSessionData(t){let e=this.getSessionDataDir(t),n=[];try{this._onWillDeleteSessionData.fire({session:t,waitUntil:i=>{n.push(i)}})}catch(i){this._logService.warn(`[SessionDataService] onWillDeleteSessionData listener threw synchronously: ${e.toString()}`,i)}if(n.length>0){let i=await Promise.allSettled(n);for(let o of i)o.status==="rejected"&&this._logService.warn(`[SessionDataService] onWillDeleteSessionData waitUntil rejected: ${e.toString()}`,o.reason)}try{await this._fileService.exists(e)&&(await this._fileService.del(e,{recursive:!0}),this._logService.trace(`[SessionDataService] Deleted session data: ${e.toString()}`))}catch(i){this._logService.warn(`[SessionDataService] Failed to delete session data: ${e.toString()}`,i)}}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 i=[];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}`),i.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(i)}catch(e){this._logService.warn("[SessionDataService] Failed to run orphan cleanup",e)}}async whenIdle(){for(;;){let t=[...this._databases.liveDatabases];if(t.length===0||(await Promise.all(t.map(n=>n.whenIdle())),[...this._databases.liveDatabases].filter(n=>!t.includes(n)).length===0))return}}};Ds=w([C(1,Se),C(2,L)],Ds);var hp=class r{static async checkSandboxDependenciesWith(t,e=ve){if(!e)return;let[n,i]=await Promise.all([t("bwrap"),t("socat")]);return{bubblewrapInstalled:!!n,socatInstalled:!!i}}checkSandboxDependencies(){return r.checkSandboxDependenciesWith(Zl)}async getWindowsMxcFilesystemPolicy(){if(!K)return;let{getAvailableToolsPolicy:t,getUserProfilePolicy:e,getTemporaryFilesPolicy:n}=await import("@microsoft/mxc-sdk"),i=t(process.env,{containerType:"processcontainer"}),o=e(),s=n(process.env),a=await this._getPSHome();return{readonlyPaths:[...new Set([...i.readonlyPaths,...o.readonlyPaths,...s.readonlyPaths,...a?[a]:[]])],readwritePaths:[...new Set([...i.readwritePaths,...o.readwritePaths,...s.readwritePaths])]}}async getWindowsMxcEnvironment(){if(!K)return;let t=[];for(let s of["SystemRoot","PATH","ComSpec","PATHEXT","PSModulePath"]){let a=ei(process.env,s);typeof a=="string"&&a&&t.push(`${s}=${a}`)}let e=ei(process.env,"USERPROFILE");typeof e=="string"&&e&&t.push(`USERPROFILE=${e}`);let n=ei(process.env,"APPDATA");typeof n=="string"&&n&&t.push(`APPDATA=${n}`);let i=this._getLocalAppData();typeof i=="string"&&i&&t.push(`LOCALAPPDATA=${i}`);let o=await this._getPSHome();return o&&t.push(`PSHOME=${o}`),t}async buildWindowsMxcSandboxPayload(t,e,n,i,o="process"){if(!K)return;let{buildSandboxPayload:s}=await import("@microsoft/mxc-sdk");return s(t,e,n,i,o)}async _getPSHome(){let t=ei(process.env,"PSHOME");if(typeof t=="string"&&t)return t;let e=await Zl("pwsh")??await Zl("powershell");return e?ae.dirname(e):void 0}_getLocalAppData(){let t=ei(process.env,"LOCALAPPDATA");return typeof t=="string"&&t?t:void 0}};var yp=class extends T{constructor(){super(...arguments);this.capabilities=1034;this._onDidChangeCapabilities=this._register(new x);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._onDidChangeFile=this._register(new x);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new x);this.onDidWatchError=this._onDidWatchError.event;this._authorityToConnection=new Map}registerAuthority(e,n){return this._authorityToConnection.set(e,n),A(()=>{this._authorityToConnection.get(e)===n&&this._authorityToConnection.delete(e)})}watch(e,n){let i=this._authorityToConnection.get(e.authority);if(!i?.watchResource)return T.None;let o=new Rt,s={channel:Ne,uri:this._decodeUri(e).toString(),recursive:n.recursive,...n.excludes.length>0?{excludes:{items:[...n.excludes]}}:{},...n.includes&&n.includes.length>0?{includes:{items:n.includes.map(l=>typeof l=="string"?l:l.pattern)}}:{}},a=!1;return i.watchResource(s).then(l=>{if(a){l.dispose();return}let c=l.onDidChange(u=>this._onDidChangeFile.fire(u.map(d=>({resource:this._encodeUri(d.resource,e.authority),type:d.type}))));o.value=A(()=>{c.dispose(),l.dispose()})},l=>{this._onDidWatchError.fire(l instanceof Error?l.message:String(l))}),A(()=>{a=!0,o.dispose()})}async stat(e){let n=e.path;if(n==="/"||n==="")return{type:2,mtime:0,ctime:0,size:0,permissions:1};let i=this._decodeUri(e);if(i.scheme==="session-db"||i.scheme==="git-blob")return{type:1,mtime:0,ctime:0,size:0,permissions:1};if(i.path==="/"||i.path==="")return{type:2,mtime:0,ctime:0,size:0,permissions:1};let o=this._getConnection(e.authority);try{let s=await o.resourceResolve({channel:Ne,uri:i.toString()});return{type:s.type==="directory"?2:s.type==="symlink"?64:1,mtime:s.mtime?Date.parse(s.mtime):0,ctime:s.ctime?Date.parse(s.ctime):0,size:s.size??0,permissions:1}}catch(s){throw this._mapError(s,"EntryNotFound")}}async readdir(e){return(await this._listDirectory(e.authority,e)).map(i=>[i.name,i.type==="directory"?2:1])}async readFile(e){let n=this._getConnection(e.authority);try{let i=this._decodeUri(e),o=await n.resourceRead(i);return o.encoding==="base64"?bn(o.data).buffer:k.fromString(o.data).buffer}catch(i){throw this._mapError(i,"EntryNotFound")}}async writeFile(e,n,i){let o=this._getConnection(e.authority);try{let s=this._decodeUri(e);await o.resourceWrite({channel:Ne,uri:s.toString(),data:k.wrap(n).toString(),encoding:"utf-8"})}catch(s){throw this._mapError(s,"NoPermissions")}}async mkdir(e){let n=this._getConnection(e.authority);try{let i=this._decodeUri(e);await n.resourceMkdir({channel:Ne,uri:i.toString()})}catch(i){throw this._mapError(i,"NoPermissions")}}async delete(e,n){let i=this._getConnection(e.authority);try{let o=this._decodeUri(e);await i.resourceDelete({channel:Ne,uri:o.toString(),recursive:n.recursive})}catch(o){throw this._mapError(o,"NoPermissions")}}async rename(e,n,i){let o=this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(n);await o.resourceMove({channel:Ne,source:s.toString(),destination:a.toString(),failIfExists:!i.overwrite})}catch(s){throw this._mapError(s,"NoPermissions")}}async copy(e,n,i){let o=this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(n);await o.resourceCopy({channel:Ne,source:s.toString(),destination:a.toString(),failIfExists:!i.overwrite})}catch(s){throw this._mapError(s,"NoPermissions")}}async requestResourceAccess(e,n){let i=this._getConnection(e.authority);if(!i.resourceRequest)throw he(`Connection for ${e.authority} does not support resourceRequest`,"Unavailable");let o=this._decodeUri(e);try{await i.resourceRequest({channel:Ne,uri:o.toString(),read:n.read,write:n.write})}catch(s){throw this._mapError(s,"NoPermissions")}}_getConnection(e){let n=this._authorityToConnection.get(e);if(!n)throw he(`No connection for authority: ${e}`,"Unavailable");return n}_mapError(e,n){return e instanceof N&&e.code===ge.PermissionDenied?he(e.message,"NoPermissions"):he(e instanceof Error?e.message:String(e),n)}async _listDirectory(e,n){let i=this._getConnection(e);try{let o=this._decodeUri(n);return(await i.resourceList(o)).entries}catch(o){throw this._mapError(o,"Unavailable")}}};var vp=class extends yp{_decodeUri(t){return kI(t)}_encodeUri(t,e){return Vi(t,e)}};var YC="agentHostClientResource";function XC(r){return{resourceList:t=>r.call("resourceList",{uri:t.toString()}),resourceRead:t=>r.call("resourceRead",{uri:t.toString()}),resourceWrite:t=>r.call("resourceWrite",{...t,uri:t.uri.toString()}),resourceCopy:t=>r.call("resourceCopy",{...t,source:t.source.toString(),destination:t.destination.toString()}),resourceDelete:t=>r.call("resourceDelete",{...t,uri:t.uri.toString()}),resourceMove:t=>r.call("resourceMove",{...t,source:t.source.toString(),destination:t.destination.toString()}),resourceResolve:t=>r.call("resourceResolve",{...t,uri:t.uri.toString()}),resourceMkdir:t=>r.call("resourceMkdir",{...t,uri:t.uri.toString()})}}var LD=20,Os=class{constructor(t,e,n,i=LD){this._fileService=e;this._logService=n;this._sequencer=new Ze;this._cachedNonces=new Map;this._lruOrder=[];this._cacheLoaded=!1;this._basePath=y.joinPath(t,"agentPlugins"),this._cachePath=y.joinPath(this._basePath,"cache.json"),this._maxPlugins=i}get basePath(){return this._basePath}async syncCustomizations(t,e,n){return await this._ensureCacheLoaded(),await Promise.all(e.map(o=>this._sequencer.queue(o.uri,async()=>{try{let s=await this._syncPlugin(t,o),a={...o,load:{kind:"loaded"}};return n?.(a),{customization:a,pluginDir:s}}catch(s){let a=s instanceof Error?s.message:String(s);this._logService.error(`[AgentPluginManager] Failed to sync plugin ${o.uri}: ${a}`);let l={...o,load:{kind:"error",message:a}};return n?.(l),{customization:l}}})))}async _syncPlugin(t,e){let n=Vi(y.parse(e.uri),t),i=this._keyForUri(e.uri),o=y.joinPath(this._basePath,i);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=y.joinPath(this._basePath,e);this._logService.info(`[AgentPluginManager] Evicting plugin: ${t}`);try{await this._fileService.del(n,{recursive:!0})}catch(i){this._logService.warn(`[AgentPluginManager] Failed to evict plugin: ${t}`,i)}}}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,k.fromString(JSON.stringify(t)))}catch(t){this._logService.warn("[AgentPluginManager] Failed to persist cache to disk",t)}}};Os=w([C(1,Se),C(2,L)],Os);MD().catch(r=>{console.error(r),process.exit(1)});async function MD(){let r;nc(process)?r=new ra:r=new ec("agentHost");let t=new z,e={_serviceBrand:void 0,...Ut},n=new Xu(Xm(process.argv,FC),e),i=new tp(Qv(n),n.logsHome);r.registerChannel("agentHostLogger",new np(i,()=>VC));let o=i.createLogger("agenthost",{name:g(1899,null)}),s=t.add(new Gu),a=t.add(new Ju(s)),l=new Zu(o,[a]);!n.isBuilt&&Gv&&t.add(Jv(l)),l.info("Agent Host process started successfully");let c=t.add(new Ji(l));t.add(c.registerProvider(oe.file,t.add(new gp(l)))),t.add(e_(c));let u=new Ds(y.file(n.userDataPath),c,l),d=ee(n.appSettingsHome,"globalStorage","agent-host-config.json"),f=await sI({environmentService:n,productService:e,fileService:c,loggerService:i,logService:l,disposables:t}),m,h;try{let P=new Ai;P.set(Ui,n),P.set(L,l),P.set(Se,c),P.set(vt,u),P.set(Lt,e),P.set(Li,f),h=new yo(P);let j=t.add(h.createInstance(An));P.set(Jo,j),P.set(vu,h.createInstance(yu)),P.set(hu,new hp);let E=h.createInstance(Oo);P.set(Nt,E);let M=t.add(h.createInstance(Mo));P.set(En,M);let O=h.createInstance(ls,void 0);P.set(cs,O);let G=t.add(h.createInstance(Cs));P.set(Fu,G);let te=h.createInstance(us);P.set(ps,te);let ye=t.add(h.createInstance(xs));P.set(nu,ye),m=new Zd(l,c,u,e,E,M,d,f,j);let Ls=new Os(y.file(n.userDataPath),c,l);P.set(Dn,Ls);let $n=t.add(new Fi(l));P.set(jc,$n),P.set(Po,m.terminalManager),P.set(Je,m.configurationService),P.set(Ud,m.completionsService),m.registerProvider(h.createInstance(me)),process.env[oa]&&m.registerProvider(h.createInstance(Ts))}catch(P){throw l.error("Failed to create AgentService",P),P}let v=oo.fromService(m,t);r.registerChannel("agentHost",v);let S=t.add(new vp);if(t.add(c.registerProvider(im,S)),r instanceof ra){let P=new Map;t.add(r.onDidAddConnection(j=>{let E=j.ctx;if(typeof E!="string"||!E)return;let M=r.getChannel(YC,G=>G.ctx===E),O=XC(M);P.set(j,S.registerAuthority(E,O))})),t.add(r.onDidRemoveConnection(j=>{let E=P.get(j);E&&(E.dispose(),P.delete(j))}))}let _=t.add(new x),b,I={onDidChangeConnectionCount:_.event,async startWebSocketServer(){if(b)return b;let P=K?`\\\\.\\pipe\\vscode-agent-host-${q().replace(/-/g,"")}`:B(hl.tmpdir(),`vscode-agent-host-${q().replace(/-/g,"")}.sock`),j=t.add(await gl.create({socketPath:P},l,{instantiationService:h,logsHome:n.logsHome})),E=t.add(new Ar(m,m.stateManager,j,{defaultDirectory:y.file(hl.homedir()).toString(),completionTriggerCharacters:m.completionTriggerCharacters,otlpLogEmitter:s},S,l));return t.add(E.onDidChangeConnectionCount(M=>_.fire(M))),l.info(`[AgentHost] Dynamic WebSocket server listening on ${P}`),b={socketPath:P},b},async getInspectInfo(P){let j=ml.url();if(!j&&P){try{ml.open(0,"127.0.0.1",!1)}catch(E){l.error("[AgentHost] Failed to open inspector",E);return}j=ml.url()}if(j)try{let E=new URL(j);if(E.protocol!=="ws:"){l.warn(`[AgentHost] Unexpected inspector URL: ${j}`);return}let M=Number(E.port),O=E.pathname.replace(/^\/+/,"");if(!Number.isInteger(M)||!O){l.warn(`[AgentHost] Unexpected inspector URL: ${j}`);return}let G=E.hostname==="0.0.0.0"?"127.0.0.1":E.hostname==="::"?"::1":E.hostname,te=G.includes(":")?`[${G}]`:G;return{host:G,port:M,devtoolsUrl:`devtools://devtools/bundled/js_app.html?v8only=true&ws=${te}:${E.port}/${O}`}}catch{l.warn(`[AgentHost] Unexpected inspector URL: ${j}`);return}}},R=oo.fromService(I,t);r.registerChannel("agentHostConnectionTracker",R),ND(m,S,h,n.logsHome,l,s,t,P=>_.fire(P)).catch(P=>{l.error("Failed to start WebSocket server",P)}),process.once("exit",()=>{m.dispose(),l.dispose(),t.dispose()})}async function ND(r,t,e,n,i,o,s,a){let l=process.env.VSCODE_AGENT_HOST_PORT,c=process.env.VSCODE_AGENT_HOST_SOCKET_PATH;if(!l&&!c)return;let u=process.env.VSCODE_AGENT_HOST_CONNECTION_TOKEN,d=process.env.VSCODE_AGENT_HOST_HOST||"localhost",f=s.add(await gl.create(c?{socketPath:c,connectionTokenValidate:u?v=>v===u:void 0}:{port:parseInt(l,10),host:d,connectionTokenValidate:u?v=>v===u:void 0},i,{instantiationService:e,logsHome:n})),m=s.add(new Ar(r,r.stateManager,f,{defaultDirectory:y.file(hl.homedir()).toString(),completionTriggerCharacters:r.completionTriggerCharacters,otlpLogEmitter:o},t,i));s.add(m.onDidChangeConnectionCount(a)),await f.whenListening;let h=c??`${d}:${f.boundPort??l}`;i.info(`[AgentHost] WebSocket server listening on ${h}`),console.log(`Agent host server listening on ${h}`)}
