/*!--------------------------------------------------------
 * 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 Ew=Object.defineProperty;var Pw=Object.getOwnPropertyDescriptor;var x=(i,t,e,n)=>{for(var r=n>1?void 0:n?Pw(t,e):t,o=i.length-1,s;o>=0;o--)(s=i[o])&&(r=(n?s(t,e,r):s(r))||r);return n&&r&&Ew(t,e,r),r},C=(i,t)=>(e,n)=>t(e,n,i);function Aw(i,t,e=0,n=i.length){let r=e,o=n;for(;r<o;){let s=Math.floor((r+o)/2);t(i[s])?r=s+1:o=s}return r-1}var sv=class i{constructor(t){this._array=t;this._findLastMonotonousLastIdx=0}static{this.assertInvariants=!1}findLastMonotonous(t){if(i.assertInvariants){if(this._prevFindLastPredicate){for(let n of this._array)if(this._prevFindLastPredicate(n)&&!t(n))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=t}let e=Aw(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=e+1,e===-1?void 0:this._array[e]}};var zf=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(t){setTimeout(()=>{throw t.stack?Dn.isErrorNoTelemetry(t)?new Dn(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)}},jf=new zf;function Fr(i){jf.onUnexpectedError(i)}function ze(i){Zn(i)||jf.onUnexpectedError(i)}function lv(i){Zn(i)||jf.onUnexpectedExternalError(i)}var dd="Canceled";function Zn(i){return i instanceof K?!0:i instanceof Error&&i.name===dd&&i.message===dd}var K=class extends Error{constructor(){super(dd),this.name=this.message}},av=class i extends Error{static{this._name="PendingMigrationError"}static is(t){return t instanceof i||t instanceof Error&&t.name===i._name}constructor(t){super(t),this.name=i._name}};function cd(){let i=new Error(dd);return i.name=i.message,i}function Kf(i){return i?new Error(`Illegal argument: ${i}`):new Error("Illegal argument")}function ud(i){return i?new Error(`Illegal state: ${i}`):new Error("Illegal state")}function Ei(i){return i?i.message?i.message:i.stack?i.stack.split(`
`)[0]:String(i):"Error"}var Dn=class i extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof i)return t;let e=new i;return e.message=t.message,e.stack=t.stack,e}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},De=class i extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,i.prototype)}};function Xt(i,t,e=(n,r)=>n===r){if(i===t)return!0;if(!i||!t||i.length!==t.length)return!1;for(let n=0,r=i.length;n<r;n++)if(!e(i[n],t[n]))return!1;return!0}function Wr(i){return i.filter(t=>!!t)}function er(i,t=e=>e){let e=new Set;return i.filter(n=>{let r=t(n);return e.has(r)?!1:(e.add(r),!0)})}function Gf(i,t){return i.push(t),()=>kw(i,t)}function kw(i,t){let e=i.indexOf(t);if(e>-1)return i.splice(e,1),t}function Jf(i,t){let e;if(typeof t=="number"){let n=t;e=()=>{let r=Math.sin(n++)*179426549;return r-Math.floor(r)}}else e=Math.random;for(let n=i.length-1;n>0;n-=1){let r=Math.floor(e()*(n+1)),o=i[n];i[n]=i[r],i[r]=o}}function uv(i){return i[Math.floor(Math.random()*i.length)]}var pv;(a=>{function i(l){return l<0}a.isLessThan=i;function t(l){return l<=0}a.isLessThanOrEqual=t;function e(l){return l>0}a.isGreaterThan=e;function n(l){return l===0}a.isNeitherLessOrGreaterThan=n,a.greaterThan=1,a.lessThan=-1,a.neitherLessOrGreaterThan=0})(pv||={});function fv(i,t){return(e,n)=>t(i(e),i(n))}var gv=(i,t)=>i-t;var cv=class i{constructor(t){this.iterate=t}static{this.empty=new i(t=>{})}forEach(t){this.iterate(e=>(t(e),!0))}toArray(){let t=[];return this.iterate(e=>(t.push(e),!0)),t}filter(t){return new i(e=>this.iterate(n=>t(n)?e(n):!0))}map(t){return new i(e=>this.iterate(n=>e(t(n))))}some(t){let e=!1;return this.iterate(n=>(e=t(n),!e)),e}findFirst(t){let e;return this.iterate(n=>t(n)?(e=n,!1):!0),e}findLast(t){let e;return this.iterate(n=>(t(n)&&(e=n),!0)),e}findLastMaxBy(t){let e,n=!0;return this.iterate(r=>((n||pv.isGreaterThan(t(r,e)))&&(n=!1,e=r),!0)),e}};function vv(i,t){let e=Object.create(null);for(let n of i){let r=t(n),o=e[r];o||(o=e[r]=[]),o.push(n)}return e}var hv,yv,mv=class{constructor(t,e){this.toKey=e;this._map=new Map;this[hv]="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))}[(yv=Symbol.iterator,hv=Symbol.toStringTag,yv)](){return this.values()}};function fo(i,t){let e=this,n=!1,r;return function(){if(n)return r;if(n=!0,t)try{r=i.apply(e,arguments)}finally{t()}else r=i.apply(e,arguments);return r}}var Qf=class{constructor(t,e){this.uri=t;this.value=e}};function Dw(i){return Array.isArray(i)}var Sv,Oe=class i{constructor(t,e){this[Sv]="ResourceMap";if(t instanceof i)this.map=new Map(t.map),this.toKey=e??i.defaultToKey;else if(Dw(t)){this.map=new Map,this.toKey=e??i.defaultToKey;for(let[n,r]of t)this.set(n,r)}else this.map=new Map,this.toKey=t??i.defaultToKey}static{this.defaultToKey=t=>t.toString()}set(t,e){return this.map.set(this.toKey(t),new Qf(t,e)),this}get(t){return this.map.get(this.toKey(t))?.value}has(t){return this.map.has(this.toKey(t))}get size(){return this.map.size}clear(){this.map.clear()}delete(t){return this.map.delete(this.toKey(t))}forEach(t,e){typeof e<"u"&&(t=t.bind(e));for(let[n,r]of this.map)t(r.value,r.uri,this)}*values(){for(let t of this.map.values())yield t.value}*keys(){for(let t of this.map.values())yield t.uri}*entries(){for(let t of this.map.values())yield[t.uri,t.value]}*[(Sv=Symbol.toStringTag,Symbol.iterator)](){for(let[,t]of this.map)yield[t.uri,t.value]}},bv,Ia=class{constructor(t,e){this[bv]="ResourceSet";!t||typeof t=="function"?this._map=new Oe(t):(this._map=new Oe(e),t.forEach(this.add,this))}get size(){return this._map.size}add(t){return this._map.set(t,t),this}clear(){this._map.clear()}delete(t){return this._map.delete(t)}forEach(t,e){this._map.forEach((n,r)=>t.call(e,r,r,this))}has(t){return this._map.has(t)}entries(){return this._map.entries()}keys(){return this._map.keys()}values(){return this._map.keys()}[(bv=Symbol.toStringTag,Symbol.iterator)](){return this.keys()}};var Iv,_a=class{constructor(){this[Iv]="LinkedMap";this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(t){return this._map.has(t)}get(t,e=0){let n=this._map.get(t);if(n)return e!==0&&this.touch(n,e),n.value}set(t,e,n=0){let r=this._map.get(t);if(r)r.value=e,n!==0&&this.touch(r,n);else{switch(r={key:t,value:e,next:void 0,previous:void 0},n){case 0:this.addItemLast(r);break;case 1:this.addItemFirst(r);break;case 2:this.addItemLast(r);break;default:this.addItemLast(r);break}this._map.set(t,r),this._size++}return this}delete(t){return!!this.remove(t)}remove(t){let e=this._map.get(t);if(e)return this._map.delete(t),this.removeItem(e),this._size--,e.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let t=this._head;return this._map.delete(t.key),this.removeItem(t),this._size--,t.value}forEach(t,e){let n=this._state,r=this._head;for(;r;){if(e?t.bind(e)(r.value,r.key,this):t(r.value,r.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){let t=this,e=this._state,n=this._head,r={[Symbol.iterator](){return r},[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 r}values(){let t=this,e=this._state,n=this._head,r={[Symbol.iterator](){return r},[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 r}entries(){let t=this,e=this._state,n=this._head,r={[Symbol.iterator](){return r},[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 r}[(Iv=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(t){if(t>=this.size)return;if(t===0){this.clear();return}let e=this._head,n=this.size;for(;e&&n>t;)this._map.delete(e.key),e=e.next,n--;this._head=e,this._size=n,e&&(e.previous=void 0),this._state++}trimNew(t){if(t>=this.size)return;if(t===0){this.clear();return}let e=this._tail,n=this.size;for(;e&&n>t;)this._map.delete(e.key),e=e.previous,n--;this._tail=e,this._size=n,e&&(e.next=void 0),this._state++}addItemFirst(t){if(!this._head&&!this._tail)this._tail=t;else if(this._head)t.next=this._head,this._head.previous=t;else throw new Error("Invalid list");this._head=t,this._state++}addItemLast(t){if(!this._head&&!this._tail)this._head=t;else if(this._tail)t.previous=this._tail,this._tail.next=t;else throw new Error("Invalid list");this._tail=t,this._state++}removeItem(t){if(t===this._head&&t===this._tail)this._head=void 0,this._tail=void 0;else if(t===this._head){if(!t.next)throw new Error("Invalid list");t.next.previous=void 0,this._head=t.next}else if(t===this._tail){if(!t.previous)throw new Error("Invalid list");t.previous.next=void 0,this._tail=t.previous}else{let e=t.next,n=t.previous;if(!e||!n)throw new Error("Invalid list");e.previous=n,n.next=e}t.next=void 0,t.previous=void 0,this._state++}touch(t,e){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(e!==1&&e!==2)){if(e===1){if(t===this._head)return;let n=t.next,r=t.previous;t===this._tail?(r.next=void 0,this._tail=r):(n.previous=r,r.next=n),t.previous=void 0,t.next=this._head,this._head.previous=t,this._head=t,this._state++}else if(e===2){if(t===this._tail)return;let n=t.next,r=t.previous;t===this._head?(n.previous=void 0,this._head=n):(n.previous=r,r.next=n),t.next=void 0,t.previous=this._tail,this._tail.next=t,this._tail=t,this._state++}}}toJSON(){let t=[];return this.forEach((e,n)=>{t.push([n,e])}),t}fromJSON(t){this.clear();for(let[e,n]of t)this.set(e,n)}},Xf=class extends _a{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))}},On=class extends Xf{constructor(t,e=1){super(t,e)}trim(t){this.trimOld(t)}set(t,e){return super.set(t,e),this.checkTrim(),this}};var pd=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 fd(i,t){if(!i)throw new Error(t?`Assertion failed (${t})`:"Assertion Failed")}function Ca(i,t="unexpected state"){if(!i)throw typeof t=="string"?new De(`Assertion Failed: ${t}`):t}function Ta(i){if(!i()){debugger;i(),ze(new De("Assertion Failed"))}}function Ne(i){return typeof i=="string"}function Ue(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof RegExp)&&!(i instanceof Date)}function _v(i){let t=Object.getPrototypeOf(Uint8Array);return typeof i=="object"&&i instanceof t}function Pi(i){return typeof i=="number"&&!isNaN(i)}function Cv(i){return!!i&&typeof i[Symbol.iterator]=="function"}function gd(i){return i===!0||i===!1}function go(i){return typeof i>"u"}function tr(i){return!bn(i)}function bn(i){return go(i)||i===null}function Tv(i,t){if(!i)throw new Error(t?`Unexpected type, expected '${t}'`:"Unexpected type")}var Mw=Object.prototype.hasOwnProperty;function md(i){if(!Ue(i))return!1;for(let t in i)if(Mw.call(i,t))return!1;return!0}function xa(i){return typeof i=="function"}function ye(i,t){for(let e in t)if(!(e in i))return!1;return!0}var ho;(q=>{function i(E){return!!E&&typeof E=="object"&&typeof E[Symbol.iterator]=="function"}q.is=i;let t=Object.freeze([]);function e(){return t}q.empty=e;function*n(E){yield E}q.single=n;function r(E){return i(E)?E:n(E)}q.wrap=r;function o(E){return E??t}q.from=o;function*s(E){for(let L=E.length-1;L>=0;L--)yield E[L]}q.reverse=s;function a(E){return!E||E[Symbol.iterator]().next().done===!0}q.isEmpty=a;function l(E){return E[Symbol.iterator]().next().value}q.first=l;function d(E,L){let U=0;for(let J of E)if(L(J,U++))return!0;return!1}q.some=d;function c(E,L){let U=0;for(let J of E)if(!L(J,U++))return!1;return!0}q.every=c;function u(E,L){for(let U of E)if(L(U))return U}q.find=u;function*p(E,L){for(let U of E)L(U)&&(yield U)}q.filter=p;function*m(E,L){let U=0;for(let J of E)yield L(J,U++)}q.map=m;function*h(E,L){let U=0;for(let J of E)yield*L(J,U++)}q.flatMap=h;function*v(...E){for(let L of E)Cv(L)?yield*L:yield L}q.concat=v;function I(E,L,U){let J=U;for(let ne of E)J=L(J,ne);return J}q.reduce=I;function b(E){let L=0;for(let U of E)L++;return L}q.length=b;function*S(E,L,U=E.length){for(L<-E.length&&(L=0),L<0&&(L+=E.length),U<0?U+=E.length:U>E.length&&(U=E.length);L<U;L++)yield E[L]}q.slice=S;function _(E,L=Number.POSITIVE_INFINITY){let U=[];if(L===0)return[U,E];let J=E[Symbol.iterator]();for(let ne=0;ne<L;ne++){let xe=J.next();if(xe.done)return[U,q.empty()];U.push(xe.value)}return[U,{[Symbol.iterator](){return J}}]}q.consume=_;async function R(E){let L=[];for await(let U of E)L.push(U);return L}q.asyncToArray=R;async function P(E){let L=[];for await(let U of E)L=L.concat(U);return L}q.asyncToArrayFlat=P})(ho||={});var Lw=!1,yo=null;var xv=class i{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(t){let e=this.livingDisposables.get(t);return e||(e={parent:null,source:null,isSingleton:!1,value:t,idx:i.idx++},this.livingDisposables.set(t,e)),e}trackDisposable(t){let e=this.getDisposableData(t);e.source||(e.source=new Error().stack)}setParent(t,e){let n=this.getDisposableData(t);n.parent=e}markAsDisposed(t){this.livingDisposables.delete(t)}markAsSingleton(t){this.getDisposableData(t).isSingleton=!0}getRootParent(t,e){let n=e.get(t);if(n)return n;let r=t.parent?this.getRootParent(this.getDisposableData(t.parent),e):t;return e.set(t,r),r}getTrackedDisposables(){let t=new Map;return[...this.livingDisposables.entries()].filter(([,n])=>n.source!==null&&!this.getRootParent(n,t).isSingleton).flatMap(([n])=>n)}computeLeakingDisposables(t=10,e){let n;if(e)n=e;else{let l=new Map,d=[...this.livingDisposables.values()].filter(u=>u.source!==null&&!this.getRootParent(u,l).isSingleton);if(d.length===0)return;let c=new Set(d.map(u=>u.value));if(n=d.filter(u=>!(u.parent&&c.has(u.parent))),n.length===0)throw new Error("There are cyclic diposable chains!")}if(!n)return;function r(l){function d(u,p){for(;u.length>0&&p.some(m=>typeof m=="string"?m===u[0]:u[0].match(m));)u.shift()}let c=l.source.split(`
`).map(u=>u.trim().replace("at ","")).filter(u=>u!=="");return d(c,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),c.reverse()}let o=new pd;for(let l of n){let d=r(l);for(let c=0;c<=d.length;c++)o.add(d.slice(0,c).join(`
`),l)}n.sort(fv(l=>l.idx,gv));let s="",a=0;for(let l of n.slice(0,t)){a++;let d=r(l),c=[];for(let u=0;u<d.length;u++){let p=d[u];p=`(shared with ${o.get(d.slice(0,u+1).join(`
`)).size}/${n.length} leaks) at ${p}`;let h=o.get(d.slice(0,u).join(`
`)),v=vv([...h].map(I=>r(I)[u]),I=>I);delete v[d[u]];for(let[I,b]of Object.entries(v))b&&c.unshift(`    - stacktraces of ${b.length} other leaks continue with ${I}`);c.unshift(p)}s+=`


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

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


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

`),{leaks:n,details:s}}};function Nw(i){yo=i}if(Lw){let i="__is_disposable_tracked__";Nw(new class{trackDisposable(t){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[i]||console.log(e)},3e3)}setParent(t,e){if(t&&t!==T.None)try{t[i]=!0}catch{}}markAsDisposed(t){if(t&&t!==T.None)try{t[i]=!0}catch{}}markAsSingleton(t){}})}function $r(i){return yo?.trackDisposable(i),i}function Hr(i){yo?.markAsDisposed(i)}function Ai(i,t){yo?.setParent(i,t)}function Uw(i,t){if(yo)for(let e of i)yo.setParent(e,t)}function So(i){return typeof i=="object"&&i!==null&&typeof i.dispose=="function"&&i.dispose.length===0}function Tt(i){if(ho.is(i)){let t=[];for(let e of i)if(e)try{e.dispose()}catch(n){t.push(n)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function wv(...i){let t=k(()=>Tt(i));return Uw(i,t),t}var Zf=class{constructor(t){this._isDisposed=!1,this._fn=t,$r(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,Hr(this),this._fn()}}};function k(i){return new Zf(i)}var z=class i{constructor(){this._toDispose=new Set;this._isDisposed=!1;$r(this)}static{this.DISABLE_DISPOSED_WARNING=!1}dispose(){this._isDisposed||(Hr(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Tt(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 Ai(t,this),this._isDisposed?i.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.delete(t)&&Ai(t,null)}assertNotDisposed(){this._isDisposed&&ze(new De("Object disposed"))}},T=class{constructor(){this._store=new z;$r(this),Ai(this._store,this)}static{this.None=Object.freeze({dispose(){}})}dispose(){Hr(this),this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}},vt=class{constructor(){this._isDisposed=!1;$r(this)}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),t&&Ai(t,this),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Hr(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let t=this._value;return this._value=void 0,t&&Ai(t,null),t}};var vo=class{constructor(){this.references=new Map}acquire(t,...e){let n=this.references.get(t);n||(n={counter:0,object:this.createReferencedObject(t,...e)},this.references.set(t,n));let{object:r}=n,o=fo(()=>{--n.counter===0&&(this.destroyReferencedObject(t,n.object),this.references.delete(t))});return n.counter++,{object:r,dispose:o}}};var ve=class{constructor(t=new Map){this._isDisposed=!1;this._store=t,$r(this)}dispose(){Hr(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{Tt(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),Ai(e,this)}deleteAndDispose(t){this._store.get(t)?.dispose(),this._store.delete(t)}deleteAndLeak(t){let e=this._store.get(t);return e&&Ai(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 eg(i,t){return i.then(e=>(t.isDisposed?e.dispose():t.add(e),e))}var hd=class extends ve{constructor(){super(new Oe)}};var Me=class i{static{this.Undefined=new i(void 0)}constructor(t){this.element=t,this.next=i.Undefined,this.prev=i.Undefined}},wa=class{constructor(){this._first=Me.Undefined;this._last=Me.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===Me.Undefined}clear(){let t=this._first;for(;t!==Me.Undefined;){let e=t.next;t.prev=Me.Undefined,t.next=Me.Undefined,t=e}this._first=Me.Undefined,this._last=Me.Undefined,this._size=0}unshift(t){return this._insert(t,!1)}push(t){return this._insert(t,!0)}_insert(t,e){let n=new Me(t);if(this._first===Me.Undefined)this._first=n,this._last=n;else if(e){let o=this._last;this._last=n,n.prev=o,o.next=n}else{let o=this._first;this._first=n,n.next=o,o.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==Me.Undefined){let t=this._first.element;return this._remove(this._first),t}}pop(){if(this._last!==Me.Undefined){let t=this._last.element;return this._remove(this._last),t}}peek(){if(this._last!==Me.Undefined)return this._last.element}_remove(t){if(t.prev!==Me.Undefined&&t.next!==Me.Undefined){let e=t.prev;e.next=t.next,t.next.prev=e}else t.prev===Me.Undefined&&t.next===Me.Undefined?(this._first=Me.Undefined,this._last=Me.Undefined):t.next===Me.Undefined?(this._last=this._last.prev,this._last.next=Me.Undefined):t.prev===Me.Undefined&&(this._first=this._first.next,this._first.prev=Me.Undefined);this._size-=1}*[Symbol.iterator](){let t=this._first;for(;t!==Me.Undefined;)yield t.element,t=t.next}};function Fw(){return globalThis._VSCODE_NLS_MESSAGES}function tg(){return globalThis._VSCODE_NLS_LANGUAGE}var Ww=tg()==="pseudo"||typeof document<"u"&&document.location&&typeof document.location.hash=="string"&&document.location.hash.indexOf("pseudo=true")>=0;function Rv(i,t){let e;return t.length===0?e=i:e=i.replace(/\{(\d+)\}/g,(n,r)=>{let o=r[0],s=t[o],a=n;return typeof s=="string"?a=s:(typeof s=="number"||typeof s=="boolean"||s===void 0||s===null)&&(a=String(s)),a}),Ww&&(e="\uFF3B"+e.replace(/[aouei]/g,"$&$&")+"\uFF3D"),e}function g(i,t,...e){return Rv(typeof i=="number"?$w(i,t):t,e)}function $w(i,t){let e=Fw()?.[i];if(typeof e!="string"){if(typeof t=="string")return t;throw new Error(`!!! NLS MISSING: ${i} !!!`)}return e}var Br="en",Ea=!1,Pa=!1,Ra=!1,Pv=!1,Av=!1,ng=!1,Hw=!1,kv=!1,qw=!1,Bw=!1,vd,Sd=Br,Ev=Br,Vw,nr,rr=globalThis,Lt;typeof rr.vscode<"u"&&typeof rr.vscode.process<"u"?Lt=rr.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(Lt=process);var Dv=typeof Lt?.versions?.electron=="string",zw=Dv&&Lt?.type==="renderer";if(typeof Lt=="object"){Ea=Lt.platform==="win32",Pa=Lt.platform==="darwin",Ra=Lt.platform==="linux",Pv=Ra&&!!Lt.env.SNAP&&!!Lt.env.SNAP_REVISION,Hw=Dv,qw=!!Lt.env.CI||!!Lt.env.BUILD_ARTIFACTSTAGINGDIRECTORY||!!Lt.env.GITHUB_WORKSPACE,vd=Br,Sd=Br;let i=Lt.env.VSCODE_NLS_CONFIG;if(i)try{let t=JSON.parse(i);vd=t.userLocale,Ev=t.osLocale,Sd=t.resolvedLanguage||Br,Vw=t.languagePack?.translationsConfigFile}catch{}Av=!0}else typeof navigator=="object"&&!zw?(nr=navigator.userAgent,Ea=nr.indexOf("Windows")>=0,Pa=nr.indexOf("Macintosh")>=0,kv=(nr.indexOf("Macintosh")>=0||nr.indexOf("iPad")>=0||nr.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Ra=nr.indexOf("Linux")>=0,Bw=nr?.indexOf("Mobi")>=0,ng=!0,Sd=tg()||Br,vd=navigator.language.toLowerCase(),Ev=vd):console.error("Unable to resolve platform.");function Ov(i){switch(i){case 0:return"Web";case 1:return"Mac";case 2:return"Linux";case 3:return"Windows"}}var bd=0;Pa?bd=1:Ea?bd=3:Ra&&(bd=2);var G=Ea,et=Pa,Se=Ra,Mv=Pv,Lv=Av;var Et=ng,jw=ng&&typeof rr.importScripts=="function",Nv=jw?rr.origin:void 0;var rg=bd,Mn=nr,qr=Sd,Kw;(n=>{function i(){return qr}n.value=i;function t(){return qr.length===2?qr==="en":qr.length>=3?qr[0]==="e"&&qr[1]==="n"&&qr[2]==="-":!1}n.isDefaultVariant=t;function e(){return qr==="en"}n.isDefault=e})(Kw||={});var Gw=typeof rr.postMessage=="function"&&!rr.importScripts,Uv=(()=>{if(Gw){let i=[];rr.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let n=0,r=i.length;n<r;n++){let o=i[n];if(o.id===e.data.vscodeScheduleAsyncWork){i.splice(n,1),o.callback();return}}});let t=0;return e=>{let n=++t;i.push({id:n,callback:e}),rr.postMessage({vscodeScheduleAsyncWork:n},"*")}}return i=>setTimeout(i)})();var at=Pa||kv?2:Ea?1:3;var ig=!!(Mn&&Mn.indexOf("Chrome")>=0),Fv=!!(Mn&&Mn.indexOf("Firefox")>=0),Wv=!!(!ig&&Mn&&Mn.indexOf("Safari")>=0),$v=!!(Mn&&Mn.indexOf("Edg/")>=0),YN=!!(Mn&&Mn.indexOf("Android")>=0);var ki,og=globalThis.vscode;if(typeof og<"u"&&typeof og.process<"u"){let i=og.process;ki={get platform(){return i.platform},get arch(){return i.arch},get env(){return i.env},cwd(){return i.cwd()}}}else typeof process<"u"&&typeof process?.versions?.node=="string"?ki={get platform(){return process.platform},get arch(){return process.arch},get env(){return process.env},cwd(){return process.env.VSCODE_CWD||process.cwd()}}:ki={get platform(){return G?"win32":et?"darwin":"linux"},get arch(){},get env(){return{}},cwd(){return"/"}};var Di=ki.cwd,Fe=ki.env,bo=ki.platform,Hv=ki.arch;var Jw=globalThis.performance.now.bind(globalThis.performance),Io=class i{static create(t){return new i(t)}constructor(t){this._now=t===!1?Date.now:Jw,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 qv=!1,Yw=!1,Qw=100,Bv=6e4;function Vv(){return!!Fe.VSCODE_DEV}var Q;(Qn=>{Qn.None=()=>T.None;function t(B){if(Yw){let{onDidAddListener:M}=B,H=Co.create(),V=0;B.onDidAddListener=()=>{++V===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),H.print()),M?.()}}}function e(B,M,H){return m(B,()=>{},0,void 0,M??!0,void 0,H)}Qn.defer=e;function n(B){return(M,H=null,V)=>{let j=!1,Y;return Y=B(re=>{if(!j)return Y?Y.dispose():j=!0,M.call(H,re)},null,V),j&&Y.dispose(),Y}}Qn.once=n;function r(B,M){return Qn.once(Qn.filter(B,M))}Qn.onceIf=r;function o(B,M,H){return u((V,j=null,Y)=>B(re=>V.call(j,M(re)),null,Y),H)}Qn.map=o;function s(B,M,H){return u((V,j=null,Y)=>B(re=>{M(re),V.call(j,re)},null,Y),H)}Qn.forEach=s;function a(B,M,H){return u((V,j=null,Y)=>B(re=>M(re)&&V.call(j,re),null,Y),H)}Qn.filter=a;function l(B){return B}Qn.signal=l;function d(...B){return(M,H=null,V)=>{let j=wv(...B.map(Y=>Y(re=>M.call(H,re))));return p(j,V)}}Qn.any=d;function c(B,M,H,V){let j=H;return o(B,Y=>(j=M(j,Y),j),V)}Qn.reduce=c;function u(B,M){let H,V={onWillAddFirstListener(){H=B(j.fire,j)},onDidRemoveLastListener(){H?.dispose()}};M||t(V);let j=new w(V);return M?.add(j),j.event}function p(B,M){return M instanceof Array?M.push(B):M&&M.add(B),B}function m(B,M,H=100,V=!1,j=!1,Y,re){let ot,Re,yt,st=0,Ct,Xn={leakWarningThreshold:Y,onWillAddFirstListener(){ot=B(iv=>{st++,Re=M(Re,iv),V&&!yt&&(Ri.fire(Re),Re=void 0),Ct=()=>{let ov=Re;Re=void 0,yt=void 0,(!V||st>1)&&Ri.fire(ov),st=0},typeof H=="number"?(yt&&clearTimeout(yt),yt=setTimeout(Ct,H)):yt===void 0&&(yt=null,queueMicrotask(Ct))})},onWillRemoveListener(){j&&st>0&&Ct?.()},onDidRemoveLastListener(){Ct=void 0,ot.dispose()}};re||t(Xn);let Ri=new w(Xn);return re?.add(Ri),Ri.event}Qn.debounce=m;function h(B,M=0,H,V){return Qn.debounce(B,(j,Y)=>j?(j.push(Y),j):[Y],M,void 0,H??!0,void 0,V)}Qn.accumulate=h;function v(B,M,H=100,V=!0,j=!0,Y,re){let ot,Re,yt,st=0,Ct={leakWarningThreshold:Y,onWillAddFirstListener(){ot=B(Ri=>{st++,Re=M(Re,Ri),yt===void 0&&(V&&(Xn.fire(Re),Re=void 0,st=0),typeof H=="number"?yt=setTimeout(()=>{j&&st>0&&Xn.fire(Re),Re=void 0,yt=void 0,st=0},H):(yt=0,queueMicrotask(()=>{j&&st>0&&Xn.fire(Re),Re=void 0,yt=void 0,st=0})))})},onDidRemoveLastListener(){ot.dispose()}};re||t(Ct);let Xn=new w(Ct);return re?.add(Xn),Xn.event}Qn.throttle=v;function I(B,M=(V,j)=>V===j,H){let V=!0,j;return a(B,Y=>{let re=V||!M(Y,j);return V=!1,j=Y,re},H)}Qn.latch=I;function b(B,M,H){return[Qn.filter(B,M,H),Qn.filter(B,V=>!M(V),H)]}Qn.split=b;function S(B,M,H=!1,V=[],j){let Y=V.slice(),re;Vv()&&(re={stack:Co.create(),timerId:setTimeout(()=>{Y&&Y.length>0&&re&&!re.warned&&(re.warned=!0,console.warn(`[Event.buffer][${M}] potential LEAK detected: ${Y.length} events buffered for ${Bv/1e3}s without being consumed. Buffered here:`),re.stack.print())},Bv),warned:!1},j&&j.add(k(()=>clearTimeout(re.timerId))));let ot=()=>{re&&clearTimeout(re.timerId)},Re=B(Ct=>{Y?(Y.push(Ct),Vv()&&re&&!re.warned&&Y.length>=Qw&&(re.warned=!0,console.warn(`[Event.buffer][${M}] potential LEAK detected: ${Y.length} events buffered without being consumed. Buffered here:`),re.stack.print())):st.fire(Ct)});j&&j.add(Re);let yt=()=>{Y?.forEach(Ct=>st.fire(Ct)),Y=null,ot()},st=new w({onWillAddFirstListener(){Re||(Re=B(Ct=>st.fire(Ct)),j&&j.add(Re))},onDidAddFirstListener(){Y&&(H?setTimeout(yt):yt())},onDidRemoveLastListener(){Re&&Re.dispose(),Re=null,ot()}});return j&&j.add(st),st.event}Qn.buffer=S;function _(B,M){return(V,j,Y)=>{let re=M(new P);return B(function(ot){let Re=re.evaluate(ot);Re!==R&&V.call(j,Re)},void 0,Y)}}Qn.chain=_;let R=Symbol("HaltChainable");class P{constructor(){this.steps=[]}map(M){return this.steps.push(M),this}forEach(M){return this.steps.push(H=>(M(H),H)),this}filter(M){return this.steps.push(H=>M(H)?H:R),this}reduce(M,H){let V=H;return this.steps.push(j=>(V=M(V,j),V)),this}latch(M=(H,V)=>H===V){let H=!0,V;return this.steps.push(j=>{let Y=H||!M(j,V);return H=!1,V=j,Y?j:R}),this}evaluate(M){for(let H of this.steps)if(M=H(M),M===R)break;return M}}function q(B,M,H=V=>V){let V=(...ot)=>re.fire(H(...ot)),j=()=>B.on(M,V),Y=()=>B.removeListener(M,V),re=new w({onWillAddFirstListener:j,onDidRemoveLastListener:Y});return re.event}Qn.fromNodeEventEmitter=q;function E(B,M,H=V=>V){let V=(...ot)=>re.fire(H(...ot)),j=()=>B.addEventListener(M,V),Y=()=>B.removeEventListener(M,V),re=new w({onWillAddFirstListener:j,onDidRemoveLastListener:Y});return re.event}Qn.fromDOMEventEmitter=E;function L(B,M){let H,V,j=new Promise(Y=>{V=n(B)(Y),ug(V,M),H=()=>{jv(V,M)}});return j.cancel=H,M&&j.finally(()=>jv(V,M)),j}Qn.toPromise=L;function U(B,M){return B(H=>M.fire(H))}Qn.forward=U;function J(B,M,H){return M(H),B(V=>M(V))}Qn.runAndSubscribe=J;class ne{constructor(M,H){this._observable=M;this._counter=0;this._hasChanged=!1;let V={onWillAddFirstListener:()=>{M.addObserver(this),this._observable.reportChanges()},onDidRemoveLastListener:()=>{M.removeObserver(this)}};H||t(V),this.emitter=new w(V),H&&H.add(this.emitter)}beginUpdate(M){this._counter++}handlePossibleChange(M){}handleChange(M,H){this._hasChanged=!0}endUpdate(M){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function xe(B,M){return new ne(B,M).emitter.event}Qn.fromObservable=xe;function ba(B){return(M,H,V)=>{let j=0,Y=!1,re={beginUpdate(){j++},endUpdate(){j--,j===0&&(B.reportChanges(),Y&&(Y=!1,M.call(H)))},handlePossibleChange(){},handleChange(){Y=!0}};B.addObserver(re),B.reportChanges();let ot={dispose(){B.removeObserver(re)}};return ug(ot,V),ot}}Qn.fromObservableLight=ba})(Q||={});var ag=class i{constructor(t){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${t}_${i._idPool++}`,i.all.add(this)}static{this.all=new Set}static{this._idPool=0}start(t){this._stopWatch=new Io,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}}},zv=-1;var lg=class i{constructor(t,e,n=(i._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t;this.threshold=e;this.name=n;this._warnCountdown=0}static{this._idPool=1}dispose(){this._stacks?.clear()}check(t,e){let n=this.threshold;if(n<=0||e<n)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=n*.5;let[o,s]=this.getMostFrequentStack(),a=/^[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 d=s/e>.3?"dominated":"popular",c=new Id(d,l,o,e,a);this._errorHandler(c)}return()=>{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,e=0;for(let[n,r]of this._stacks)(!t||e<r)&&(t=[n,r],e=r);return t}},Co=class i{constructor(t){this.value=t}static create(){let t=new Error;return new i(t.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},Id=class i extends Error{constructor(t,e,n,r,o){super(o?`[${o}] potential listener LEAK detected, ${t}`:`potential listener LEAK detected, ${t}`),this.name="ListenerLeakError",this.kind=t,this.listenerCount=r,this.details=e,this.stack=n}static is(t){return t instanceof i||t instanceof Error&&typeof t.kind=="string"&&typeof t.listenerCount=="number"}},dg=class extends Id{constructor(t,e,n,r,o){super(t,e,n,r,o),this.name="ListenerRefusalError"}},Xw=0,_o=class{constructor(t){this.value=t;this.id=Xw++}},Zw=2,eR=(i,t)=>{if(i instanceof _o)t(i);else for(let e=0;e<i.length;e++){let n=i[e];n&&t(n)}},w=class{constructor(t){this._size=0;this._options=t,this._leakageMon=zv>0||this._options?.leakWarningThreshold?new lg(t?.onListenerError??ze,this._options?.leakWarningThreshold??zv,this._options?.leakWarningName):void 0,this._perfMon=this._options?._profName?new ag(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(qv){let t=this._listeners;queueMicrotask(()=>{eR(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 d=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=d[1]/this._size>.3?"dominated":"popular",u=new dg(c,`${l}. HINT: Stack shows most frequent listener (${d[1]}-times)`,d[0],this._size,this._options?.leakWarningName);return(this._options?.onListenerError||ze)(u),T.None}if(this._disposed)return T.None;e&&(t=t.bind(e));let r=new _o(t),o,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Co.create(),o=this._leakageMon.check(r.stack,this._size+1)),qv&&(r.stack=s??Co.create()),this._listeners?this._listeners instanceof _o?(this._deliveryQueue??=new cg,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._options?.onDidAddListener?.(this),this._size++;let a=k(()=>{o?.(),this._removeListener(r)});return ug(a,n),a},this._event}_removeListener(t){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let e=this._listeners,n=e.indexOf(t);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,e[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Zw<=e.length){let o=0;for(let s=0;s<e.length;s++)e[s]?e[o++]=e[s]:r&&o<this._deliveryQueue.end&&(this._deliveryQueue.end--,o<this._deliveryQueue.i&&this._deliveryQueue.i--);e.length=o}}_deliver(t,e){if(!t)return;let n=this._options?.onListenerError||ze;if(!n){t.value(e);return}try{t.value(e)}catch(r){n(r)}}_deliverQueue(t){let e=t.current._listeners;for(;t.i<t.end;)this._deliver(e[t.i++],t.value);t.reset()}fire(t){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof _o)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 cg=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 _d=class{constructor(){this.hasListeners=!1;this.events=[];this.emitter=new w({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),k(fo(()=>{this.hasListeners&&this.unhook(e);let r=this.events.indexOf(e);this.events.splice(r,1)}))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach(t=>this.hook(t))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach(t=>this.unhook(t))}hook(t){t.listener=t.event(e=>this.emitter.fire(e))}unhook(t){t.listener?.dispose(),t.listener=null}dispose(){this.emitter.dispose();for(let t of this.events)t.listener?.dispose();this.events=[]}};var Aa=class{constructor(){this.listening=!1;this.inputEvent=Q.None;this.inputEventListener=T.None;this.emitter=new w({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 ug(i,t){t instanceof z?t.add(i):Array.isArray(t)&&t.push(i)}function jv(i,t){if(t instanceof z)t.delete(i);else if(Array.isArray(t)){let e=t.indexOf(i);e!==-1&&t.splice(e,1)}i.dispose()}var Kv=Object.freeze(function(i,t){let e=setTimeout(i.bind(t),0);return{dispose(){clearTimeout(e)}}}),Ee;(n=>{function i(r){return r===n.None||r===n.Cancelled||r instanceof To?!0:!r||typeof r!="object"?!1:typeof r.isCancellationRequested=="boolean"&&typeof r.onCancellationRequested=="function"}n.isCancellationToken=i,n.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Q.None}),n.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Kv})})(Ee||={});var To=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?Kv:(this._emitter||(this._emitter=new w),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},je=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 To),this._token}cancel(){this._token?this._token instanceof To&&this._token.cancel():this._token=Ee.Cancelled}dispose(t=!1){t&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof To&&this._token.dispose():this._token=Ee.None}};var tR=65,nR=97,rR=90,iR=122,Oi=46,lt=47,Nt=92,ir=58,oR=63,Cd=class extends Error{constructor(t,e,n){let r;typeof e=="string"&&e.indexOf("not ")===0?(r="must not be",e=e.replace(/^not /,"")):r="must be";let o=t.indexOf(".")!==-1?"property":"argument",s=`The "${t}" ${o} ${r} of type ${e}`;s+=`. Received type ${typeof n}`,super(s),this.code="ERR_INVALID_ARG_TYPE"}};function sR(i,t){if(i===null||typeof i!="object")throw new Cd(t,"Object",i)}function Ge(i,t){if(typeof i!="string")throw new Cd(t,"string",i)}var Ut=bo==="win32";function oe(i){return i===lt||i===Nt}function pg(i){return i===lt}function or(i){return i>=tR&&i<=rR||i>=nR&&i<=iR}function Td(i,t,e,n){let r="",o=0,s=-1,a=0,l=0;for(let d=0;d<=i.length;++d){if(d<i.length)l=i.charCodeAt(d);else{if(n(l))break;l=lt}if(n(l)){if(!(s===d-1||a===1))if(a===2){if(r.length<2||o!==2||r.charCodeAt(r.length-1)!==Oi||r.charCodeAt(r.length-2)!==Oi){if(r.length>2){let c=r.lastIndexOf(e);c===-1?(r="",o=0):(r=r.slice(0,c),o=r.length-1-r.lastIndexOf(e)),s=d,a=0;continue}else if(r.length!==0){r="",o=0,s=d,a=0;continue}}t&&(r+=r.length>0?`${e}..`:"..",o=2)}else r.length>0?r+=`${e}${i.slice(s+1,d)}`:r=i.slice(s+1,d),o=d-s-1;s=d,a=0}else l===Oi&&a!==-1?++a:a=-1}return r}function aR(i){return i?`${i[0]==="."?"":"."}${i}`:""}function Gv(i,t){sR(t,"pathObject");let e=t.dir||t.root,n=t.base||`${t.name||""}${aR(t.ext)}`;return e?e===t.root?`${e}${n}`:`${e}${i}${n}`:n}var le={resolve(...i){let t="",e="",n=!1;for(let r=i.length-1;r>=-1;r--){let o;if(r>=0){if(o=i[r],Ge(o,`paths[${r}]`),o.length===0)continue}else t.length===0?o=Di():(o=Fe[`=${t}`]||Di(),(o===void 0||o.slice(0,2).toLowerCase()!==t.toLowerCase()&&o.charCodeAt(2)===Nt)&&(o=`${t}\\`));let s=o.length,a=0,l="",d=!1,c=o.charCodeAt(0);if(s===1)oe(c)&&(a=1,d=!0);else if(oe(c))if(d=!0,oe(o.charCodeAt(1))){let u=2,p=u;for(;u<s&&!oe(o.charCodeAt(u));)u++;if(u<s&&u!==p){let m=o.slice(p,u);for(p=u;u<s&&oe(o.charCodeAt(u));)u++;if(u<s&&u!==p){for(p=u;u<s&&!oe(o.charCodeAt(u));)u++;(u===s||u!==p)&&(l=`\\\\${m}\\${o.slice(p,u)}`,a=u)}}}else a=1;else or(c)&&o.charCodeAt(1)===ir&&(l=o.slice(0,2),a=2,s>2&&oe(o.charCodeAt(2))&&(d=!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=d,d&&t.length>0)break}return e=Td(e,!n,"\\",oe),n?`${t}\\${e}`:`${t}${e}`||"."},normalize(i){Ge(i,"path");let t=i.length;if(t===0)return".";let e=0,n,r=!1,o=i.charCodeAt(0);if(t===1)return pg(o)?"\\":i;if(oe(o))if(r=!0,oe(i.charCodeAt(1))){let a=2,l=a;for(;a<t&&!oe(i.charCodeAt(a));)a++;if(a<t&&a!==l){let d=i.slice(l,a);for(l=a;a<t&&oe(i.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&!oe(i.charCodeAt(a));)a++;if(a===t)return`\\\\${d}\\${i.slice(l)}\\`;a!==l&&(n=`\\\\${d}\\${i.slice(l,a)}`,e=a)}}}else e=1;else or(o)&&i.charCodeAt(1)===ir&&(n=i.slice(0,2),e=2,t>2&&oe(i.charCodeAt(2))&&(r=!0,e=3));let s=e<t?Td(i.slice(e),!r,"\\",oe):"";if(s.length===0&&!r&&(s="."),s.length>0&&oe(i.charCodeAt(t-1))&&(s+="\\"),!r&&n===void 0&&i.includes(":")){if(s.length>=2&&or(s.charCodeAt(0))&&s.charCodeAt(1)===ir)return`.\\${s}`;let a=i.indexOf(":");do if(a===t-1||oe(i.charCodeAt(a+1)))return`.\\${s}`;while((a=i.indexOf(":",a+1))!==-1)}return n===void 0?r?`\\${s}`:s:r?`${n}\\${s}`:`${n}${s}`},isAbsolute(i){Ge(i,"path");let t=i.length;if(t===0)return!1;let e=i.charCodeAt(0);return oe(e)||t>2&&or(e)&&i.charCodeAt(1)===ir&&oe(i.charCodeAt(2))},join(...i){if(i.length===0)return".";let t,e;for(let o=0;o<i.length;++o){let s=i[o];Ge(s,"path"),s.length>0&&(t===void 0?t=e=s:t+=`\\${s}`)}if(t===void 0)return".";let n=!0,r=0;if(typeof e=="string"&&oe(e.charCodeAt(0))){++r;let o=e.length;o>1&&oe(e.charCodeAt(1))&&(++r,o>2&&(oe(e.charCodeAt(2))?++r:n=!1))}if(n){for(;r<t.length&&oe(t.charCodeAt(r));)r++;r>=2&&(t=`\\${t.slice(r)}`)}return le.normalize(t)},relative(i,t){if(Ge(i,"from"),Ge(t,"to"),i===t)return"";let e=le.resolve(i),n=le.resolve(t);if(e===n||(i=e.toLowerCase(),t=n.toLowerCase(),i===t))return"";if(e.length!==i.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 I=h.length,b=v.length,S=I<b?I:b,_;for(_=0;_<S&&h[_].toLowerCase()===v[_].toLowerCase();_++);return _===0?n:_===S?b>S?v.slice(_).join("\\"):I>S?"..\\".repeat(I-1-_)+"..":"":"..\\".repeat(I-_)+v.slice(_).join("\\")}let r=0;for(;r<i.length&&i.charCodeAt(r)===Nt;)r++;let o=i.length;for(;o-1>r&&i.charCodeAt(o-1)===Nt;)o--;let s=o-r,a=0;for(;a<t.length&&t.charCodeAt(a)===Nt;)a++;let l=t.length;for(;l-1>a&&t.charCodeAt(l-1)===Nt;)l--;let d=l-a,c=s<d?s:d,u=-1,p=0;for(;p<c;p++){let h=i.charCodeAt(r+p);if(h!==t.charCodeAt(a+p))break;h===Nt&&(u=p)}if(p!==c){if(u===-1)return n}else{if(d>c){if(t.charCodeAt(a+p)===Nt)return n.slice(a+p+1);if(p===2)return n.slice(a+p)}s>c&&(i.charCodeAt(r+p)===Nt?u=p:p===2&&(u=3)),u===-1&&(u=0)}let m="";for(p=r+u+1;p<=o;++p)(p===o||i.charCodeAt(p)===Nt)&&(m+=m.length===0?"..":"\\..");return a+=u,m.length>0?`${m}${n.slice(a,l)}`:(n.charCodeAt(a)===Nt&&++a,n.slice(a,l))},toNamespacedPath(i){if(typeof i!="string"||i.length===0)return i;let t=le.resolve(i);if(t.length<=2)return i;if(t.charCodeAt(0)===Nt){if(t.charCodeAt(1)===Nt){let e=t.charCodeAt(2);if(e!==oR&&e!==Oi)return`\\\\?\\UNC\\${t.slice(2)}`}}else if(or(t.charCodeAt(0))&&t.charCodeAt(1)===ir&&t.charCodeAt(2)===Nt)return`\\\\?\\${t}`;return t},dirname(i){Ge(i,"path");let t=i.length;if(t===0)return".";let e=-1,n=0,r=i.charCodeAt(0);if(t===1)return oe(r)?i:".";if(oe(r)){if(e=n=1,oe(i.charCodeAt(1))){let a=2,l=a;for(;a<t&&!oe(i.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&oe(i.charCodeAt(a));)a++;if(a<t&&a!==l){for(l=a;a<t&&!oe(i.charCodeAt(a));)a++;if(a===t)return i;a!==l&&(e=n=a+1)}}}}else or(r)&&i.charCodeAt(1)===ir&&(e=t>2&&oe(i.charCodeAt(2))?3:2,n=e);let o=-1,s=!0;for(let a=t-1;a>=n;--a)if(oe(i.charCodeAt(a))){if(!s){o=a;break}}else s=!1;if(o===-1){if(e===-1)return".";o=e}return i.slice(0,o)},basename(i,t){t!==void 0&&Ge(t,"suffix"),Ge(i,"path");let e=0,n=-1,r=!0,o;if(i.length>=2&&or(i.charCodeAt(0))&&i.charCodeAt(1)===ir&&(e=2),t!==void 0&&t.length>0&&t.length<=i.length){if(t===i)return"";let s=t.length-1,a=-1;for(o=i.length-1;o>=e;--o){let l=i.charCodeAt(o);if(oe(l)){if(!r){e=o+1;break}}else a===-1&&(r=!1,a=o+1),s>=0&&(l===t.charCodeAt(s)?--s===-1&&(n=o):(s=-1,n=a))}return e===n?n=a:n===-1&&(n=i.length),i.slice(e,n)}for(o=i.length-1;o>=e;--o)if(oe(i.charCodeAt(o))){if(!r){e=o+1;break}}else n===-1&&(r=!1,n=o+1);return n===-1?"":i.slice(e,n)},extname(i){Ge(i,"path");let t=0,e=-1,n=0,r=-1,o=!0,s=0;i.length>=2&&i.charCodeAt(1)===ir&&or(i.charCodeAt(0))&&(t=n=2);for(let a=i.length-1;a>=t;--a){let l=i.charCodeAt(a);if(oe(l)){if(!o){n=a+1;break}continue}r===-1&&(o=!1,r=a+1),l===Oi?e===-1?e=a:s!==1&&(s=1):e!==-1&&(s=-1)}return e===-1||r===-1||s===0||s===1&&e===r-1&&e===n+1?"":i.slice(e,r)},format:Gv.bind(null,"\\"),parse(i){Ge(i,"path");let t={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return t;let e=i.length,n=0,r=i.charCodeAt(0);if(e===1)return oe(r)?(t.root=t.dir=i,t):(t.base=t.name=i,t);if(oe(r)){if(n=1,oe(i.charCodeAt(1))){let u=2,p=u;for(;u<e&&!oe(i.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&oe(i.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&!oe(i.charCodeAt(u));)u++;u===e?n=u:u!==p&&(n=u+1)}}}}else if(or(r)&&i.charCodeAt(1)===ir){if(e<=2)return t.root=t.dir=i,t;if(n=2,oe(i.charCodeAt(2))){if(e===3)return t.root=t.dir=i,t;n=3}}n>0&&(t.root=i.slice(0,n));let o=-1,s=n,a=-1,l=!0,d=i.length-1,c=0;for(;d>=n;--d){if(r=i.charCodeAt(d),oe(r)){if(!l){s=d+1;break}continue}a===-1&&(l=!1,a=d+1),r===Oi?o===-1?o=d:c!==1&&(c=1):o!==-1&&(c=-1)}return a!==-1&&(o===-1||c===0||c===1&&o===a-1&&o===s+1?t.base=t.name=i.slice(s,a):(t.name=i.slice(s,o),t.base=i.slice(s,a),t.ext=i.slice(o,a))),s>0&&s!==n?t.dir=i.slice(0,s-1):t.dir=t.root,t},sep:"\\",delimiter:";",win32:null,posix:null},lR=(()=>{if(Ut){let i=/\\/g;return()=>{let t=Di().replace(i,"/");return t.slice(t.indexOf("/"))}}return()=>Di()})(),Z={resolve(...i){let t="",e=!1;for(let n=i.length-1;n>=0&&!e;n--){let r=i[n];Ge(r,`paths[${n}]`),r.length!==0&&(t=`${r}/${t}`,e=r.charCodeAt(0)===lt)}if(!e){let n=lR();t=`${n}/${t}`,e=n.charCodeAt(0)===lt}return t=Td(t,!e,"/",pg),e?`/${t}`:t.length>0?t:"."},normalize(i){if(Ge(i,"path"),i.length===0)return".";let t=i.charCodeAt(0)===lt,e=i.charCodeAt(i.length-1)===lt;return i=Td(i,!t,"/",pg),i.length===0?t?"/":e?"./":".":(e&&(i+="/"),t?`/${i}`:i)},isAbsolute(i){return Ge(i,"path"),i.length>0&&i.charCodeAt(0)===lt},join(...i){if(i.length===0)return".";let t=[];for(let e=0;e<i.length;++e){let n=i[e];Ge(n,"path"),n.length>0&&t.push(n)}return t.length===0?".":Z.normalize(t.join("/"))},relative(i,t){if(Ge(i,"from"),Ge(t,"to"),i===t||(i=Z.resolve(i),t=Z.resolve(t),i===t))return"";let e=1,n=i.length,r=n-e,o=1,s=t.length-o,a=r<s?r:s,l=-1,d=0;for(;d<a;d++){let u=i.charCodeAt(e+d);if(u!==t.charCodeAt(o+d))break;u===lt&&(l=d)}if(d===a)if(s>a){if(t.charCodeAt(o+d)===lt)return t.slice(o+d+1);if(d===0)return t.slice(o+d)}else r>a&&(i.charCodeAt(e+d)===lt?l=d:d===0&&(l=0));let c="";for(d=e+l+1;d<=n;++d)(d===n||i.charCodeAt(d)===lt)&&(c+=c.length===0?"..":"/..");return`${c}${t.slice(o+l)}`},toNamespacedPath(i){return i},dirname(i){if(Ge(i,"path"),i.length===0)return".";let t=i.charCodeAt(0)===lt,e=-1,n=!0;for(let r=i.length-1;r>=1;--r)if(i.charCodeAt(r)===lt){if(!n){e=r;break}}else n=!1;return e===-1?t?"/":".":t&&e===1?"//":i.slice(0,e)},basename(i,t){t!==void 0&&Ge(t,"suffix"),Ge(i,"path");let e=0,n=-1,r=!0,o;if(t!==void 0&&t.length>0&&t.length<=i.length){if(t===i)return"";let s=t.length-1,a=-1;for(o=i.length-1;o>=0;--o){let l=i.charCodeAt(o);if(l===lt){if(!r){e=o+1;break}}else a===-1&&(r=!1,a=o+1),s>=0&&(l===t.charCodeAt(s)?--s===-1&&(n=o):(s=-1,n=a))}return e===n?n=a:n===-1&&(n=i.length),i.slice(e,n)}for(o=i.length-1;o>=0;--o)if(i.charCodeAt(o)===lt){if(!r){e=o+1;break}}else n===-1&&(r=!1,n=o+1);return n===-1?"":i.slice(e,n)},extname(i){Ge(i,"path");let t=-1,e=0,n=-1,r=!0,o=0;for(let s=i.length-1;s>=0;--s){let a=i[s];if(a==="/"){if(!r){e=s+1;break}continue}n===-1&&(r=!1,n=s+1),a==="."?t===-1?t=s:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||n===-1||o===0||o===1&&t===n-1&&t===e+1?"":i.slice(t,n)},format:Gv.bind(null,"/"),parse(i){Ge(i,"path");let t={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return t;let e=i.charCodeAt(0)===lt,n;e?(t.root="/",n=1):n=0;let r=-1,o=0,s=-1,a=!0,l=i.length-1,d=0;for(;l>=n;--l){let c=i.charCodeAt(l);if(c===lt){if(!a){o=l+1;break}continue}s===-1&&(a=!1,s=l+1),c===Oi?r===-1?r=l:d!==1&&(d=1):r!==-1&&(d=-1)}if(s!==-1){let c=o===0&&e?1:o;r===-1||d===0||d===1&&r===s-1&&r===o+1?t.base=t.name=i.slice(c,s):(t.name=i.slice(c,r),t.base=i.slice(c,s),t.ext=i.slice(r,s))}return o>0?t.dir=i.slice(0,o-1):e&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};Z.win32=le.win32=le;Z.posix=le.posix=Z;var Ft=Ut?le.normalize:Z.normalize,Wt=Ut?le.isAbsolute:Z.isAbsolute,W=Ut?le.join:Z.join,dn=Ut?le.resolve:Z.resolve,Jv=Ut?le.relative:Z.relative,se=Ut?le.dirname:Z.dirname,Ce=Ut?le.basename:Z.basename,xd=Ut?le.extname:Z.extname,m4=Ut?le.format:Z.format,Yv=Ut?le.parse:Z.parse,h4=Ut?le.toNamespacedPath:Z.toNamespacedPath,be=Ut?le.sep:Z.sep,xo=Ut?le.delimiter:Z.delimiter;function dR(i){return i}var wd=class{constructor(t,e){this.lastCache=void 0;this.lastArgKey=void 0;typeof t=="function"?(this._fn=t,this._computeKey=dR):(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 Le=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 tS(i){return!i||typeof i!="string"?!0:i.trim().length===0}var cR=/{(\d+)}/g;function Mi(i,...t){return t.length===0?i:i.replace(cR,function(e,n){let r=parseInt(n,10);return isNaN(r)||r<0||r>=t.length?e:t[r]})}var uR=/{([^}]+)}/g;function nS(i,t){return Object.keys(t).length===0?i:i.replace(uR,(e,n)=>t[n]??e)}function Zt(i){return i.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function ar(i,t,e=vR){return i.length<=t?i:`${i.substr(0,t)}${e}`}function fg(i,t){if(!i||!t)return i;let e=t.length,n=0;if(e===1){let r=t.charCodeAt(0);for(;n<i.length&&i.charCodeAt(n)===r;)n++}else for(;i.startsWith(t,n);)n+=e;return i.substring(n)}function wo(i,t){if(!i||!t)return i;let e=t.length,n=i.length;if(e===1){let o=n,s=t.charCodeAt(0);for(;o>0&&i.charCodeAt(o-1)===s;)o--;return i.substring(0,o)}let r=n;for(;r>0&&i.endsWith(t,r);)r-=e;return i.substring(0,r)}function rS(i){return i.source==="^"||i.source==="^$"||i.source==="$"||i.source==="^\\s*$"?!1:!!(i.exec("")&&i.lastIndex===0)}function iS(i){let t=[],e=i.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 lr(i,t){return i<t?-1:i>t?1:0}function Rd(i,t,e=0,n=i.length,r=0,o=t.length){for(;e<n&&r<o;e++,r++){let l=i.charCodeAt(e),d=t.charCodeAt(r);if(l<d)return-1;if(l>d)return 1}let s=n-e,a=o-r;return s<a?-1:s>a?1:0}function gg(i,t){return Li(i,t,0,i.length,0,t.length)}function Li(i,t,e=0,n=i.length,r=0,o=t.length){for(;e<n&&r<o;e++,r++){let l=i.charCodeAt(e),d=t.charCodeAt(r);if(l===d)continue;if(l>=128||d>=128)return Rd(i.toLowerCase(),t.toLowerCase(),e,n,r,o);Qv(l)&&(l-=32),Qv(d)&&(d-=32);let c=l-d;if(c!==0)return c}let s=n-e,a=o-r;return s<a?-1:s>a?1:0}function Qv(i){return i>=97&&i<=122}function mg(i){return i>=65&&i<=90}function dr(i,t){return i.length===t.length&&Li(i,t)===0}function jr(i,t){let e=t.length;return e<=i.length&&Li(i,t,0,e)===0}function oS(i,t){let e=i.length,n=e-t.length;return n>=0&&Li(i,t,n,e)===0}function sS(i){return 55296<=i&&i<=56319}function hg(i){return 56320<=i&&i<=57343}function aS(i,t){return(i-55296<<10)+(t-56320)+65536}var pR=/(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/,fR=/(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/,gR=/\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/,mR=new RegExp("(?:"+[pR.source,fR.source,gR.source].join("|")+")","g");function lS(i){return i&&(i=i.replace(mR,"")),i}var R4=String.fromCharCode(65279);function hR(i){return!!(i&&i.length>0&&i.charCodeAt(0)===65279)}function dS(i){return hR(i)?i.substr(1):i}var Xv=class i{static{this._INSTANCE=null}static getInstance(){return i._INSTANCE||(i._INSTANCE=new i),i._INSTANCE}constructor(){this._data=yR()}getGraphemeBreakType(t){if(t<32)return t===10?3:t===13?2:4;if(t<127)return 0;let e=this._data,n=e.length/3,r=1;for(;r<=n;)if(t<e[3*r])r=2*r;else if(t>e[3*r+1])r=2*r+1;else return e[3*r+2];return 0}};function yR(){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 Zv=class i{constructor(t){this.confusableDictionary=t}static{this.ambiguousCharacterData=new Le(()=>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 wd(t=>{let e=t.split(",");function n(u){let p=new Map;for(let m=0;m<u.length;m+=2)p.set(u[m],u[m+1]);return p}function r(u,p){let m=new Map(u);for(let[h,v]of p)m.set(h,v);return m}function o(u,p){if(!u)return p;let m=new Map;for(let[h,v]of u)p.has(h)&&m.set(h,v);return m}let s=this.ambiguousCharacterData.value,a=e.filter(u=>!u.startsWith("_")&&Object.hasOwn(s,u));a.length===0&&(a=["_default"]);let l;for(let u of a){let p=n(s[u]);l=o(l,p)}let d=n(s._common),c=r(d,l);return new i(c)})}static getInstance(t){return i.cache.get(Array.from(t).join(","))}static{this._locales=new Le(()=>Object.keys(i.ambiguousCharacterData.value).filter(t=>!t.startsWith("_")))}static getLocales(){return i._locales.value}isAmbiguous(t){return this.confusableDictionary.has(t)}containsAmbiguousCharacter(t){for(let e=0;e<t.length;e++){let n=t.codePointAt(e);if(typeof n=="number"&&this.isAmbiguous(n))return!0}return!1}getPrimaryConfusable(t){return this.confusableDictionary.get(t)}getConfusableCodePoints(){return new Set(this.confusableDictionary.keys())}},eS=class i{static getRawData(){return JSON.parse('{"_common":[11,12,13,127,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999],"cs":[173,8203,12288],"de":[173,8203,12288],"es":[8203,12288],"fr":[173,8203,12288],"it":[160,173,12288],"ja":[173],"ko":[173,12288],"pl":[173,8203,12288],"pt-BR":[173,8203,12288],"qps-ploc":[160,173,8203,12288],"ru":[173,12288],"tr":[160,173,8203,12288],"zh-hans":[160,173,8203,12288],"zh-hant":[173,12288]}')}static{this._data=void 0}static getData(){return this._data||(this._data=new Set([...Object.values(i.getRawData())].flat())),this._data}static isInvisibleCharacter(t){return i.getData().has(t)}static containsInvisibleCharacter(t){for(let e=0;e<t.length;e++){let n=t.codePointAt(e);if(typeof n=="number"&&(i.isInvisibleCharacter(n)||n===32))return!0}return!1}static get codePoints(){return i.getData()}},vR="\u2026";function Kr(i){return i===47||i===92}function Ed(i){return i.replace(/[\\/]/g,Z.sep)}function cS(i){return i.indexOf("/")===-1&&(i=Ed(i)),/^[a-zA-Z]:(\/|$)/.test(i)&&(i="/"+i),i}function vg(i,t=Z.sep){if(!i)return"";let e=i.length,n=i.charCodeAt(0);if(Kr(n)){if(Kr(i.charCodeAt(1))&&!Kr(i.charCodeAt(2))){let o=3,s=o;for(;o<e&&!Kr(i.charCodeAt(o));o++);if(s!==o&&!Kr(i.charCodeAt(o+1))){for(o+=1;o<e;o++)if(Kr(i.charCodeAt(o)))return i.slice(0,o+1).replace(/[\\/]/g,t)}}return t}else if(uS(n)&&i.charCodeAt(1)===58)return Kr(i.charCodeAt(2))?i.slice(0,2)+t:i.slice(0,2);let r=i.indexOf("://");if(r!==-1){for(r+=3;r<e;r++)if(Kr(i.charCodeAt(r)))return i.slice(0,r+1)}return""}function Ro(i,t,e){let n=i===t;return!e||n?n:!i||!t?!1:dr(i,t)}function cr(i,t,e,n=!1){let r=n?Z.sep:be;if(i===t)return!0;if(!i||!t||((i.indexOf("..")>=0||t.indexOf("..")>=0)&&(i=n?Z.normalize(i):Ft(i),t=n?Z.normalize(t):Ft(t)),t.length>i.length))return!1;if(e){if(!jr(i,t))return!1;if(t.length===i.length)return!0;let s=t.length;return t.charAt(t.length-1)===r&&s--,i.charAt(s)===r}return t.charAt(t.length-1)!==r&&(t+=r),i.indexOf(t)===0}function uS(i){return i>=65&&i<=90||i>=97&&i<=122}function pS(i){return G?(i=wo(i,be),i.endsWith(":")&&(i+=be)):(i=wo(i,be),i||(i=be)),i}function Sg(i){let t=Ft(i);return G?i.length>3?!1:fS(t)&&(i.length===2||t.charCodeAt(2)===92):t===Z.sep}function fS(i,t=G){return t?uS(i.charCodeAt(0))&&i.charCodeAt(1)===58:!1}var SR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",bR="BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";function gS(i,t,e=8){let n="";for(let o=0;o<e;o++){let s;o===0&&G&&!t&&(e===3||e===4)?s=bR:s=SR,n+=s.charAt(Math.floor(Math.random()*s.length))}let r;return t?r=`${t}-${n}`:r=n,i?W(i,r):r}var _R=/^\w[\w\d+.-]*$/,CR=/^\//,TR=/^\/\//;function xR(i,t){if(!i.scheme&&t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${i.authority}", path: "${i.path}", query: "${i.query}", fragment: "${i.fragment}"}`);if(i.scheme&&!_R.test(i.scheme)){let e=[...i.scheme.matchAll(/[^\w\d+.-]/gu)],n=e.length>0?` Found '${e[0][0]}' at index ${e[0].index} (${e.length} total)`:"";throw new Error(`[UriError]: Scheme contains illegal characters.${n} (len:${i.scheme.length})`)}if(i.path){if(i.authority){if(!CR.test(i.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(TR.test(i.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function wR(i,t){return!i&&!t?"file":i}function RR(i,t){switch(i){case"https":case"http":case"file":t?t[0]!==In&&(t=In+t):t=In;break}return t}var Pe="",In="/",ER=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,y=class i{static isUri(t){return t instanceof i?!0:!t||typeof t!="object"?!1:typeof t.authority=="string"&&typeof t.fragment=="string"&&typeof t.path=="string"&&typeof t.query=="string"&&typeof t.scheme=="string"&&typeof t.fsPath=="string"&&typeof t.with=="function"&&typeof t.toString=="function"}constructor(t,e,n,r,o,s=!1){typeof t=="object"?(this.scheme=t.scheme||Pe,this.authority=t.authority||Pe,this.path=t.path||Pe,this.query=t.query||Pe,this.fragment=t.fragment||Pe):(this.scheme=wR(t,s),this.authority=e||Pe,this.path=RR(this.scheme,n||Pe),this.query=r||Pe,this.fragment=o||Pe,xR(this,s))}get fsPath(){return ka(this,!1)}with(t){if(!t)return this;let{scheme:e,authority:n,path:r,query:o,fragment:s}=t;return e===void 0?e=this.scheme:e===null&&(e=Pe),n===void 0?n=this.authority:n===null&&(n=Pe),r===void 0?r=this.path:r===null&&(r=Pe),o===void 0?o=this.query:o===null&&(o=Pe),s===void 0?s=this.fragment:s===null&&(s=Pe),e===this.scheme&&n===this.authority&&r===this.path&&o===this.query&&s===this.fragment?this:new Gr(e,n,r,o,s)}static parse(t,e=!1){let n=ER.exec(t);return n?new Gr(n[2]||Pe,Pd(n[4]||Pe),Pd(n[5]||Pe),Pd(n[7]||Pe),Pd(n[9]||Pe),e):new Gr(Pe,Pe,Pe,Pe,Pe)}static file(t){let e=Pe;if(G&&(t=t.replace(/\\/g,In)),t[0]===In&&t[1]===In){let n=t.indexOf(In,2);n===-1?(e=t.substring(2),t=In):(e=t.substring(2,n),t=t.substring(n)||In)}return new Gr("file",e,t,Pe,Pe)}static from(t,e){return new Gr(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 G&&t.scheme==="file"?n=i.file(le.join(ka(t,!0),...e)).path:n=Z.join(t.path,...e),t.with({path:n})}toString(t=!1){return bg(this,t)}toJSON(){return this}static revive(t){if(t){if(t instanceof i)return t;{let e=new Gr(t);return e._formatted=t.external??null,e._fsPath=t._sep===vS?t.fsPath??null:null,e}}else return t}[Symbol.for("debug.description")](){return`URI(${this.toString()})`}};function yS(i){return!i||typeof i!="object"?!1:typeof i.scheme=="string"&&(typeof i.authority=="string"||typeof i.authority>"u")&&(typeof i.path=="string"||typeof i.path>"u")&&(typeof i.query=="string"||typeof i.query>"u")&&(typeof i.fragment=="string"||typeof i.fragment>"u")}var vS=G?1:void 0,Gr=class extends y{constructor(){super(...arguments);this._formatted=null;this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=ka(this,!1)),this._fsPath}toString(e=!1){return e?bg(this,!0):(this._formatted||(this._formatted=bg(this,!1)),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=vS),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}},SS={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 mS(i,t,e){let n,r=-1;for(let o=0;o<i.length;o++){let s=i.charCodeAt(o);if(s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||s===45||s===46||s===95||s===126||t&&s===47||e&&s===91||e&&s===93||e&&s===58)r!==-1&&(n+=encodeURIComponent(i.substring(r,o)),r=-1),n!==void 0&&(n+=i.charAt(o));else{n===void 0&&(n=i.substr(0,o));let a=SS[s];a!==void 0?(r!==-1&&(n+=encodeURIComponent(i.substring(r,o)),r=-1),n+=a):r===-1&&(r=o)}}return r!==-1&&(n+=encodeURIComponent(i.substring(r))),n!==void 0?n:i}function PR(i){let t;for(let e=0;e<i.length;e++){let n=i.charCodeAt(e);n===35||n===63?(t===void 0&&(t=i.substr(0,e)),t+=SS[n]):t!==void 0&&(t+=i[e])}return t!==void 0?t:i}function ka(i,t){let e;return i.authority&&i.path.length>1&&i.scheme==="file"?e=`//${i.authority}${i.path}`:i.path.charCodeAt(0)===47&&(i.path.charCodeAt(1)>=65&&i.path.charCodeAt(1)<=90||i.path.charCodeAt(1)>=97&&i.path.charCodeAt(1)<=122)&&i.path.charCodeAt(2)===58?t?e=i.path.substr(1):e=i.path[1].toLowerCase()+i.path.substr(2):e=i.path,G&&(e=e.replace(/\//g,"\\")),e}function bg(i,t){let e=t?PR:mS,n="",{scheme:r,authority:o,path:s,query:a,fragment:l}=i;if(r&&(n+=r,n+=":"),(o||r==="file")&&(n+=In,n+=In),o){let d=o.indexOf("@");if(d!==-1){let c=o.substr(0,d);o=o.substr(d+1),d=c.lastIndexOf(":"),d===-1?n+=e(c,!1,!1):(n+=e(c.substr(0,d),!1,!1),n+=":",n+=e(c.substr(d+1),!1,!0)),n+="@"}o=o.toLowerCase(),d=o.lastIndexOf(":"),d===-1?n+=e(o,!1,!0):(n+=e(o.substr(0,d),!1,!0),n+=o.substr(d))}if(s){if(s.length>=3&&s.charCodeAt(0)===47&&s.charCodeAt(2)===58){let d=s.charCodeAt(1);d>=65&&d<=90&&(s=`/${String.fromCharCode(d+32)}:${s.substr(3)}`)}else if(s.length>=2&&s.charCodeAt(1)===58){let d=s.charCodeAt(0);d>=65&&d<=90&&(s=`${String.fromCharCode(d+32)}:${s.substr(2)}`)}n+=e(s,!0,!1)}return a&&(n+="?",n+=e(a,!1,!1)),l&&(n+="#",n+=t?l:mS(l,!1,!1)),n}function bS(i){try{return decodeURIComponent(i)}catch{return i.length>3?i.substr(0,3)+bS(i.substr(3)):i}}var hS=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function Pd(i){return i.match(hS)?i.replace(hS,t=>bS(t)):i}var ie;(te=>(te.inMemory="inmemory",te.vscode="vscode",te.internal="private",te.walkThrough="walkThrough",te.walkThroughSnippet="walkThroughSnippet",te.http="http",te.https="https",te.file="file",te.mailto="mailto",te.untitled="untitled",te.data="data",te.command="command",te.vscodeRemote="vscode-remote",te.vscodeRemoteResource="vscode-remote-resource",te.vscodeManagedRemoteResource="vscode-managed-remote-resource",te.vscodeUserData="vscode-userdata",te.vscodeCustomEditor="vscode-custom-editor",te.vscodeNotebookCell="vscode-notebook-cell",te.vscodeNotebookCellMetadata="vscode-notebook-cell-metadata",te.vscodeNotebookCellMetadataDiff="vscode-notebook-cell-metadata-diff",te.vscodeNotebookCellOutput="vscode-notebook-cell-output",te.vscodeNotebookCellOutputDiff="vscode-notebook-cell-output-diff",te.vscodeNotebookMetadata="vscode-notebook-metadata",te.vscodeInteractiveInput="vscode-interactive-input",te.vscodeSettings="vscode-settings",te.vscodeWorkspaceTrust="vscode-workspace-trust",te.vscodeTerminal="vscode-terminal",te.vscodeImageCarousel="vscode-image-carousel",te.vscodeChatCodeBlock="vscode-chat-code-block",te.vscodeChatCodeCompareBlock="vscode-chat-code-compare-block",te.vscodeChatEditor="vscode-chat-editor",te.vscodeChatInput="chatSessionInput",te.vscodeLocalChatSession="vscode-chat-session",te.webviewPanel="webview-panel",te.vscodeWebview="vscode-webview",te.vscodeBrowser="vscode-browser",te.extension="extension",te.vscodeFileResource="vscode-file",te.tmp="tmp",te.vsls="vsls",te.vscodeSourceControl="vscode-scm",te.commentsInput="comment",te.codeSetting="code-setting",te.outputChannel="output",te.accessibleView="accessible-view",te.chatEditingSnapshotScheme="chat-editing-snapshot-text-model",te.chatEditingModel="chat-editing-text-model",te.copilotPr="copilot-pr"))(ie||={});var Tg="tkn",_g=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??"/",kR(t))}getServerRootPath(){return this._serverRootPath}get _remoteResourcesPath(){return Z.join(this._serverRootPath,ie.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 lv(a),t}let e=t.authority,n=this._hosts[e];n&&n.indexOf(":")!==-1&&n.indexOf("[")===-1&&(n=`[${n}]`);let r=this._ports[e],o=this._connectionTokens[e],s=`path=${encodeURIComponent(t.path)}`;return typeof o=="string"&&(s+=`&${Tg}=${encodeURIComponent(o)}`),y.from({scheme:Et?this._preferredWebSchema:ie.vscodeRemoteResource,authority:`${n}:${r}`,path:Et?(window.location.pathname+"/"+this._remoteResourcesPath).replace(/\/\/+/g,"/"):this._remoteResourcesPath,query:s})}},AR=new _g;function kR(i){return`${i.quality??"oss"}-${i.commit??"dev"}`}var IS="vs/../../node_modules",_S="vs/../../node_modules.asar";var xg="vscode-app",Cg=class i{static{this.FALLBACK_AUTHORITY=xg}asBrowserUri(t){let e=this.toUri(t);return this.uriToBrowserUri(e)}uriToBrowserUri(t){return t.scheme===ie.vscodeRemote?AR.rewrite(t):t.scheme===ie.file&&(Lv||Nv===`${ie.vscodeFileResource}://${i.FALLBACK_AUTHORITY}`)?t.with({scheme:ie.vscodeFileResource,authority:t.authority||i.FALLBACK_AUTHORITY,query:null,fragment:null}):t}asFileUri(t){let e=this.toUri(t);return this.uriToFileUri(e)}uriToFileUri(t){return t.scheme===ie.vscodeFileResource?t.with({scheme:ie.file,authority:t.authority!==i.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=W(e,t);return y.file(n)}throw new Error("Cannot determine URI for module id!")}},dt=new Cg,$4=Object.freeze({"Cache-Control":"no-cache, no-store"}),H4=Object.freeze({"Document-Policy":"include-js-call-stacks-in-crash-reports"}),DR;(o=>{let i=new Map([["1",{"Cross-Origin-Opener-Policy":"same-origin"}],["2",{"Cross-Origin-Embedder-Policy":"require-corp"}],["3",{"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"require-corp"}]]);o.CoopAndCoep=Object.freeze(i.get("3"));let e="vscode-coi";function n(s){let a;typeof s=="string"?a=new URL(s).searchParams:s instanceof URL?a=s.searchParams:y.isUri(s)&&(a=new URL(s.toString(!0)).searchParams);let l=a?.get(e);if(l)return i.get(l)}o.getHeadersFromQuery=n;function r(s,a,l){if(!globalThis.crossOriginIsolated)return;let d=a&&l?"3":l?"2":"1";s instanceof URLSearchParams?s.set(e,d):s[e]=d}o.addSearchParam=r})(DR||={});function ur(i){return ka(i,!0)}var Da=class{constructor(t){this._ignorePathCasing=t}compare(t,e,n=!1){return t===e?0:lr(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===ie.file)return cr(ur(t),ur(e),this._ignorePathCasing(t))&&t.query===e.query&&(n||t.fragment===e.fragment);if(CS(t.authority,e.authority))return cr(t.path,e.path,this._ignorePathCasing(t),!0)&&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===ie.file?e=y.file(se(ur(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===ie.file?e=y.file(Ft(ur(t))).path:e=Z.normalize(t.path),t.with({path:e})}relativePath(t,e){if(t.scheme!==e.scheme||!CS(t.authority,e.authority))return;if(t.scheme===ie.file){let o=Jv(ur(t),ur(e));return G?Ed(o):o}let n=t.path||"/",r=e.path||"/";if(this._ignorePathCasing(t)){let o=0;for(let s=Math.min(n.length,r.length);o<s&&!(n.charCodeAt(o)!==r.charCodeAt(o)&&n.charAt(o).toLowerCase()!==r.charAt(o).toLowerCase());o++);n=r.substr(0,o)+n.substr(o)}return Z.relative(n,r)}resolvePath(t,e){if(t.scheme===ie.file){let n=y.file(dn(ur(t),e));return t.with({authority:n.authority,path:n.path})}return e=cS(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&&dr(t,e)}hasTrailingPathSeparator(t,e=be){if(t.scheme===ie.file){let n=ur(t);return n.length>vg(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=be){return TS(t,e)?t.with({path:t.path.substr(0,t.path.length-1)}):t}addTrailingPathSeparator(t,e=be){let n=!1;if(t.scheme===ie.file){let r=ur(t);n=r!==void 0&&r.length===vg(r).length&&r[r.length-1]===e}else{e="/";let r=t.path;n=r.length===1&&r.charCodeAt(r.length-1)===47}return!n&&!TS(t,e)?t.with({path:t.path+"/"}):t}},ae=new Da(()=>!1),Je=new Da(i=>i.scheme===ie.file?!Se:!0),wg=new Da(i=>!0),Eo=ae.isEqual.bind(ae),Oa=ae.isEqualOrParent.bind(ae),G4=ae.getComparisonKey.bind(ae),J4=ae.basenameOrAuthority.bind(ae),pe=ae.basename.bind(ae),Ma=ae.extname.bind(ae),pr=ae.dirname.bind(ae),X=ae.joinPath.bind(ae),en=ae.normalizePath.bind(ae),Rg=ae.relativePath.bind(ae),Y4=ae.resolvePath.bind(ae),xS=ae.isAbsolutePath.bind(ae),CS=ae.isEqualAuthority.bind(ae),TS=ae.hasTrailingPathSeparator.bind(ae),Q4=ae.removeTrailingPathSeparator.bind(ae),X4=ae.addTrailingPathSeparator.bind(ae);var OR;(o=>{o.META_DATA_LABEL="label",o.META_DATA_DESCRIPTION="description",o.META_DATA_SIZE="size",o.META_DATA_MIME="mime";function r(s){let a=new Map;s.path.substring(s.path.indexOf(";")+1,s.path.lastIndexOf(";")).split(";").forEach(c=>{let[u,p]=c.split(":");u&&p&&a.set(u,p)});let d=s.path.substring(0,s.path.indexOf(";"));return d&&a.set(o.META_DATA_MIME,d),a}o.parseMetaData=r})(OR||={});var wS=Symbol("MicrotaskDelay");function Md(i){return!!i&&typeof i.then=="function"}function Qr(i){let t=new je,e=i(t.token),n=!1,r=new Promise((o,s)=>{let a=t.token.onCancellationRequested(()=>{n=!0,a.dispose(),s(new K)});Promise.resolve(e).then(l=>{a.dispose(),t.dispose(),n?So(l)&&l.dispose():o(l)},l=>{a.dispose(),t.dispose(),s(l)})});return new class{cancel(){t.cancel(),t.dispose()}then(o,s){return r.then(o,s)}catch(o){return this.then(void 0,o)}finally(o){return r.finally(o)}}}function PS(i){let t=-1,e=i.map((r,o)=>r.then(s=>(t=o,s))),n=Promise.race(e);return n.cancel=()=>{i.forEach((r,o)=>{o!==t&&r.cancel&&r.cancel()})},n.finally(()=>{n.cancel()}),n}var Eg=class{constructor(){this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null,this.cancellationTokenSource=new je}queue(t){if(this.cancellationTokenSource.token.isCancellationRequested)return Promise.reject(new Error("Throttler is disposed"));if(this.activePromise){if(this.queuedPromiseFactory=t,!this.queuedPromise){let e=()=>{if(this.queuedPromise=null,this.cancellationTokenSource.token.isCancellationRequested)return;let n=this.queue(this.queuedPromiseFactory);return this.queuedPromiseFactory=null,n};this.queuedPromise=new Promise(n=>{this.activePromise.then(e,e).then(n)})}return new Promise((e,n)=>{this.queuedPromise.then(e,n)})}return this.activePromise=t(this.cancellationTokenSource.token),new Promise((e,n)=>{this.activePromise.then(r=>{this.activePromise=null,e(r)},r=>{this.activePromise=null,n(r)})})}dispose(){this.cancellationTokenSource.cancel()}};var nt=class{constructor(){this.promiseMap=new Map}queue(t,e){let r=(this.promiseMap.get(t)??Promise.resolve()).catch(()=>{}).then(e).finally(()=>{this.promiseMap.get(t)===r&&this.promiseMap.delete(t)});return this.promiseMap.set(t,r),r}peek(t){return this.promiseMap.get(t)||void 0}keys(){return this.promiseMap.keys()}},LR=(i,t)=>{let e=!0,n=setTimeout(()=>{e=!1,t()},i);return{isTriggered:()=>e,dispose:()=>{clearTimeout(n),e=!1}}},NR=i=>{let t=!0;return queueMicrotask(()=>{t&&(t=!1,i())}),{isTriggered:()=>t,dispose:()=>{t=!1}}},Ni=class{constructor(t){this.defaultDelay=t;this.deferred=null,this.completionPromise=null,this.doResolve=null,this.doReject=null,this.task=null}trigger(t,e=this.defaultDelay){this.task=t,this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise((r,o)=>{this.doResolve=r,this.doReject=o}).then(()=>{if(this.completionPromise=null,this.doResolve=null,this.task){let r=this.task;return this.task=null,r()}}));let n=()=>{this.deferred=null,this.doResolve?.(null)};return this.deferred=e===wS?NR(n):LR(e,n),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject?.(new K),this.completionPromise=null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}},Ui=class{constructor(t){this.delayer=new Ni(t),this.throttler=new Eg}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()}},kd=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 _n(i,t){return t?new Promise((e,n)=>{let r=setTimeout(()=>{o.dispose(),e()},i),o=t.onCancellationRequested(()=>{clearTimeout(r),o.dispose(),n(new K)})}):Qr(e=>_n(i,e))}function $t(i,t=0,e){let n=setTimeout(()=>{i(),e&&r.dispose()},t),r=k(()=>{clearTimeout(n),e?.delete(r)});return e?.add(r),r}var Po=class{constructor(t){this._size=0;this._isDisposed=!1;this.maxDegreeOfParalellism=t,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new w}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()}},Jr=class extends Po{constructor(){super(1)}};var Ao=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 Ie;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=ae){let n=e.getComparisonKey(t);return this.queues.get(n)?.size??0}queueFor(t,e,n=ae){let r=n.getComparisonKey(t),o=this.queues.get(r);if(!o){o=new Jr;let s=this.drainListenerCount++,a=Q.once(o.onDrained)(()=>{o?.dispose(),this.queues.delete(r),this.onDidQueueDrain(),this.drainListeners?.deleteAndDispose(s),this.drainListeners?.size===0&&(this.drainListeners.dispose(),this.drainListeners=void 0)});this.drainListeners||(this.drainListeners=new ve),this.drainListeners.set(s,a),this.queues.set(r,o)}return o.queue(e)}onDidQueueDrain(){this.isDrained()&&this.releaseDrainers()}releaseDrainers(){for(let t of this.drainers)t.complete();this.drainers.clear()}dispose(){for(let[,t]of this.queues)t.dispose();this.queues.clear(),this.releaseDrainers(),this.drainListeners?.dispose()}};var Yr=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 Dd=class extends Yr{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()}},ko=class extends T{constructor(e,n){super();this.options=e;this.handler=n;this.pendingWork=[];this.throttler=this._register(new vt);this.disposed=!1;this.lastExecutionTime=0}get pending(){return this.pendingWork.length}work(e){if(this.disposed)return!1;if(typeof this.options.maxBufferedWork=="number"){if(this.throttler.value){if(this.pending+e.length>this.options.maxBufferedWork)return!1}else if(this.pending+e.length-this.options.maxWorkChunkSize>this.options.maxBufferedWork)return!1}for(let r of e)this.pendingWork.push(r);let n=Date.now()-this.lastExecutionTime;return!this.throttler.value&&(!this.options.waitThrottleDelayBetweenWorkUnits||n>=this.options.throttleDelay)?this.doWork():!this.throttler.value&&this.options.waitThrottleDelayBetweenWorkUnits&&this.scheduleThrottler(Math.max(this.options.throttleDelay-n,0)),!0}doWork(){this.lastExecutionTime=Date.now(),this.handler(this.pendingWork.splice(0,this.options.maxWorkChunkSize)),this.pendingWork.length>0&&this.scheduleThrottler()}scheduleThrottler(e=this.options.throttleDelay){this.throttler.value=new Yr(()=>{this.throttler.clear(),this.doWork()},e),this.throttler.value.schedule()}dispose(){super.dispose(),this.pendingWork.length=0,this.disposed=!0}},UR,Ad;(function(){let i=globalThis;typeof i.requestIdleCallback!="function"||typeof i.cancelIdleCallback!="function"?Ad=(t,e,n)=>{Uv(()=>{if(r)return;let o=Date.now()+15;e(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,o-Date.now())}}))});let r=!1;return{dispose(){r||(r=!0)}}}:Ad=(t,e,n)=>{let r=t.requestIdleCallback(e,typeof n=="number"?{timeout:n}:void 0),o=!1;return{dispose(){o||(o=!0,t.cancelIdleCallback(r))}}},UR=(t,e)=>Ad(globalThis,t,e)})();var Pg=class{constructor(t,e){this._didRun=!1;this._executor=()=>{try{this._value=e()}catch(n){this._error=n}finally{this._didRun=!0}},this._handle=Ad(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}},Od=class extends Pg{constructor(t){super(globalThis,t)}};async function AS(i,t,e){let n;for(let r=0;r<e;r++)try{return await i()}catch(o){n=o,await _n(t)}throw n}var Ie=class i{static fromPromise(t){let e=new i;return e.settleWith(t),e}get isRejected(){return this.outcome?.outcome===1}get isResolved(){return this.outcome?.outcome===0}get isSettled(){return!!this.outcome}get value(){return this.outcome?.outcome===0?this.outcome?.value:void 0}constructor(){this.p=new Promise((t,e)=>{this.completeCallback=t,this.errorCallback=e})}complete(t){return this.isSettled?Promise.resolve():new Promise(e=>{this.completeCallback(t),this.outcome={outcome:0,value:t},e()})}error(t){return this.isSettled?Promise.resolve():new Promise(e=>{this.errorCallback(t),this.outcome={outcome:1,value:t},e()})}settleWith(t){return t.then(e=>this.complete(e),e=>this.error(e))}cancel(){return this.error(new K)}},Cn;(e=>{async function i(n){let r,o=await Promise.all(n.map(s=>s.then(a=>a,a=>{r||(r=a)})));if(typeof r<"u")throw r;return o}e.settled=i;function t(n){return new Promise(async(r,o)=>{try{await n(r,o)}catch(s){o(s)}})}e.withAsyncBody=t})(Cn||={});var RS=class i{static fromArray(t){return new i(e=>{e.emitMany(t)})}static fromPromise(t){return new i(async e=>{e.emitMany(await t)})}static fromPromisesResolveOrder(t){return new i(async e=>{await Promise.all(t.map(async n=>e.emitOne(await n)))})}static merge(t){return new i(async e=>{await Promise.all(t.map(async n=>{for await(let r of n)e.emitOne(r)}))})}static{this.EMPTY=i.fromArray([])}constructor(t,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new w,queueMicrotask(async()=>{let n={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(n)),this.resolve()}catch(r){this.reject(r)}finally{n.emitOne=void 0,n.emitMany=void 0,n.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await Q.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,e){return new i(async n=>{for await(let r of t)n.emitOne(e(r))})}map(t){return i.map(this,t)}static filter(t,e){return new i(async n=>{for await(let r of t)e(r)&&n.emitOne(r)})}filter(t){return i.filter(this,t)}static coalesce(t){return i.filter(t,e=>!!e)}coalesce(){return i.coalesce(this)}static async toPromise(t){let e=[];for await(let n of t)e.push(n);return e}toPromise(){return i.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};var Ag=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 De("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 Ie;return this._unsatisfiedConsumers.push(t),t.p}}},ES=class i{constructor(t,e){this._onReturn=e;this._producerConsumer=new Ag;this._iterator={next:()=>this._producerConsumer.consume(),return:()=>(this._onReturn?.(),Promise.resolve({done:!0,value:void 0})),throw:async t=>(this._finishError(t),{done:!0,value:void 0})};queueMicrotask(async()=>{let n=t({emitOne:r=>this._producerConsumer.produce({ok:!0,value:{done:!1,value:r}}),emitMany:r=>{for(let o of r)this._producerConsumer.produce({ok:!0,value:{done:!1,value:o}})},reject:r=>this._finishError(r)});if(!this._producerConsumer.hasFinalValue)try{await n,this._finishOk()}catch(r){this._finishError(r)}})}static fromArray(t){return new i(e=>{e.emitMany(t)})}static fromPromise(t){return new i(async e=>{e.emitMany(await t)})}static fromPromisesResolveOrder(t){return new i(async e=>{await Promise.all(t.map(async n=>e.emitOne(await n)))})}static merge(t){return new i(async e=>{await Promise.all(t.map(async n=>{for await(let r of n)e.emitOne(r)}))})}static{this.EMPTY=i.fromArray([])}static map(t,e){return new i(async n=>{for await(let r of t)n.emitOne(e(r))})}static tee(t){let e,n,r=new Ie,o=async()=>{if(!(!e||!n))try{for await(let l of t)e.emitOne(l),n.emitOne(l)}catch(l){e.reject(l),n.reject(l)}finally{r.complete()}},s=new i(async l=>(e=l,o(),r.p)),a=new i(async l=>(n=l,o(),r.p));return[s,a]}map(t){return i.map(this,t)}static coalesce(t){return i.filter(t,e=>!!e)}coalesce(){return i.coalesce(this)}static filter(t,e){return new i(async n=>{for await(let r of t)e(r)&&n.emitOne(r)})}filter(t){return i.filter(this,t)}_finishOk(){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!0,value:{done:!0,value:void 0}})}_finishError(t){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!1,error:t})}[Symbol.asyncIterator](){return this._iterator}};function La(i){let t=i;return t?[t.on,t.pause,t.resume,t.destroy].every(e=>typeof e=="function"):!1}function Ld(i){let t=i;return t?La(t.stream)&&Array.isArray(t.buffer)&&typeof t.ended=="boolean":!1}function fr(i,t){return new kg(i,t)}var kg=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?ze(t):this.listeners.error.slice(0).forEach(e=>e(t))}emitEnd(){this.listeners.end.slice(0).forEach(t=>t())}on(t,e){if(!this.state.destroyed)switch(t){case"data":this.listeners.data.push(e),this.resume();break;case"end":this.listeners.end.push(e),this.state.flowing&&this.flowEnd()&&this.destroy();break;case"error":this.listeners.error.push(e),this.state.flowing&&this.flowErrors();break}}removeListener(t,e){if(this.state.destroyed)return;let n;switch(t){case"data":n=this.listeners.data;break;case"end":n=this.listeners.end;break;case"error":n=this.listeners.error;break}if(n){let r=n.indexOf(e);r>=0&&n.splice(r,1)}}flowData(){if(this.buffer.data.length===0)return;if(typeof this.reducer=="function"){let e=this.reducer(this.buffer.data);this.emitData(e)}else for(let e of this.buffer.data)this.emitData(e);this.buffer.data.length=0;let t=[...this.pendingWritePromises];this.pendingWritePromises.length=0,t.forEach(e=>e())}flowErrors(){if(this.listeners.error.length>0){for(let t of this.buffer.error)this.emitError(t);this.buffer.error.length=0}}flowEnd(){return this.state.ended?(this.emitEnd(),this.listeners.end.length>0):!1}destroy(){this.state.destroyed||(this.state.destroyed=!0,this.state.ended=!0,this.buffer.data.length=0,this.buffer.error.length=0,this.listeners.data.length=0,this.listeners.error.length=0,this.listeners.end.length=0,this.pendingWritePromises.length=0)}};function kS(i,t){let e=[],n;for(;(n=i.read())!==null;)e.push(n);return t(e)}function DS(i,t,e){let n=[],r;for(;(r=i.read())!==null&&n.length<e;)n.push(r);return r===null&&n.length>0?t(n):{read:()=>{if(n.length>0)return n.shift();if(typeof r<"u"){let o=r;return r=void 0,o}return i.read()}}}function Nd(i,t){return new Promise((e,n)=>{let r=[];Ud(i,{onData:o=>{t&&r.push(o)},onError:o=>{t?n(o):e(void 0)},onEnd:()=>{e(t?t(r):void 0)}})})}function Ud(i,t,e){i.on("error",n=>{e?.isCancellationRequested||t.onError(n)}),i.on("end",()=>{e?.isCancellationRequested||t.onEnd()}),i.on("data",n=>{e?.isCancellationRequested||t.onData(n)})}function OS(i,t){return new Promise((e,n)=>{let r=new z,o=[],s=d=>{if(o.push(d),o.length>t)return r.dispose(),i.pause(),e({stream:i,buffer:o,ended:!1})},a=d=>(r.dispose(),n(d)),l=()=>(r.dispose(),e({stream:i,buffer:o,ended:!0}));r.add(k(()=>i.removeListener("error",a))),i.on("error",a),r.add(k(()=>i.removeListener("end",l))),i.on("end",l),r.add(k(()=>i.removeListener("data",s))),i.on("data",s)})}function MS(i){let t=!1;return{read:()=>t?null:(t=!0,i)}}function Fd(i,t,e){let n=fr(e);return Ud(i,{onData:r=>n.write(t.data(r)),onError:r=>n.error(t.error?t.error(r):r),onEnd:()=>n.end()}),n}var Na=typeof Buffer<"u",WR=new Le(()=>new Uint8Array(256)),Dg,Og,A=class i{static alloc(t){return Na?new i(Buffer.allocUnsafe(t)):new i(new Uint8Array(t))}static wrap(t){return Na&&!Buffer.isBuffer(t)&&(t=Buffer.from(t.buffer,t.byteOffset,t.byteLength)),new i(t)}static fromString(t,e){return!(e?.dontUseNodeBuffer||!1)&&Na?new i(Buffer.from(t)):(Dg||(Dg=new TextEncoder),new i(Dg.encode(t)))}static fromByteArray(t){let e=i.alloc(t.length);for(let n=0,r=t.length;n<r;n++)e.buffer[n]=t[n];return e}static concat(t,e){if(typeof e>"u"){e=0;for(let o=0,s=t.length;o<s;o++)e+=t[o].byteLength}let n=i.alloc(e),r=0;for(let o=0,s=t.length;o<s;o++){let a=t[o];n.set(a,r),r+=a.byteLength}return n}static isNativeBuffer(t){return Na&&Buffer.isBuffer(t)}constructor(t){this.buffer=t,this.byteLength=this.buffer.byteLength}clone(){let t=i.alloc(this.byteLength);return t.set(this),t}toString(){return Na?this.buffer.toString():(Og||(Og=new TextDecoder(void 0,{ignoreBOM:!0})),Og.decode(this.buffer))}slice(t,e){return new i(this.buffer.subarray(t,e))}set(t,e){if(t instanceof i)this.buffer.set(t.buffer,e);else if(t instanceof Uint8Array)this.buffer.set(t,e);else if(t instanceof ArrayBuffer)this.buffer.set(new Uint8Array(t),e);else if(ArrayBuffer.isView(t))this.buffer.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),e);else throw new Error("Unknown argument 'array'")}readUInt32BE(t){return HR(this.buffer,t)}writeUInt32BE(t,e){qR(this.buffer,t,e)}readUInt32LE(t){return BR(this.buffer,t)}writeUInt32LE(t,e){VR(this.buffer,t,e)}readUInt8(t){return zR(this.buffer,t)}writeUInt8(t,e){jR(this.buffer,t,e)}indexOf(t,e=0){return $R(this.buffer,t instanceof i?t.buffer:t,e)}equals(t){return this===t?!0:this.byteLength!==t.byteLength?!1:this.buffer.every((e,n)=>e===t.buffer[n])}};function $R(i,t,e=0){let n=t.byteLength,r=i.byteLength;if(n===0)return 0;if(n===1)return i.indexOf(t[0],e);if(n>r-e)return-1;let o=WR.value;o.fill(t.length);for(let d=0;d<t.length;d++)o[t[d]]=t.length-d-1;let s=e+t.length-1,a=s,l=-1;for(;s<r;)if(i[s]===t[a]){if(a===0){l=s;break}s--,a--}else s+=Math.max(t.length-a,o[i[s]]),a=t.length-1;return l}function HR(i,t){return i[t]*2**24+i[t+1]*2**16+i[t+2]*2**8+i[t+3]}function qR(i,t,e){i[e+3]=t,t=t>>>8,i[e+2]=t,t=t>>>8,i[e+1]=t,t=t>>>8,i[e]=t}function BR(i,t){return i[t+0]<<0>>>0|i[t+1]<<8>>>0|i[t+2]<<16>>>0|i[t+3]<<24>>>0}function VR(i,t,e){i[e+0]=t&255,t=t>>>8,i[e+1]=t&255,t=t>>>8,i[e+2]=t&255,t=t>>>8,i[e+3]=t&255}function zR(i,t){return i[t]}function jR(i,t,e){i[e]=t}function US(i){return kS(i,t=>A.concat(t))}function FS(i){return MS(i)}function Xr(i){return Nd(i,t=>A.concat(t))}async function WS(i){return i.ended?A.concat(i.buffer):A.concat([...i.buffer,await Xr(i.stream)])}function $S(i){return Fd(i,{data:t=>typeof t=="string"?A.fromString(t):A.wrap(t)},t=>A.concat(t))}function HS(i){return fr(t=>A.concat(t),i)}function Ln(i){let t=0,e=0,n=0,r=new Uint8Array(Math.floor(i.length/4*3)),o=a=>{switch(e){case 3:r[n++]=t|a,e=0;break;case 2:r[n++]=t|a>>>2,t=a<<6,e=3;break;case 1:r[n++]=t|a>>>4,t=a<<4,e=2;break;default:t=a<<2,e=1}};for(let a=0;a<i.length;a++){let l=i.charCodeAt(a);if(l>=65&&l<=90)o(l-65);else if(l>=97&&l<=122)o(l-97+26);else if(l>=48&&l<=57)o(l-48+52);else if(l===43||l===45)o(62);else if(l===47||l===95)o(63);else{if(l===61)break;throw new SyntaxError(`Unexpected base64 character ${i[a]}`)}}let s=n;for(;e>0;)o(0);return A.wrap(r).slice(0,s)}var KR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",GR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Fi({buffer:i},t=!0,e=!1){let n=e?GR:KR,r="",o=i.byteLength%3,s=0;for(;s<i.byteLength-o;s+=3){let a=i[s+0],l=i[s+1],d=i[s+2];r+=n[a>>>2],r+=n[(a<<4|l>>>4)&63],r+=n[(l<<2|d>>>6)&63],r+=n[d&63]}if(o===1){let a=i[s+0];r+=n[a>>>2],r+=n[a<<4&63],t&&(r+="==")}else if(o===2){let a=i[s+0],l=i[s+1];r+=n[a>>>2],r+=n[(a<<4|l>>>4)&63],r+=n[l<<2&63],t&&(r+="=")}return r}var LS="0123456789abcdef";function Zr({buffer:i}){let t="";for(let e=0;e<i.length;e++){let n=i[e];t+=LS[n>>>4],t+=LS[n&15]}return t}function Mg(i){if(i.length%2!==0)throw new SyntaxError("Hex string must have an even length");let t=new Uint8Array(i.length>>1);for(let e=0;e<i.length;)t[e>>1]=NS(i,e++)<<4|NS(i,e++);return A.wrap(t)}function NS(i,t){let e=i.charCodeAt(t);if(e>=48&&e<=57)return e-48;if(e>=97&&e<=102)return e-87;if(e>=65&&e<=70)return e-55;throw new SyntaxError(`Invalid hex character at position ${t}`)}function ce(i,t,e){let n=null,r=null;if(typeof e.value=="function"?(n="value",r=e.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof e.get=="function"&&(n="get",r=e.get),!r)throw new Error("not supported");let o=`$memoize$${t}`;e[n]=function(...s){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,s)}),this[o]}}function Ua(i,t=0){if(!i||t>200)return i;if(typeof i=="object"){switch(i.$mid){case 1:return y.revive(i);case 2:return new RegExp(i.source,i.flags);case 17:return new Date(i.source)}if(i instanceof A||i instanceof Uint8Array)return i;if(Array.isArray(i))for(let e=0;e<i.length;++e)i[e]=Ua(i[e],t+1);else for(let e in i)Object.hasOwnProperty.call(i,e)&&(i[e]=Ua(i[e],t+1))}return i}function Mo(i){switch(i){case 100:return"req";case 101:return"cancel";case 102:return"subscribe";case 103:return"unsubscribe"}}function Wd(i){switch(i){case 200:return"init";case 201:return"reply:";case 202:case 203:return"replyErr:";case 204:return"event:"}}function Do(i){let t=0;for(let e=0;;e+=7){let n=i.read(1);if(t|=(n.buffer[0]&127)<<e,!(n.buffer[0]&128))return t}}var JR=ei(0);function Oo(i,t){if(t===0){i.write(JR);return}let e=0;for(let r=t;r!==0;r=r>>>7)e++;let n=A.alloc(e);for(let r=0;t!==0;r++)n.buffer[r]=t&127,t=t>>>7,t>0&&(n.buffer[r]|=128);i.write(n)}var Fa=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}},$d=class{constructor(){this.buffers=[]}get buffer(){return A.concat(this.buffers)}write(t){this.buffers.push(t)}dispose(){this.buffers.length=0}};function ei(i){let t=A.alloc(1);return t.writeUInt8(i,0),t}var Wi={Undefined:ei(0),String:ei(1),Buffer:ei(2),VSBuffer:ei(3),Array:ei(4),Object:ei(5),Uint:ei(6)};function Wa(i,t){if(typeof t>"u")i.write(Wi.Undefined);else if(typeof t=="string"){let e=A.fromString(t);i.write(Wi.String),Oo(i,e.byteLength),i.write(e)}else if(A.isNativeBuffer(t)){let e=A.wrap(t);i.write(Wi.Buffer),Oo(i,e.byteLength),i.write(e)}else if(t instanceof A)i.write(Wi.VSBuffer),Oo(i,t.byteLength),i.write(t);else if(Array.isArray(t)){i.write(Wi.Array),Oo(i,t.length);for(let e of t)Wa(i,e)}else if(typeof t=="number"&&(t|0)===t)i.write(Wi.Uint),Oo(i,t);else{let e=A.fromString(JSON.stringify(t));i.write(Wi.Object),Oo(i,e.byteLength),i.write(e)}}function No(i){switch(i.read(1).readUInt8(0)){case 0:return;case 1:return i.read(Do(i)).toString();case 2:return i.read(Do(i)).buffer;case 3:return i.read(Do(i));case 4:{let e=Do(i),n=[];for(let r=0;r<e;r++)n.push(No(i));return n}case 5:return JSON.parse(i.read(Do(i)).toString());case 6:return Do(i)}}var $a=class{constructor(t,e,n=null,r=1e3){this.protocol=t;this.ctx=e;this.logger=n;this.timeoutDelay=r;this.channels=new Map;this.activeRequests=new Map;this.pendingRequests=new Map;this.protocolListener=this.protocol.onMessage(o=>this.onRawMessage(o)),this.sendResponse({type:200})}registerChannel(t,e){this.channels.set(t,e),setTimeout(()=>this.flushPendingRequests(t),0)}sendResponse(t){switch(t.type){case 200:{let e=this.send([t.type]);this.logger?.logOutgoing(e,0,1,Wd(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,Wd(t.type),t.data);return}}}send(t,e=void 0){let n=new $d;try{return Wa(n,t),Wa(n,e),this.sendBuffer(n.buffer)}finally{n.dispose()}}sendBuffer(t){try{return this.protocol.send(t),t.byteLength}catch{return 0}}onRawMessage(t){let e=new Fa(t),n=No(e),r=No(e),o=n[0];switch(o){case 100:return this.logger?.logIncoming(t.byteLength,n[1],1,`${Mo(o)}: ${n[2]}.${n[3]}`,r),this.onPromise({type:o,id:n[1],channelName:n[2],name:n[3],arg:r});case 102:return this.logger?.logIncoming(t.byteLength,n[1],1,`${Mo(o)}: ${n[2]}.${n[3]}`,r),this.onEventListen({type:o,id:n[1],channelName:n[2],name:n[3],arg:r});case 101:return this.logger?.logIncoming(t.byteLength,n[1],1,`${Mo(o)}`),this.disposeActiveRequest({type:o,id:n[1]});case 103:return this.logger?.logIncoming(t.byteLength,n[1],1,`${Mo(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 je,r;try{r=e.call(this.ctx,t.name,t.arg,n.token)}catch(a){r=Promise.reject(a)}let o=t.id;r.then(a=>{this.sendResponse({id:o,data:a,type:201})},a=>{a instanceof Error?this.sendResponse({id:o,data:{message:a.message,name:a.name,stack:a.stack?a.stack.split(`
`):void 0},type:202}):this.sendResponse({id:o,data:a,type:203})}).finally(()=>{s.dispose(),this.activeRequests.delete(t.id)});let s=k(()=>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),Tt(this.activeRequests.values()),this.activeRequests.clear()}};var Lo=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 w;this.onDidInitialize=this._onDidInitialize.event;this.protocolListener=this.protocol.onMessage(n=>this.onBuffer(n)),this.logger=e}getChannel(t){let e=this;return{call(n,r,o){return e.isDisposed?Promise.reject(new K):e.requestPromise(t,n,r,o)},listen(n,r){return e.isDisposed?Q.None:e.requestEvent(t,n,r)}}}requestPromise(t,e,n,r=Ee.None){let o=this.lastRequestId++,a={id:o,type:100,channelName:t,name:e,arg:n};if(r.isCancellationRequested)return Promise.reject(new K);let l,d;return new Promise((u,p)=>{if(r.isCancellationRequested)return p(new K);let m=()=>{let I=b=>{switch(b.type){case 201:this.handlers.delete(o),u(b.data);break;case 202:{this.handlers.delete(o);let S=new Error(b.data.message);S.stack=Array.isArray(b.data.stack)?b.data.stack.join(`
`):b.data.stack,S.name=b.data.name,p(S);break}case 203:this.handlers.delete(o),p(b.data);break}};this.handlers.set(o,I);try{this.sendRequest(a)}catch(b){this.handlers.delete(o),p(b)}},h=null;this.state===1?m():(h=Qr(I=>this.whenInitialized()),h.then(()=>{h=null,m()}));let v=()=>{h?(h.cancel(),h=null):this.sendRequest({id:o,type:101}),p(new K)};l=r.onCancellationRequested(v),d={dispose:fo(()=>{v(),l.dispose()})},this.activeRequests.add(d)}).finally(()=>{l?.dispose(),this.activeRequests.delete(d)})}requestEvent(t,e,n){let r=this.lastRequestId++,s={id:r,type:102,channelName:t,name:e,arg:n},a=null,l=new w({onWillAddFirstListener:()=>{let c=()=>{this.activeRequests.add(l),this.sendRequest(s)};this.state===1?c():(a=Qr(u=>this.whenInitialized()),a.then(()=>{a=null,c()}))},onDidRemoveLastListener:()=>{a?(a.cancel(),a=null):(this.activeRequests.delete(l),this.sendRequest({id:r,type:103})),this.handlers.delete(r)}}),d=c=>l.fire(c.data);return this.handlers.set(r,d),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,`${Mo(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,Mo(t.type));return}}}send(t,e=void 0){let n=new $d;try{return Wa(n,t),Wa(n,e),this.sendBuffer(n.buffer)}finally{n.dispose()}}sendBuffer(t){try{return this.protocol.send(t),t.byteLength}catch{return 0}}onBuffer(t){let e=new Fa(t),n=No(e),r=No(e),o=n[0];switch(o){case 200:return this.logger?.logIncoming(t.byteLength,0,0,Wd(o)),this.onResponse({type:n[0]});case 201:case 202:case 204:case 203:return this.logger?.logIncoming(t.byteLength,n[1],0,Wd(o),r),this.onResponse({type:n[0],id:n[1],data:r})}}onResponse(t){if(t.type===200){this.state=1,this._onDidInitialize.fire();return}this.handlers.get(t.id)?.(t)}get onDidInitializePromise(){return Q.toPromise(this.onDidInitialize)}whenInitialized(){return this.state===1?Promise.resolve():this.onDidInitializePromise}dispose(){this.isDisposed=!0,this.protocolListener&&(this.protocolListener.dispose(),this.protocolListener=null),Tt(this.activeRequests.values()),this.activeRequests.clear(),this._onDidInitialize.dispose()}};x([ce],Lo.prototype,"onDidInitializePromise",1);var Hd=class{constructor(t,e,n){this.channels=new Map;this._connections=new Set;this._onDidAddConnection=new w;this.onDidAddConnection=this._onDidAddConnection.event;this._onDidRemoveConnection=new w;this.onDidRemoveConnection=this._onDidRemoveConnection.event;this.disposables=new z;this.disposables.add(t(({protocol:r,onDidClientDisconnect:o})=>{let s=Q.once(r.onMessage),a=new z,l=s(d=>{let c=new Fa(d),u=No(c),p=new $a(r,u,e,n),m=new Lo(r,e);this.channels.forEach((v,I)=>p.registerChannel(I,v));let h={channelServer:p,channelClient:m,ctx:u};this._connections.add(h),this._onDidAddConnection.fire(h),a.add(o(()=>{p.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(r,o,s){let a;if(xa(e)){let d=uv(n.connections.filter(e));a=d?Promise.resolve(d):Q.toPromise(Q.filter(n.onDidAddConnection,e))}else a=e.routeCall(n,r,o);let l=a.then(d=>d.channelClient.getChannel(t));return qS(l).call(r,o,s)},listen(r,o){if(xa(e))return n.getMulticastEvent(t,e,r,o);let s=e.routeEvent(n,r,o).then(a=>a.channelClient.getChannel(t));return qS(s).listen(r,o)}}}getMulticastEvent(t,e,n,r){let o=this,s,a=new w({onWillAddFirstListener:()=>{s=new z;let l=new _d,d=new Map,c=p=>{let h=p.channelClient.getChannel(t).listen(n,r),v=l.add(h);d.set(p,v)},u=p=>{let m=d.get(p);m&&(m.dispose(),d.delete(p))};o.connections.filter(e).forEach(c),Q.filter(o.onDidAddConnection,e)(c,void 0,s),o.onDidRemoveConnection(u,void 0,s),l.event(a.fire,a,s),s.add(l)},onDidRemoveLastListener:()=>{s?.dispose(),s=void 0}});return o.disposables.add(a),a.event}registerChannel(t,e){this.channels.set(t,e);for(let n of this._connections)n.channelServer.registerChannel(t,e)}dispose(){this.disposables.dispose();for(let t of this._connections)t.channelClient.dispose(),t.channelServer.dispose();this._connections.clear(),this.channels.clear(),this._onDidAddConnection.dispose(),this._onDidRemoveConnection.dispose()}};function qS(i){return{call(t,e,n){return i.then(r=>r.call(t,e,n))},listen(t,e){let n=new Aa;return i.then(r=>n.input=r.listen(t,e)),n.event}}}function BS(i){let t=!1;return{call(e,n,r){return t?i.call(e,n,r):_n(0).then(()=>t=!0).then(()=>i.call(e,n,r))},listen(e,n){if(t)return i.listen(e,n);let r=new Aa;return _n(0).then(()=>t=!0).then(()=>r.input=i.listen(e,n)),r.event}}}var Uo;(r=>{function i(o,s,a){let l=o,d=a?.disableMarshalling,c=new Map;for(let u in l)e(u)&&c.set(u,Q.buffer(l[u],u,!0,void 0,s));return new class{listen(u,p,m){let h=c.get(p);if(h)return h;let v=l[p];if(typeof v=="function"){if(n(p))return v.call(l,m);if(e(p))return c.set(p,Q.buffer(l[p],p,!0,void 0,s)),c.get(p)}throw new Dn(`Event not found: ${p}`)}call(u,p,m){let h=l[p];if(typeof h=="function"){if(!d&&Array.isArray(m))for(let I=0;I<m.length;I++)m[I]=Ua(m[I]);let v=h.apply(l,m);return v instanceof Promise||(v=Promise.resolve(v)),v}throw new Dn(`Method not found: ${p}`)}}}r.fromService=i;function t(o,s){let a=s?.disableMarshalling;return new Proxy({},{get(l,d){if(typeof d=="string")return s?.properties?.has(d)?s.properties.get(d):n(d)?function(c){return o.listen(d,c)}:e(d)?o.listen(d):async function(...c){let u;s&&!bn(s.context)?u=[s.context,...c]:u=c;let p=await o.call(d,u);return a?p:Ua(p)};throw new Dn(`Property not found: ${String(d)}`)}})}r.toService=t;function e(o){return o[0]==="o"&&o[1]==="n"&&mg(o.charCodeAt(2))}function n(o){return/^onDynamic/.test(o)&&mg(o.charCodeAt(9))}})(Uo||={});import{fork as C0}from"child_process";function VS(i){let t=i;return t&&typeof t.type=="string"&&typeof t.severity=="string"}function YR(i){let t=[],e;try{let n=JSON.parse(i.arguments),r=n[n.length-1];r&&r.__$stack&&(n.pop(),e=r.__$stack),t.push(...n)}catch{t.push("Unable to log remote console arguments",i.arguments)}return{args:t,stack:e}}function QR(i){if(!i)return i;let t=i.indexOf(`
`);return t===-1?i:i.substring(0,t)}function zS(i,t){let{args:e,stack:n}=YR(i),r=typeof e[0]=="string"&&e.length===1,o=QR(n);o&&(o=`(${o.trim()})`);let s=[];if(typeof e[0]=="string"?o&&r?s=[`%c[${t}] %c${e[0]} %c${o}`,Fo("blue"),Fo(""),Fo("grey")]:s=[`%c[${t}] %c${e[0]}`,Fo("blue"),Fo(""),...e.slice(1)]:s=[`%c[${t}]%`,Fo("blue"),...e],o&&!r&&s.push(o),typeof console[i.severity]!="function")throw new Error("Unknown console method");console[i.severity].apply(console,s)}function Fo(i){return`color: ${i}`}function cn(i){if(!i||typeof i!="object"||i instanceof RegExp)return i;let t=Array.isArray(i)?[]:{};return Object.entries(i).forEach(([e,n])=>{t[e]=n&&typeof n=="object"?cn(n):n}),t}function jS(i){if(!i||typeof i!="object")return i;let t=[i];for(;t.length>0;){let e=t.shift();Object.freeze(e);for(let n in e)if(KS.call(e,n)){let r=e[n];typeof r=="object"&&!Object.isFrozen(r)&&!_v(r)&&t.push(r)}}return i}var KS=Object.prototype.hasOwnProperty;function Ha(i,t){return Lg(i,t,new Set)}function Lg(i,t,e){if(bn(i))return i;let n=t(i);if(typeof n<"u")return n;if(Array.isArray(i)){let r=[];for(let o of i)r.push(Lg(o,t,e));return r}if(Ue(i)){if(e.has(i))throw new Error("Cannot clone recursive data-structure");e.add(i);let r={};for(let o in i)KS.call(i,o)&&(r[o]=Lg(i[o],t,e));return e.delete(i),r}return i}function Wo(i,t,e=!0){return Ue(i)?(Ue(t)&&Object.keys(t).forEach(n=>{n in i?e&&(Ue(i[n])&&Ue(t[n])?Wo(i[n],t[n],e):i[n]=t[n]):i[n]=t[n]}),i):t}function We(i,t){if(i===t)return!0;if(i==null||t===null||t===void 0||typeof i!=typeof t||typeof i!="object"||Array.isArray(i)!==Array.isArray(t))return!1;let e,n;if(Array.isArray(i)){if(i.length!==t.length)return!1;for(e=0;e<i.length;e++)if(!We(i[e],t[e]))return!1}else{let r=[];for(n in i)r.push(n);r.sort();let o=[];for(n in t)o.push(n);if(o.sort(),!We(r,o))return!1;for(e=0;e<r.length;e++)if(!We(i[r[e]],t[r[e]]))return!1}return!0}function Ng(i){let t=new Set;return JSON.stringify(i,(e,n)=>{if(Ue(n)||Array.isArray(n)){if(t.has(n))return"[Circular]";t.add(n)}return typeof n=="bigint"?`[BigInt ${n.toString()}]`:n})}function gr(i,t){let e=t.toLowerCase(),n=Object.keys(i).find(r=>r.toLowerCase()===e);return n?i[n]:i[t]}import*as b0 from"child_process";import{promises as ib}from"fs";function GS(i){i&&(delete i.DEBUG,delete i.NODE_OPTIONS,Se&&delete i.LD_PRELOAD)}import*as ee from"fs";import{tmpdir as i0}from"os";import{promisify as Ba}from"util";var ZR=new On(1e4);function qa(i){return JS(i,"NFC",ZR)}var e0=new On(1e4);function t0(i){return JS(i,"NFD",e0)}var n0=/[^\u0000-\u0080]/;function JS(i,t,e){if(!i)return i;let n=e.get(i);if(n)return n;let r;return n0.test(i)?r=i.normalize(t):r=i,e.set(i,r),r}var r0=(function(){let i=new On(1e4),t=/[\u0300-\u036f]/g;return function(e){let n=i.get(e);if(n)return n;let r=t0(e).replace(t,""),o=(r.length===e.length?r:e).toLowerCase();return i.set(e,o),o}})();async function XS(i,t=0,e){if(Sg(i))throw new Error("rimraf - will refuse to recursively delete root");return t===0?Ug(i):o0(i,e)}async function o0(i,t=gS(i0())){try{try{await ee.promises.rename(i,t)}catch(e){return e.code==="ENOENT"?void 0:Ug(i)}Ug(t).catch(()=>{})}catch(e){if(e.code!=="ENOENT")throw e}}async function Ug(i){return ee.promises.rm(i,{recursive:!0,force:!0,maxRetries:3})}async function qd(i,t){try{return await YS(i,t)}catch(e){if(e.code==="ENOENT"&&G&&Sg(i))try{return await YS(`${i}.`,t)}catch{}throw e}}async function YS(i,t){return a0(await(t?s0(i):ee.promises.readdir(i)))}async function s0(i){try{return await ee.promises.readdir(i,{withFileTypes:!0})}catch(n){n.code!=="ENOENT"&&console.warn("[node.js fs] readdir with filetypes failed with error: ",n)}let t=[],e=await qd(i);for(let n of e){let r=!1,o=!1,s=!1;try{let a=await ee.promises.lstat(W(i,n));r=a.isFile(),o=a.isDirectory(),s=a.isSymbolicLink()}catch(a){a.code!=="ENOENT"&&console.warn("[node.js fs] unexpected error from lstat after readdir: ",a)}t.push({name:n,isFile:()=>r,isDirectory:()=>o,isSymbolicLink:()=>s})}return t}function a0(i){return i.map(t=>typeof t=="string"?et?qa(t):t:(t.name=et?qa(t.name):t.name,t))}async function l0(i){let t=await qd(i),e=[];for(let n of t)await Pt.existsDirectory(W(i,n))&&e.push(n);return e}var Pt;(n=>{async function i(r){let o;try{if(o=await ee.promises.lstat(r),!o.isSymbolicLink())return{stat:o}}catch{}try{return{stat:await ee.promises.stat(r),symbolicLink:o?.isSymbolicLink()?{dangling:!1}:void 0}}catch(s){if(s.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};if(G&&s.code==="EACCES")try{return{stat:await ee.promises.stat(await ee.promises.readlink(r)),symbolicLink:{dangling:!1}}}catch(a){if(a.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};throw a}throw s}}n.stat=i;async function t(r){try{let{stat:o,symbolicLink:s}=await n.stat(r);return o.isFile()&&s?.dangling!==!0}catch{}return!1}n.existsFile=t;async function e(r){try{let{stat:o,symbolicLink:s}=await n.stat(r);return o.isDirectory()&&s?.dangling!==!0}catch{}return!1}n.existsDirectory=e})(Pt||={});var d0=new Ao;function c0(i,t,e){return d0.queueFor(y.file(i),()=>{let n=f0(e);return new Promise((r,o)=>p0(i,t,n,s=>s?o(s):r()))},Je)}var ZS=!0;function u0(i){ZS=i}function p0(i,t,e,n){if(!ZS)return ee.writeFile(i,t,{mode:e.mode,flag:e.flag},n);ee.open(i,e.flag,e.mode,(r,o)=>{if(r)return n(r);ee.writeFile(o,t,s=>{if(s)return ee.close(o,()=>n(s));ee.fdatasync(o,a=>(a&&(console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ",a),u0(!1)),ee.close(o,l=>n(l))))})})}function f0(i){return i?{mode:typeof i.mode=="number"?i.mode:438,flag:typeof i.flag=="string"?i.flag:"w"}:{mode:438,flag:"w"}}async function g0(i,t,e=6e4){if(i!==t)try{G&&typeof e=="number"?await eb(i,t,Date.now(),e):await ee.promises.rename(i,t)}catch(n){if(i.toLowerCase()!==t.toLowerCase()&&n.code==="EXDEV"||i.endsWith("."))await tb(i,t,{preserveSymlinks:!1}),await XS(i,1);else throw n}}async function eb(i,t,e,n,r=0){try{return await ee.promises.rename(i,t)}catch(o){if(o.code!=="EACCES"&&o.code!=="EPERM"&&o.code!=="EBUSY")throw o;if(Date.now()-e>=n)throw console.error(`[node.js fs] rename failed after ${r} retries with error: ${o}`),o;if(r===0){let s=!1;try{let{stat:a}=await Pt.stat(t);a.isFile()||(s=!0)}catch{}if(s)throw o}return await _n(Math.min(100,r*10)),eb(i,t,e,n,r+1)}}async function tb(i,t,e){return nb(i,t,{root:{source:i,target:t},options:e,handledSourcePaths:new Set})}var QS=511;async function nb(i,t,e){if(e.handledSourcePaths.has(i))return;e.handledSourcePaths.add(i);let{stat:n,symbolicLink:r}=await Pt.stat(i);if(r){if(e.options.preserveSymlinks)try{return await y0(i,t,e)}catch{}if(r.dangling)return}return n.isDirectory()?m0(i,t,n.mode&QS,e):h0(i,t,n.mode&QS)}async function m0(i,t,e,n){await ee.promises.mkdir(t,{recursive:!0,mode:e});let r=await qd(i);for(let o of r)await nb(W(i,o),W(t,o),n)}async function h0(i,t,e){await ee.promises.copyFile(i,t),await ee.promises.chmod(t,e)}async function y0(i,t,e){let n=await ee.promises.readlink(i);cr(n,e.root.source,!Se)&&(n=W(e.root.target,n.substr(e.root.source.length+1))),await ee.promises.symlink(n,t)}async function v0(i){try{return await Ba(ee.realpath)(i)}catch{let t=S0(i);return await ee.promises.access(t,ee.constants.R_OK),t}}function S0(i){return wo(Ft(i),be)}var Ae=new class{get read(){return(i,t,e,n,r)=>new Promise((o,s)=>{ee.read(i,t,e,n,r,(a,l,d)=>a?s(a):o({bytesRead:l,buffer:d}))})}get write(){return(i,t,e,n,r)=>new Promise((o,s)=>{ee.write(i,t,e,n,r,(a,l,d)=>a?s(a):o({bytesWritten:l,buffer:d}))})}get fdatasync(){return Ba(ee.fdatasync)}get open(){return Ba(ee.open)}get close(){return Ba(ee.close)}get ftruncate(){return Ba(ee.ftruncate)}async exists(i){try{return await ee.promises.access(i),!0}catch{return!1}}get readdir(){return qd}get readDirsInDir(){return l0}get writeFile(){return c0}get rm(){return XS}get rename(){return g0}get copy(){return tb}get realpath(){return v0}};function ob(i=Fe){return i.comspec||"cmd.exe"}function sb(i){let t=[],e=!1,n=function(r){if(e){t.push(r);return}(!i.send(r,s=>{if(s&&console.error(s),e=!1,t.length>0){let a=t.slice(0);t=[],a.forEach(l=>n(l))}})||G)&&(e=!0)};return{send:n}}async function I0(i){if(await Ae.exists(i)){let t;try{t=await ib.stat(i)}catch(e){e.message.startsWith("EACCES")&&(t=await ib.lstat(i))}return t?!t.isDirectory():!1}return!1}async function Bd(i,t,e,n=Fe,r=I0){if(Wt(i))return await r(i)?i:void 0;if(t===void 0&&(t=Di()),se(i)!=="."){let l=W(t,i);return await r(l)?l:void 0}let s=gr(n,"PATH");if(e===void 0&&Ne(s)&&(e=s.split(xo)),e===void 0||e.length===0){let l=W(t,i);return await r(l)?l:void 0}for(let l of e){let d;if(Wt(l)?d=W(l,i):d=W(t,l,i),G){let u=(gr(n,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").map(async p=>{let m=d+p;return await r(m)?m:void 0});for(let p of u){let m=await p;if(m)return m}}if(await r(d))return d}let a=W(t,i);return await r(a)?a:void 0}var Vd=class extends $a{constructor(t){super({send:e=>{try{process.send?.(e.buffer.toString("base64"))}catch{}},onMessage:Q.fromNodeEventEmitter(process,"message",e=>A.wrap(Buffer.from(e,"base64")))},t),process.once("disconnect",()=>this.dispose())}},zd=class{constructor(t,e){this.modulePath=t;this.options=e;this.activeRequests=new Set;this.channels=new Map;this._onDidProcessExit=new w;this.onDidProcessExit=this._onDidProcessExit.event;let n=e.timeout||6e4;this.disposeDelayer=new Ni(n),this.child=null,this._client=null}getChannel(t){let e=this;return{call(n,r,o){return e.requestPromise(t,n,r,o)},listen(n,r){return e.requestEvent(t,n,r)}}}requestPromise(t,e,n,r=Ee.None){if(!this.disposeDelayer)return Promise.reject(new Error("disposed"));if(r.isCancellationRequested)return Promise.reject(cd());this.disposeDelayer.cancel();let o=this.getCachedChannel(t),s=Qr(d=>o.call(e,n,d)),a=r.onCancellationRequested(()=>s.cancel()),l=k(()=>s.cancel());return this.activeRequests.add(l),s.finally(()=>{a.dispose(),this.activeRequests.delete(l),this.activeRequests.size===0&&this.disposeDelayer&&this.disposeDelayer.trigger(()=>this.disposeClient())}),s}requestEvent(t,e,n){if(!this.disposeDelayer)return Q.None;this.disposeDelayer.cancel();let r,o=new w({onWillAddFirstListener:()=>{r=this.getCachedChannel(t).listen(e,n)(o.fire,o),this.activeRequests.add(r)},onDidRemoveLastListener:()=>{this.activeRequests.delete(r),r.dispose(),this.activeRequests.size===0&&this.disposeDelayer&&this.disposeDelayer.trigger(()=>this.disposeClient())}});return o.event}get client(){if(!this._client){let t=this.options.args||[],e=Object.create(null);e.env={...cn(process.env),VSCODE_PARENT_PID:String(process.pid)},this.options.env&&(e.env={...e.env,...this.options.env}),this.options.freshExecArgv&&(e.execArgv=[]),typeof this.options.debug=="number"&&(e.execArgv=["--nolazy","--inspect="+this.options.debug]),typeof this.options.debugBrk=="number"&&(e.execArgv=["--nolazy","--inspect-brk="+this.options.debugBrk]),e.execArgv===void 0&&(e.execArgv=process.execArgv.filter(u=>!/^--inspect(-brk)?=/.test(u)).filter(u=>!u.startsWith("--vscode-"))),GS(e.env),this.child=C0(this.modulePath,t,e);let n=new w,o=Q.fromNodeEventEmitter(this.child,"message",u=>u)(u=>{if(VS(u)){zS(u,`IPC Library: ${this.options.serverName}`);return}n.fire(A.wrap(Buffer.from(u,"base64")))}),s=this.options.useQueue?sb(this.child):this.child,a=u=>this.child?.connected&&s.send(u.buffer.toString("base64")),l=n.event,d={send:a,onMessage:l};this._client=new Lo(d);let c=()=>this.disposeClient();process.once("exit",c),this.child.on("error",u=>console.warn('IPC "'+this.options.serverName+'" errored with '+u)),this.child.on("exit",(u,p)=>{process.removeListener("exit",c),o.dispose(),this.activeRequests.forEach(m=>Tt(m)),this.activeRequests.clear(),u!==0&&p!=="SIGTERM"&&console.warn('IPC "'+this.options.serverName+'" crashed with exit code '+u+" and signal "+p),this.disposeDelayer?.cancel(),this.disposeClient(),this._onDidProcessExit.fire({code:u,signal:p})})}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 jd(i){return!!i.parentPort}var Fg=class{constructor(t){this.port=t;this.onMessage=Q.fromNodeEventEmitter(this.port,"message",e=>e.data?A.wrap(e.data):A.alloc(0)),t.start()}send(t){this.port.postMessage(t.buffer)}disconnect(){this.port.close()}},Va=class i extends Hd{static getOnDidClientConnect(t){Tv(jd(process),"Electron Utility Process");let e=new w;return process.parentPort.on("message",n=>{if(t?.handledClientConnection(n))return;let r=n.ports.at(0);r&&e.fire(r)}),Q.map(e.event,n=>({protocol:new Fg(n),onDidClientDisconnect:Q.fromNodeEventEmitter(n,"close")}))}constructor(t){super(i.getOnDidClientConnect(t))}};var N=(function(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let i=new Uint8Array(16),t=[];for(let e=0;e<256;e++)t.push(e.toString(16).padStart(2,"0"));return function(){crypto.getRandomValues(i),i[6]=i[6]&15|64,i[8]=i[8]&63|128;let n=0,r="";return r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+="-",r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r+=t[i[n++]],r}})();import*as ld from"os";import*as ad from"inspector";var Tn;(r=>{r.serviceIds=new Map,r.DI_TARGET="$di$target",r.DI_DEPENDENCIES="$di$dependencies";function n(o){return o[r.DI_DEPENDENCIES]||[]}r.getServiceDependencies=n})(Tn||={});var ke=$("instantiationService");function x0(i,t,e){t[Tn.DI_TARGET]===t?t[Tn.DI_DEPENDENCIES].push({id:i,index:e}):(t[Tn.DI_DEPENDENCIES]=[{id:i,index:e}],t[Tn.DI_TARGET]=t)}function $(i){if(Tn.serviceIds.has(i))return Tn.serviceIds.get(i);let t=function(e,n,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");x0(t,e,r)};return t.toString=()=>i,Tn.serviceIds.set(i,t),t}var Wg="VSCODE_AGENT_HOST_CLAUDE_SDK_ROOT",ab="VSCODE_AGENT_HOST_CLAUDE_AGENT_ENABLED",lb="VSCODE_AGENT_HOST_CODEX_AGENT_ENABLED";function $g(i,t){if(i===void 0||i==="")return t;let e=i.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:t}var db="VSCODE_AGENT_HOST_CODEX_SDK_ROOT",cb="CODEX_HOME",ub="VSCODE_AGENT_HOST_CODEX_APP_SERVER_ARGS";var pb="agent-host/otel/agent-host-traces.db",o5=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 St={resource:"https://api.github.com",resource_name:"GitHub Copilot",authorization_servers:["https://github.com/login/oauth"],scopes_supported:["read:user","user:email"],required:!0},Hg={resource:"https://api.github.com/repos",resource_name:"GitHub Repository",authorization_servers:["https://github.com/login/oauth"],scopes_supported:["repo"],required:!1},F;(n=>{function i(r,o){return y.from({scheme:r,path:`/${o}`})}n.uri=i;function t(r){return(typeof r=="string"?y.parse(r):r).path.substring(1)}n.id=t;function e(r){return(typeof r=="string"?y.parse(r):r).scheme||void 0}n.provider=e})(F||={});var ti=$("agentService"),s5=$("agentHostService");function qg(i,t){return t&&(i.stack||i.stacktrace)?g(116,null,gb(i),fb(i.stack)||fb(i.stacktrace)):gb(i)}function fb(i){return Array.isArray(i)?i.join(`
`):i}function gb(i){return i.code==="ERR_UNC_HOST_NOT_ALLOWED"?`${i.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`:typeof i.code=="string"&&typeof i.errno=="number"&&typeof i.syscall=="string"?g(115,null,i.message):i.message||g(113,null)}function xt(i=null,t=!1){if(!i)return g(113,null);if(Array.isArray(i)){let e=Wr(i),n=xt(e[0],t);return e.length>1?g(114,null,n,e.length):n}if(Ne(i))return i;if(i.detail){let e=i.detail;if(e.error)return qg(e.error,t);if(e.exception)return qg(e.exception,t)}return i.stack?qg(i,t):i.message?i.message:g(113,null)}var c5=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 Bg={".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 Kd(i){let t=xd(i),e=Bg[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function mb(i){for(let t in Bg){let e=Bg[t];if(Array.isArray(e)?e.includes(i):e===i)return t}}var ct=class{constructor(t,e,n){this.owner=t;this.debugNameSource=e;this.referenceFn=n}getDebugName(t){return Sb(t,this)}},hb=new Map,Vg=new WeakMap;function Sb(i,t){let e=Vg.get(i);if(e)return e;let n=w0(i,t);if(n){let r=hb.get(n)??0;r++,hb.set(n,r);let o=r===1?n:`${n}#${r}`;return Vg.set(i,o),o}}function w0(i,t){let e=Vg.get(i);if(e)return e;let n=t.owner?E0(t.owner)+".":"",r,o=t.debugNameSource;if(o!==void 0)if(typeof o=="function"){if(r=o(),r!==void 0)return n+r}else return n+o;let s=t.referenceFn;if(s!==void 0&&(r=za(s),r!==void 0))return n+r;if(t.owner!==void 0){let a=R0(t.owner,i);if(a!==void 0)return n+a}}function R0(i,t){for(let e in i)if(i[e]===t)return e}var yb=new Map,vb=new WeakMap;function E0(i){let t=vb.get(i);if(t)return t;let e=zg(i)??"Object",n=yb.get(e)??0;n++,yb.set(e,n);let r=n===1?e:`${e}#${n}`;return vb.set(i,r),r}function zg(i){let t=i.constructor;if(t)return t.name==="Object"?void 0:t.name}function za(i){let t=i.toString(),n=/\/\*\*\s*@description\s*([^*]*)\*\//.exec(t);return(n?n[1]:void 0)?.trim()}function Ht(i,t){return i===t}function P0(){return(i,t)=>i===t}function jg(i,t,e){return Xt(i,t,e??Ht)}function A0(i){return(t,e)=>Xt(t,e,i??Ht)}function $i(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++)if(!$i(i[e],t[e]))return!1;return!0}if(i&&typeof i=="object"&&t&&typeof t=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let e=i,n=t,r=Object.keys(e),o=Object.keys(n),s=new Set(o);if(r.length!==o.length)return!1;for(let a of r)if(!s.has(a)||!$i(e[a],n[a]))return!1;return!0}return!1}function k0(){return(i,t)=>$i(i,t)}function D0(i,t){return JSON.stringify(i)===JSON.stringify(t)}function O0(){return(i,t)=>JSON.stringify(i)===JSON.stringify(t)}function M0(){return(i,t)=>i.equals(t)}function L0(i,t,e){return i==null||t===void 0||t===null?t===i:e(i,t)}function N0(i){return(t,e)=>t==null||e===void 0||e===null?e===t:i(t,e)}var U0;(u=>(u.strict=Ht,u.strictC=P0,u.array=jg,u.arrayC=A0,u.structural=$i,u.structuralC=k0,u.jsonStringify=D0,u.jsonStringifyC=O0,u.thisC=M0,u.ifDefined=L0,u.ifDefinedC=N0))(U0||={});function Kg(i){let t=new Error("BugIndicatingErrorRecovery: "+i);ze(t),console.error("recovered from an error that indicates a bug",t)}var Hi;function ja(i){Hi?Hi instanceof Gd?Hi.loggers.push(i):Hi=new Gd([Hi,i]):Hi=i}function we(){return Hi}var Gg;function bb(i){Gg=i}function Ib(i){Gg&&Gg(i)}var Gd=class{constructor(t){this.loggers=t}handleObservableCreated(t,e){for(let n of this.loggers)n.handleObservableCreated(t,e)}handleOnListenerCountChanged(t,e){for(let n of this.loggers)n.handleOnListenerCountChanged(t,e)}handleObservableUpdated(t,e){for(let n of this.loggers)n.handleObservableUpdated(t,e)}handleAutorunCreated(t,e){for(let n of this.loggers)n.handleAutorunCreated(t,e)}handleAutorunDisposed(t){for(let e of this.loggers)e.handleAutorunDisposed(t)}handleAutorunDependencyChanged(t,e,n){for(let r of this.loggers)r.handleAutorunDependencyChanged(t,e,n)}handleAutorunStarted(t){for(let e of this.loggers)e.handleAutorunStarted(t)}handleAutorunFinished(t){for(let e of this.loggers)e.handleAutorunFinished(t)}handleDerivedDependencyChanged(t,e,n){for(let r of this.loggers)r.handleDerivedDependencyChanged(t,e,n)}handleDerivedCleared(t){for(let e of this.loggers)e.handleDerivedCleared(t)}handleBeginTransaction(t){for(let e of this.loggers)e.handleBeginTransaction(t)}handleEndTransaction(t){for(let e of this.loggers)e.handleEndTransaction(t)}};function qi(i,t){let e=new ni(i,t);try{i(e)}finally{e.finish()}}function Jg(i,t,e){i?t(i):qi(t,e)}var ni=class{constructor(t,e){this._fn=t;this._getDebugName=e;this._updatingObservers=[];we()?.handleBeginTransaction(this)}getDebugName(){return this._getDebugName?this._getDebugName():za(this._fn)}updateObserver(t,e){if(!this._updatingObservers){Kg("Transaction already finished!"),qi(n=>{n.updateObserver(t,e)});return}this._updatingObservers.push({observer:t,observable:e}),t.beginUpdate(e)}finish(){let t=this._updatingObservers;if(!t){Kg("transaction.finish() has already been called!");return}for(let e=0;e<t.length;e++){let{observer:n,observable:r}=t[e];n.endUpdate(r)}this._updatingObservers=null,we()?.handleEndTransaction(this)}debugGetUpdatingObservers(){return this._updatingObservers}};var Qe;(n=>{let i=!1;function t(){i=!0}n.enable=t;function e(){if(!i)return;let r=Error,o=r.stackTraceLimit;r.stackTraceLimit=3;let s=new Error().stack;return r.stackTraceLimit=o,Yg.fromStack(s,2)}n.ofCaller=e})(Qe||={});var Yg=class i{constructor(t,e,n,r){this.fileName=t;this.line=e;this.column=n;this.id=r}static fromStack(t,e){let n=t.split(`
`),r=F0(n[e+1]);if(r)return new i(r.fileName,r.line,r.column,r.id)}};function F0(i){let t=i.match(/\((.*):(\d+):(\d+)\)/);if(t)return{fileName:t[1],line:parseInt(t[2]),column:parseInt(t[3]),id:i};let e=i.match(/at ([^\(\)]*):(\d+):(\d+)/);if(e)return{fileName:e[1],line:parseInt(e[2]),column:parseInt(e[3]),id:i}}var Qg;function _b(i){Qg=i}var Cb;function Tb(i){Cb=i}var xb;function wb(i){xb=i}var Xg;function Rb(i){Xg=i}var Jd=class{get TChange(){return null}reportChanges(){this.get()}read(t){return t?t.readObservable(this):this.get()}map(t,e,n=Qe.ofCaller()){let r=e===void 0?void 0:t,o=e===void 0?t:e;return Qg({owner:r,debugName:()=>{let s=za(o);if(s!==void 0)return s;let l=/^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/.exec(o.toString());if(l)return`${this.debugName}.${l[2]}`;if(!r)return`${this.debugName} (mapped)`},debugReferenceFn:o},s=>o(this.read(s),s),n)}flatten(){return Qg({owner:void 0,debugName:()=>`${this.debugName} (flattened)`},t=>this.read(t).read(t))}recomputeInitiallyAndOnChange(t,e){return t.add(Cb(this,e)),this}keepObserved(t){return t.add(xb(this)),this}get debugValue(){return this.get()}get debug(){return new Zg(this)}},Zg=class{constructor(t){this.observable=t}getDependencyGraph(){return Xg(this.observable,{type:"dependencies"})}getObserverGraph(){return Xg(this.observable,{type:"observers"})}},un=class extends Jd{constructor(e){super();this._observers=new Set;we()?.handleObservableCreated(this,e)}addObserver(e){let n=this._observers.size;this._observers.add(e),n===0&&this.onFirstObserverAdded(),n!==this._observers.size&&we()?.handleOnListenerCountChanged(this,this._observers.size)}removeObserver(e){let n=this._observers.delete(e);n&&this._observers.size===0&&this.onLastObserverRemoved(),n&&we()?.handleOnListenerCountChanged(this,this._observers.size)}onFirstObserverAdded(){}onLastObserverRemoved(){}log(){let e=!!we();return Ib(this),e||we()?.handleObservableCreated(this,Qe.ofCaller()),this}debugGetObservers(){return this._observers}};function pn(i,t,e=Qe.ofCaller()){let n;return typeof i=="string"?n=new ct(void 0,i,void 0):n=new ct(i,void 0,void 0),new Nn(n,t,Ht,e)}var Nn=class extends un{constructor(e,n,r,o){super(o);this._debugNameData=e;this._equalityComparator=r;this._value=n,we()?.handleObservableUpdated(this,{hadValue:!1,newValue:n,change:void 0,didChange:!0,oldValue:void 0})}get debugName(){return this._debugNameData.getDebugName(this)??"ObservableValue"}get(){return this._value}set(e,n,r){if(r===void 0&&this._equalityComparator(this._value,e))return;let o;n||(n=o=new ni(()=>{},()=>`Setting ${this.debugName}`));try{let s=this._value;this._setValue(e),we()?.handleObservableUpdated(this,{oldValue:s,newValue:e,change:r,didChange:!0,hadValue:!0});for(let a of this._observers)n.updateObserver(a,this),a.handleChange(this,r)}finally{o&&o.finish()}}toString(){return`${this.debugName}: ${this._value}`}_setValue(e){this._value=e}debugGetState(){return{value:this._value}}debugSetValue(e){this._value=e}};var Yd=class extends un{constructor(e,n,r,o){super(o);this._debugNameData=e;this._equalityComparator=r;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){we()?.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{we()?.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,r){if(r===void 0&&this._equalityComparator(this._value,e))return;let o;n||(n=o=new ni(()=>{},()=>`Setting ${this.debugName}`));try{if(this._isUpToDate=!1,this._setValue(e),r!==void 0&&this._deltas.push(r),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 Bi(i,t,e=Qe.ofCaller()){return i.lazy?new Yd(new ct(i.owner,i.debugName,void 0),t,i.equalsFn??Ht,e):new Nn(new ct(i.owner,i.debugName,void 0),t,i.equalsFn??Ht,e)}function W0(i){switch(i){case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var mr=class{constructor(t,e,n,r){this._debugNameData=t;this._runFn=e;this._changeTracker=n;this._state=2;this._updateCount=0;this._disposed=!1;this._dependencies=new Set;this._dependenciesToBeRemoved=new Set;this._isRunning=!1;this._iteration=0;this._store=void 0;this._delayedStore=void 0;this._changeSummary=this._changeTracker?.createChangeSummary(void 0),we()?.handleAutorunCreated(this,r),this._run(),$r(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(),we()?.handleAutorunDisposed(this),Hr(this)}}_run(){let t=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=t,this._state=3;try{if(!this._disposed){we()?.handleAutorunStarted(this);let e=this._changeSummary,n=this._delayedStore;n!==void 0&&(this._delayedStore=void 0);try{this._isRunning=!0,this._changeTracker&&(this._changeTracker.beforeUpdate?.(this,e),this._changeSummary=this._changeTracker.createChangeSummary(e)),this._store!==void 0&&(this._store.dispose(),this._store=void 0),this._runFn(this,e)}catch(r){Fr(r)}finally{this._isRunning=!1,n!==void 0&&n.dispose()}}}finally{this._disposed||we()?.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--}Ta(()=>this._updateCount>=0)}handlePossibleChange(t){this._state===3&&this._isDependency(t)&&(this._checkIterations(),this._state=1)}handleChange(t,e){if(this._isDependency(t)){we()?.handleAutorunDependencyChanged(this,t,e);try{(!this._changeTracker||this._changeTracker.handleChange({changedObservable:t,change:e,didChange:r=>r===t},this._changeSummary))&&(this._checkIterations(),this._state=2)}catch(n){Fr(n)}}}_isDependency(t){return this._dependencies.has(t)&&!this._dependenciesToBeRemoved.has(t)}_ensureNoRunning(){if(!this._isRunning)throw new De("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 De("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 De("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:W0(this._state)}}debugRerun(){this._isRunning?this._state=2:this._run()}_checkIterations(){return this._iteration>100?(Fr(new De(`Autorun '${this.debugName}' is stuck in an infinite update loop.`)),!0):!1}};function Un(i,t=Qe.ofCaller()){return new mr(new ct(void 0,void 0,i),i,void 0,t)}function $0(i){switch(i){case 0:return"initial";case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var ut=class extends un{constructor(e,n,r,o=void 0,s,a){super(a);this._debugNameData=e;this._computeFn=n;this._changeTracker=r;this._handleLastObserverRemoved=o;this._equalityComparator=s;this._state=0;this._value=void 0;this._updateCount=0;this._dependencies=new Set;this._dependenciesToBeRemoved=new Set;this._changeSummary=void 0;this._isUpdating=!1;this._isComputing=!1;this._didReportChange=!1;this._isInBeforeUpdate=!1;this._isReaderValid=!1;this._store=void 0;this._delayedStore=void 0;this._removedObserverToCallEndUpdateOn=null;this._changeSummary=this._changeTracker?.createChangeSummary(void 0)}get debugName(){return this._debugNameData.getDebugName(this)??"(anonymous)"}onLastObserverRemoved(){this._state=0,this._value=void 0,we()?.handleDerivedCleared(this);for(let e of this._dependencies)e.removeObserver(this);this._dependencies.clear(),this._store!==void 0&&(this._store.dispose(),this._store=void 0),this._delayedStore!==void 0&&(this._delayedStore.dispose(),this._delayedStore=void 0),this._handleLastObserverRemoved?.()}get(){if(this._isComputing,this._observers.size===0){let n;try{this._isReaderValid=!0;let r;this._changeTracker&&(r=this._changeTracker.createChangeSummary(void 0),this._changeTracker.beforeUpdate?.(this,r)),n=this._computeFn(this,r)}finally{this._isReaderValid=!1}return this.onLastObserverRemoved(),n}else{do{if(this._state===1){for(let n of this._dependencies)if(n.reportChanges(),this._state===2)break}this._state===1&&(this._state=3),this._state!==3&&this._recompute()}while(this._state!==3);return this._value}}_recompute(){let e=!1;this._isComputing=!0,this._didReportChange=!1;let n=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=n;try{let r=this._changeSummary;this._isReaderValid=!0,this._changeTracker&&(this._isInBeforeUpdate=!0,this._changeTracker.beforeUpdate?.(this,r),this._isInBeforeUpdate=!1,this._changeSummary=this._changeTracker?.createChangeSummary(r));let o=this._state!==0,s=this._value;this._state=3;let a=this._delayedStore;a!==void 0&&(this._delayedStore=void 0);try{this._store!==void 0&&(this._store.dispose(),this._store=void 0),this._value=this._computeFn(this,r)}finally{this._isReaderValid=!1;for(let l of this._dependenciesToBeRemoved)l.removeObserver(this);this._dependenciesToBeRemoved.clear(),a!==void 0&&a.dispose()}e=this._didReportChange||o&&!this._equalityComparator(s,this._value),we()?.handleObservableUpdated(this,{oldValue:s,newValue:this._value,change:void 0,didChange:e,hadValue:o})}catch(r){Fr(r)}if(this._isComputing=!1,!this._didReportChange&&e)for(let r of this._observers)r.handleChange(this,void 0);else this._didReportChange=!1}toString(){return`LazyDerived<${this.debugName}>`}beginUpdate(e){if(this._isUpdating)throw new De("Cyclic deriveds are not supported yet!");this._updateCount++,this._isUpdating=!0;try{let n=this._updateCount===1;if(this._state===3&&(this._state=1,!n))for(let r of this._observers)r.handlePossibleChange(this);if(n)for(let r of this._observers)r.beginUpdate(this)}finally{this._isUpdating=!1}}endUpdate(e){if(this._updateCount--,this._updateCount===0){let n=[...this._observers];for(let r of n)r.endUpdate(this);if(this._removedObserverToCallEndUpdateOn){let r=[...this._removedObserverToCallEndUpdateOn];this._removedObserverToCallEndUpdateOn=null;for(let o of r)o.endUpdate(this)}}Ta(()=>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){we()?.handleDerivedDependencyChanged(this,e,n);let r=!1;try{r=this._changeTracker?this._changeTracker.handleChange({changedObservable:e,change:n,didChange:s=>s===e},this._changeSummary):!0}catch(s){Fr(s)}let o=this._state===3;if(r&&(this._state===1||o)&&(this._state=2,o))for(let s of this._observers)s.handlePossibleChange(this)}}_ensureReaderValid(){if(!this._isReaderValid)throw new De("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:$0(this._state),updateCount:this._updateCount,isComputing:this._isComputing,dependencies:this._dependencies,value:this._value}}debugSetValue(e){this._value=e}debugRecompute(){this.beginUpdate(this);try{this._isComputing?this._state=2:this._recompute()}finally{this.endUpdate(this)}}setValue(e,n,r){this._value=e;let o=this._observers;n.updateObserver(this,this);for(let s of o)s.handleChange(this,r)}};function Ka(i,t,e=Qe.ofCaller()){return new ut(new ct(i.owner,i.debugName,i.debugReferenceFn),t,void 0,i.onLastObserverRemoved,i.equalsFn??Ht,e)}_b(Ka);function $o(...i){let t,e,n,r;return i.length===2?[e,n]=i:[t,e,n,r]=i,new fn(new ct(t,void 0,n),e,n,()=>fn.globalTransaction,Ht,r??Qe.ofCaller())}var fn=class extends un{constructor(e,n,r,o,s,a){super(a);this._debugNameData=e;this.event=n;this._getValue=r;this._getTransaction=o;this._equalityComparator=s;this._hasValue=!1;this.handleEvent=e=>{let n=this._getValue(e),r=this._value,o=!this._hasValue||!this._equalityComparator(r,n),s=!1;o&&(this._value=n,this._hasValue&&(s=!0,Jg(this._getTransaction(),a=>{we()?.handleObservableUpdated(this,{oldValue:r,newValue:n,change:void 0,didChange:o,hadValue:this._hasValue});for(let l of this._observers)a.updateObserver(l,this),l.handleChange(this,void 0)},()=>{let a=this.getDebugName();return"Event fired"+(a?`: ${a}`:"")})),this._hasValue=!0),s||we()?.handleObservableUpdated(this,{oldValue:r,newValue:n,change:void 0,didChange:o,hadValue:this._hasValue})}}getDebugName(){return this._debugNameData.getDebugName(this)}get debugName(){let e=this.getDebugName();return"From Event"+(e?`: ${e}`:"")}onFirstObserverAdded(){this._subscription=this.event(this.handleEvent)}onLastObserverRemoved(){this._subscription.dispose(),this._subscription=void 0,this._hasValue=!1,this._value=void 0}get(){return this._subscription?(this._hasValue||this.handleEvent(void 0),this._value):this._getValue(void 0)}debugSetValue(e){this._value=e}debugGetState(){return{value:this._value,hasValue:this._hasValue}}};(e=>{e.Observer=fn;function t(n,r){let o=!1;fn.globalTransaction===void 0&&(fn.globalTransaction=n,o=!0);try{r()}finally{o&&(fn.globalTransaction=void 0)}}e.batchEventsGlobally=t})($o||={});function Pb(i){let t=new Qd(!1,void 0);return i.addObserver(t),k(()=>{i.removeObserver(t)})}wb(Pb);function Ab(i,t){let e=new Qd(!0,t);i.addObserver(e);try{e.beginUpdate(i)}finally{e.endUpdate(i)}return k(()=>{i.removeObserver(e)})}Tb(Ab);var Qd=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 Xd;function kb(i){Xd||(Xd=new Ga,ja(Xd)),Xd.addFilteredObj(i)}var Ga=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 j0([Ho(J0("|  ",this.indentation)),t])}formatInfo(t){return t.hadValue?t.didChange?[Ho(" "),gn(tn(t.oldValue,70),{color:"red",strikeThrough:!0}),Ho(" "),gn(tn(t.newValue,60),{color:"green"})]:[Ho(" (unchanged)")]:[Ho(" "),gn(tn(t.newValue,60),{color:"green"}),Ho(" (initial)")]}handleObservableCreated(t){if(t instanceof ut){let e=t;if(this.changedObservablesSets.set(e,new Set),!1){let r=[];e.__debugUpdating=r;let o=e.beginUpdate;e.beginUpdate=a=>(r.push(a),o.apply(e,[a]));let s=e.endUpdate;e.endUpdate=a=>{let l=r.indexOf(a);return l===-1&&console.error("endUpdate called without beginUpdate",e.debugName,a.debugName),r.splice(l,1),s.apply(e,[a])}}}}handleOnListenerCountChanged(t,e){}handleObservableUpdated(t,e){if(this._isIncluded(t)){if(t instanceof ut){this._handleDerivedRecomputed(t,e);return}console.log(...this.textToConsoleArgs([qo("observable value changed"),gn(t.debugName,{color:"BlueViolet"}),...this.formatInfo(e)]))}}formatChanges(t){if(t.size!==0)return gn(" (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([qo("derived recomputed"),gn(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([qo("derived cleared"),gn(t.debugName,{color:"BlueViolet"})]))}handleFromEventObservableTriggered(t,e){this._isIncluded(t)&&console.log(...this.textToConsoleArgs([qo("observable from event triggered"),gn(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([qo("autorun"),gn(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([qo("transaction"),gn(e,{color:"BlueViolet"}),{data:[{fn:t._fn}]}])),this.indentation++}handleEndTransaction(){this.indentation--}};function j0(i){let t=new Array,e=[],n="";function r(s){if("length"in s)for(let a of s)a&&r(a);else"text"in s?(n+=`%c${s.text}`,t.push(s.style),s.data&&e.push(...s.data)):"data"in s&&e.push(...s.data)}r(i);let o=[n,...t];return o.push(...e),o}function Ho(i){return gn(i,{color:"black"})}function qo(i){return gn(Y0(`${i}: `,10),{color:"black",bold:!0})}function gn(i,t={color:"black"}){function e(r){return Object.entries(r).reduce((o,[s,a])=>`${o}${s}:${a};`,"")}let n={color:t.color};return t.strikeThrough&&(n["text-decoration"]="line-through"),t.bold&&(n["font-weight"]="bold"),{text:i,style:e(n)}}function tn(i,t){switch(typeof i){case"number":return""+i;case"string":return i.length+2<=t?`"${i}"`:`"${i.substr(0,t-7)}"+...`;case"boolean":return i?"true":"false";case"undefined":return"undefined";case"object":return i===null?"null":Array.isArray(i)?K0(i,t):G0(i,t);case"symbol":return i.toString();case"function":return`[[Function${i.name?" "+i.name:""}]]`;default:return""+i}}function K0(i,t){let e="[ ",n=!0;for(let r of i){if(n||(e+=", "),e.length-5>t){e+="...";break}n=!1,e+=`${tn(r,t-e.length)}`}return e+=" ]",e}function G0(i,t){if(typeof i.toString=="function"&&i.toString!==Object.prototype.toString){let o=i.toString();return o.length<=t?o:o.substring(0,t-3)+"..."}let e=zg(i),n=e?e+"(":"{ ",r=!0;for(let[o,s]of Object.entries(i)){if(r||(n+=", "),n.length-5>t){n+="...";break}r=!1,n+=`${o}: ${tn(s,t-n.length)}`}return n+=e?")":" }",n}function J0(i,t){let e="";for(let n=1;n<=t;n++)e+=i;return e}function Y0(i,t){for(;i.length<t;)i+=" ";return i}var Zd=class i{constructor(t,e){this._channelFactory=t;this._getHandler=e;this._channel=this._channelFactory({handleNotification:o=>{let s=o,a=this._getHandler().notifications[s[0]];if(!a)throw new Error(`Unknown notification "${s[0]}"!`);a(...s[1])},handleRequest:o=>{let s=o;try{return{type:"result",value:this._getHandler().requests[s[0]](...s[1])}}catch(a){return{type:"error",value:a}}}});let n=new Proxy({},{get:(o,s)=>async(...a)=>{let l=await this._channel.sendRequest([s,a]);if(l.type==="error")throw l.value;return l.value}}),r=new Proxy({},{get:(o,s)=>(...a)=>{this._channel.sendNotification([s,a])}});this.api={notifications:r,requests:n}}static createHost(t,e){return new i(t,e)}static createClient(t,e){return new i(t,e)}};function Db(i,t){let e=globalThis,n=[],r,{channel:o,handler:s}=Q0({sendNotification:l=>{r?r.sendNotification(l):n.push(l)}}),a;return(e.$$debugValueEditor_debugChannels??(e.$$debugValueEditor_debugChannels={}))[i]=l=>{a=t(),r=l;for(let d of n)l.sendNotification(d);return n=[],s},Zd.createClient(o,()=>{if(!a)throw new Error("Not supported");return a})}function Q0(i){let t;return{channel:n=>(t=n,{sendNotification:r=>{i.sendNotification(r)},sendRequest:r=>{throw new Error("not supported")}}),handler:{handleRequest:n=>n.type==="notification"?t?.handleNotification(n.data):t?.handleRequest(n.data)}}}var ec=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 em(i,t){for(let e in t)i[e]&&typeof i[e]=="object"&&t[e]&&typeof t[e]=="object"?em(i[e],t[e]):i[e]=t[e]}function tm(i,t){for(let e in t)t[e]===null?delete i[e]:i[e]&&typeof i[e]=="object"&&t[e]&&typeof t[e]=="object"?tm(i[e],t[e]):i[e]=t[e]}var tc=class i{constructor(){this._declarationId=0;this._instanceId=0;this._declarations=new Map;this._instanceInfos=new WeakMap;this._aliveInstances=new Map;this._activeTransactions=new Set;this._channel=Db("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(tr)}),getDerivedInfo:t=>{let e=this._aliveInstances.get(t);return{dependencies:[...e.debugGetState().dependencies].map(n=>this._formatObservable(n)).filter(tr),observers:[...e.debugGetObservers()].map(n=>this._formatObserver(n)).filter(tr)}},getAutorunInfo:t=>({dependencies:[...this._aliveInstances.get(t).debugGetState().dependencies].map(n=>this._formatObservable(n)).filter(tr)}),getTransactionState:()=>this.getTransactionState(),setValue:(t,e)=>{let n=this._aliveInstances.get(t);if(n instanceof ut)n.debugSetValue(e);else if(n instanceof Nn)n.debugSetValue(e);else if(n instanceof fn)n.debugSetValue(e);else throw new De("Observable is not supported");let r=[...n.debugGetObservers()];for(let o of r)o.beginUpdate(n);for(let o of r)o.handleChange(n,void 0);for(let o of r)o.endUpdate(n)},getValue:t=>{let e=this._aliveInstances.get(t);if(e instanceof ut)return tn(e.debugGetState().value,200);if(e instanceof Nn)return tn(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 De("Observable is not supported")},rerun:t=>{let e=this._aliveInstances.get(t);if(e instanceof ut)e.debugRecompute();else if(e instanceof mr)e.debugRerun();else throw new De("Observable is not supported")}}}));this._pendingChanges=null;this._changeThrottler=new ec;this._fullState={};this._flushUpdates=()=>{this._pendingChanges!==null&&(this._channel.api.notifications.handleChange(this._pendingChanges,!1),this._pendingChanges=null)};Qe.enable()}static{this._instance=void 0}static getInstance(){return i._instance===void 0&&(i._instance=new i),i._instance}getTransactionState(){let t=[],e=[...this._activeTransactions];if(e.length===0)return;let n=e.flatMap(o=>o.debugGetUpdatingObservers()??[]).map(o=>o.observer),r=new Set;for(;n.length>0;){let o=n.shift();if(r.has(o))continue;r.add(o);let s=this._getInfo(o,a=>{r.has(a)||n.push(a)});s&&t.push(s)}return{names:e.map(o=>o.getDebugName()??"tx"),affected:t}}_getObservableInfo(t){let e=this._instanceInfos.get(t);if(!e){ze(new De("No info found"));return}return e}_getAutorunInfo(t){let e=this._instanceInfos.get(t);if(!e){ze(new De("No info found"));return}return e}_getInfo(t,e){if(t instanceof ut){let n=[...t.debugGetObservers()];for(let l of n)e(l);let r=this._getObservableInfo(t);if(!r)return;let o=t.debugGetState(),s={name:t.debugName,instanceId:r.instanceId,updateCount:o.updateCount},a=[...r.changedObservables].map(l=>this._instanceInfos.get(l)?.instanceId).filter(tr);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 mr){let n=this._getAutorunInfo(t);if(!n)return;let r={name:t.debugName,instanceId:n.instanceId,updateCount:n.updateCount},o=[...n.changedObservables].map(s=>this._instanceInfos.get(s).instanceId);if(t.debugGetState().isRunning)return{...r,type:"autorun",state:"updating",changedDependencies:o};switch(t.debugGetState().state){case 3:return{...r,type:"autorun",state:"upToDate"};case 2:return{...r,type:"autorun",state:"stale",changedDependencies:o};case 1:return{...r,type:"autorun",state:"possiblyStale"}}}}_formatObservable(t){let e=this._getObservableInfo(t);if(e)return{name:t.debugName,instanceId:e.instanceId}}_formatObserver(t){if(t instanceof ut)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){tm(this._fullState,t),this._pendingChanges===null?this._pendingChanges=t:em(this._pendingChanges,t),this._changeThrottler.throttle(this._flushUpdates,10)}_getDeclarationId(t,e){if(!e)return-1;let n=this._declarations.get(e.id);return n===void 0&&(n={id:this._declarationId++,type:t,url:e.fileName,line:e.line,column:e.column},this._declarations.set(e.id,n),this._handleChange({decls:{[n.id]:n}})),n.id}handleObservableCreated(t,e){let r={declarationId:this._getDeclarationId("observable/value",e),instanceId:this._instanceId++,listenerCount:0,lastValue:void 0,updateCount:0,changedObservables:new Set};this._instanceInfos.set(t,r)}handleOnListenerCountChanged(t,e){let n=this._getObservableInfo(t);if(n){if(n.listenerCount===0&&e>0){let r=t instanceof ut?"observable/derived":"observable/value";this._aliveInstances.set(n.instanceId,t),this._handleChange({instances:{[n.instanceId]:{instanceId:n.instanceId,declarationId:n.declarationId,formattedValue:n.lastValue,type:r,name:t.debugName}}})}else n.listenerCount>0&&e===0&&(this._handleChange({instances:{[n.instanceId]:null}}),this._aliveInstances.delete(n.instanceId));n.listenerCount=e}}handleObservableUpdated(t,e){if(t instanceof ut){this._handleDerivedRecomputed(t,e);return}let n=this._getObservableInfo(t);n&&e.didChange&&(n.lastValue=tn(e.newValue,30),n.listenerCount>0&&this._handleChange({instances:{[n.instanceId]:{formattedValue:n.lastValue}}}))}handleAutorunCreated(t,e){let r={declarationId:this._getDeclarationId("autorun",e),instanceId:this._instanceId++,updateCount:0,changedObservables:new Set};this._instanceInfos.set(t,r),this._aliveInstances.set(r.instanceId,t),r&&this._handleChange({instances:{[r.instanceId]:{instanceId:r.instanceId,declarationId:r.declarationId,runCount:0,type:"autorun",name:t.debugName}}})}handleAutorunDisposed(t){let e=this._getAutorunInfo(t);e&&(this._handleChange({instances:{[e.instanceId]:null}}),this._instanceInfos.delete(t),this._aliveInstances.delete(e.instanceId))}handleAutorunDependencyChanged(t,e,n){let r=this._getAutorunInfo(t);r&&r.changedObservables.add(e)}handleAutorunStarted(t){}handleAutorunFinished(t){let e=this._getAutorunInfo(t);e&&(e.changedObservables.clear(),e.updateCount++,this._handleChange({instances:{[e.instanceId]:{runCount:e.updateCount}}}))}handleDerivedDependencyChanged(t,e,n){let r=this._getObservableInfo(t);r&&r.changedObservables.add(e)}_handleDerivedRecomputed(t,e){let n=this._getObservableInfo(t);if(!n)return;let r=tn(e.newValue,30);n.updateCount++,n.changedObservables.clear(),n.lastValue=r,n.listenerCount>0&&this._handleChange({instances:{[n.instanceId]:{formattedValue:r,recomputationCount:n.updateCount}}})}handleDerivedCleared(t){let e=this._getObservableInfo(t);e&&(e.lastValue=void 0,e.changedObservables.clear(),e.listenerCount>0&&this._handleChange({instances:{[e.instanceId]:{formattedValue:void 0}}}))}handleBeginTransaction(t){this._activeTransactions.add(t)}handleEndTransaction(t){this._activeTransactions.delete(t)}};function Ob(i,t){let e=t?.debugNamePostProcessor??(o=>o),n=Vi.from(i,e);if(!n)return"";let r=new Set;return t.type==="observers"?Lb(n,0,r,t).trim():Mb(n,0,r,t).trim()}function Mb(i,t,e,n){let r="		".repeat(t),o=[];if(e.has(i.sourceObj))return o.push(`${r}* ${i.type} ${i.name} (already listed)`),o.join(`
`);if(e.add(i.sourceObj),o.push(`${r}* ${i.type} ${i.name}:`),o.push(`${r}  value: ${tn(i.value,50)}`),o.push(`${r}  state: ${i.state}`),i.dependencies.length>0){o.push(`${r}  dependencies:`);for(let a of i.dependencies){let l=Vi.from(a,n.debugNamePostProcessor??(d=>d))??Vi.unknown(a);o.push(Mb(l,t+1,e,n))}}return o.join(`
`)}function Lb(i,t,e,n){let r="		".repeat(t),o=[];if(e.has(i.sourceObj))return o.push(`${r}* ${i.type} ${i.name} (already listed)`),o.join(`
`);if(e.add(i.sourceObj),o.push(`${r}* ${i.type} ${i.name}:`),o.push(`${r}  value: ${tn(i.value,50)}`),o.push(`${r}  state: ${i.state}`),i.observers.length>0){o.push(`${r}  observers:`);for(let a of i.observers){let l=Vi.from(a,n.debugNamePostProcessor??(d=>d))??Vi.unknown(a);o.push(Lb(l,t+1,e,n))}}return o.join(`
`)}var Vi=class i{constructor(t,e,n,r,o,s,a){this.sourceObj=t;this.name=e;this.type=n;this.value=r;this.state=o;this.dependencies=s;this.observers=a}static from(t,e){if(t instanceof mr){let n=t.debugGetState();return new i(t,e(t.debugName),"autorun",void 0,n.stateStr,Array.from(n.dependencies),[])}else if(t instanceof ut){let n=t.debugGetState();return new i(t,e(t.debugName),"derived",n.value,n.stateStr,Array.from(n.dependencies),Array.from(t.debugGetObservers()))}else if(t instanceof Nn){let n=t.debugGetState();return new i(t,e(t.debugName),"observableValue",n.value,"upToDate",[],Array.from(t.debugGetObservers()))}else if(t instanceof fn){let n=t.debugGetState();return new i(t,e(t.debugName),"fromEvent",n.value,n.hasValue?"upToDate":"initial",[],Array.from(t.debugGetObservers()))}}static unknown(t){return new i(t,"(unknown)","unknown",void 0,"unknown",[],[])}};Rb(Ob);bb(kb);var X0=!1;X0&&ja(new Ga);Fe&&Fe.VSCODE_DEV_DEBUG_OBSERVABLES&&ja(tc.getInstance());var nm=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]}},rm=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?Rd(t,this._value,0,t.length,this._from,this._to):Li(t,this._value,0,t.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}},nc=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?Rd(t,this._value,0,t.length,this._from,this._to):Li(t,this._value,0,t.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}};var im=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 nc(!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 gg(t,this._value.scheme);if(this._states[this._stateIdx]===2)return gg(t,this._value.authority);if(this._states[this._stateIdx]===3)return this._pathIterator.cmp(t);if(this._states[this._stateIdx]===4)return lr(t,this._value.query);if(this._states[this._stateIdx]===5)return lr(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}},hr=class i{static{this.Val=Symbol("undefined_placeholder")}static wrap(t){return t===void 0?i.Val:t}static unwrap(t){return t===i.Val?void 0:t}},Bo=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 Fn=class i{static forUris(t=()=>!1,e=()=>!1){return new i(new im(t,e))}static forPaths(t=!1){return new i(new nc(void 0,!t))}static forStrings(){return new i(new nm)}static forConfigKeys(){return new i(new rm)}constructor(t){this._iter=t}clear(){this._root=void 0}fill(t,e){if(e){let n=e.slice(0);Jf(n);for(let r of n)this.set(r,t)}else{let n=t.slice(0);Jf(n);for(let r of n)this.set(r[0],r[1])}}set(t,e){let n=this._iter.reset(t),r;this._root||(this._root=new Bo,this._root.segment=n.value());let o=[];for(r=this._root;;){let a=n.cmp(r.segment);if(a>0)r.left||(r.left=new Bo,r.left.segment=n.value()),o.push([-1,r]),r=r.left;else if(a<0)r.right||(r.right=new Bo,r.right.segment=n.value()),o.push([1,r]),r=r.right;else if(n.hasNext())n.next(),r.mid||(r.mid=new Bo,r.mid.segment=n.value()),o.push([0,r]),r=r.mid;else break}let s=hr.unwrap(r.value);r.value=hr.wrap(e),r.key=t;for(let a=o.length-1;a>=0;a--){let l=o[a][1];l.updateHeight();let d=l.balanceFactor();if(d<-1||d>1){let c=o[a][0],u=o[a+1][0];if(c===1&&u===1)o[a][1]=l.rotateLeft();else if(c===-1&&u===-1)o[a][1]=l.rotateRight();else if(c===1&&u===-1)l.right=o[a+1][1]=o[a+1][1].rotateRight(),o[a][1]=l.rotateLeft();else if(c===-1&&u===1)l.left=o[a+1][1]=o[a+1][1].rotateLeft(),o[a][1]=l.rotateRight();else throw new Error;if(a>0)switch(o[a-1][0]){case-1:o[a-1][1].left=o[a][1];break;case 1:o[a-1][1].right=o[a][1];break;case 0:o[a-1][1].mid=o[a][1];break}else this._root=o[0][1]}}return s}get(t){return hr.unwrap(this._getNode(t)?.value)}_getNode(t){let e=this._iter.reset(t),n=this._root;for(;n;){let r=e.cmp(n.segment);if(r>0)n=n.left;else if(r<0)n=n.right;else if(e.hasNext())e.next(),n=n.mid;else break}return n}has(t){let e=this._getNode(t);return!(e?.value===void 0&&e?.mid===void 0)}delete(t){return this._delete(t,!1)}deleteSuperstr(t){return this._delete(t,!0)}_delete(t,e){let n=this._iter.reset(t),r=[],o=this._root;for(;o;){let s=n.cmp(o.segment);if(s>0)r.push([-1,o]),o=o.left;else if(s<0)r.push([1,o]),o=o.right;else if(n.hasNext())n.next(),r.push([0,o]),o=o.mid;else break}if(o){if(e?(o.left=void 0,o.mid=void 0,o.right=void 0,o.height=1):(o.key=void 0,o.value=void 0),!o.mid&&!o.value)if(o.left&&o.right){let s=[[1,o]],a=this._min(o.right,s);if(a.key){o.key=a.key,o.value=a.value,o.segment=a.segment;let l=a.right;if(s.length>1){let[c,u]=s[s.length-1];switch(c){case-1:u.left=l;break;case 0:Ca(!1);case 1:Ca(!1)}}else o.right=l;let d=this._balanceByStack(s);if(r.length>0){let[c,u]=r[r.length-1];switch(c){case-1:u.left=d;break;case 0:u.mid=d;break;case 1:u.right=d;break}}else this._root=d}}else{let s=o.left??o.right;if(r.length>0){let[a,l]=r[r.length-1];switch(a){case-1:l.left=s;break;case 0:l.mid=s;break;case 1:l.right=s;break}}else this._root=s}this._root=this._balanceByStack(r)??this._root}}_min(t,e){for(;t.left;)e.push([-1,t]),t=t.left;return t}_balanceByStack(t){for(let e=t.length-1;e>=0;e--){let n=t[e][1];n.updateHeight();let r=n.balanceFactor();if(r>1?(n.right.balanceFactor()>=0||(n.right=n.right.rotateRight()),t[e][1]=n.rotateLeft()):r<-1&&(n.left.balanceFactor()<=0||(n.left=n.left.rotateLeft()),t[e][1]=n.rotateRight()),e>0)switch(t[e-1][0]){case-1:t[e-1][1].left=t[e][1];break;case 1:t[e-1][1].right=t[e][1];break;case 0:t[e-1][1].mid=t[e][1];break}else return t[0][1]}}findSubstr(t){let e=this._iter.reset(t),n=this._root,r;for(;n;){let o=e.cmp(n.segment);if(o>0)n=n.left;else if(o<0)n=n.right;else if(e.hasNext())e.next(),r=hr.unwrap(n.value)||r,n=n.mid;else break}return n&&hr.unwrap(n.value)||r}findSuperstr(t){return this._findSuperstrOrElement(t,!1)}_findSuperstrOrElement(t,e){let n=this._iter.reset(t),r=this._root;for(;r;){let o=n.cmp(r.segment);if(o>0)r=r.left;else if(o<0)r=r.right;else if(n.hasNext())n.next(),r=r.mid;else return r.mid?this._entries(r.mid):e?hr.unwrap(r.value):void 0}}hasElementOrSubtree(t){return this._findSuperstrOrElement(t,!0)!==void 0}forEach(t){for(let[e,n]of this)t(n,e)}*[Symbol.iterator](){yield*this._entries(this._root)}_entries(t){let e=[];return this._dfsEntries(t,e),e[Symbol.iterator]()}_dfsEntries(t,e){t&&(t.left&&this._dfsEntries(t.left,e),t.value!==void 0&&e.push([t.key,hr.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 Te=$("fileService");function vr(i){return i.create===!0}function nn(i){return!!(i.capabilities&2)}function Nb(i){return!!(i.capabilities&524288)}function om(i){return!!(i.capabilities&8)}function Ub(i){return!!(i.capabilities&131072)}function Fb(i){return!!(i.capabilities&262144)}function Sr(i){return!!(i.capabilities&4)}function oc(i){return!!(i.capabilities&16)}function sc(i){return nn(i)?!!(i.capabilities&16384):!1}function sm(i){return nn(i)?!!(i.capabilities&32768):!1}function Wb(i){return!!(i.capabilities&65536)}var Vo=class i extends Error{constructor(e,n){super(e);this.code=n}static create(e,n){let r=new i(e.toString(),n);return Z0(r,n),r}};function he(i,t){return Vo.create(i,t)}function br(i){return i||he(g(2456,null),"Unknown")}function Z0(i,t){return i.name=t?`${t} (FileSystemError)`:"FileSystemError",i}function qt(i){if(!i)return"Unknown";if(i instanceof Vo)return i.code;let t=/^(.+) \(FileSystemError\)$/.exec(i.name);if(!t)return"Unknown";switch(t[1]){case"EntryExists":return"EntryExists";case"EntryIsADirectory":return"EntryIsADirectory";case"EntryNotADirectory":return"EntryNotADirectory";case"EntryNotFound":return"EntryNotFound";case"EntryTooLarge":return"EntryTooLarge";case"EntryWriteLocked":return"EntryWriteLocked";case"NoPermissions":return"NoPermissions";case"Unavailable":return"Unavailable"}return"Unknown"}function Ja(i){if(i instanceof Ke)return i.fileOperationResult;switch(qt(i)){case"EntryNotFound":return 1;case"EntryIsADirectory":return 0;case"EntryNotADirectory":return 9;case"EntryWriteLocked":return 5;case"NoPermissions":return 6;case"EntryExists":return 4;case"EntryTooLarge":return 7;default:return 10}}var yr=class{constructor(t,e,n){this.resource=t;this.operation=e;this.target=n}isOperation(t){return this.operation===t}};var rc=class i{constructor(t,e){this.ignorePathCasing=e;this.correlationId=void 0;this.added=new Le(()=>{let t=Fn.forUris(()=>this.ignorePathCasing);return t.fill(this.rawAdded.map(e=>[e,!0])),t});this.updated=new Le(()=>{let t=Fn.forUris(()=>this.ignorePathCasing);return t.fill(this.rawUpdated.map(e=>[e,!0])),t});this.deleted=new Le(()=>{let t=Fn.forUris(()=>this.ignorePathCasing);return t.fill(this.rawDeleted.map(e=>[e,!0])),t});this.rawAdded=[];this.rawUpdated=[];this.rawDeleted=[];for(let n of t){switch(n.type){case 1:this.rawAdded.push(n.resource);break;case 0:this.rawUpdated.push(n.resource);break;case 2:this.rawDeleted.push(n.resource);break}this.correlationId!==i.MIXED_CORRELATION&&(typeof n.cId=="number"?this.correlationId===void 0?this.correlationId=n.cId:this.correlationId!==n.cId&&(this.correlationId=i.MIXED_CORRELATION):this.correlationId!==void 0&&(this.correlationId=i.MIXED_CORRELATION))}}static{this.MIXED_CORRELATION=null}contains(t,...e){return this.doContains(t,{includeChildren:!1},...e)}affects(t,...e){return this.doContains(t,{includeChildren:!0},...e)}doContains(t,e,...n){if(!t)return!1;let r=n.length>0;return!!((!r||n.includes(1))&&(this.added.value.get(t)||e.includeChildren&&this.added.value.findSuperstr(t))||(!r||n.includes(0))&&(this.updated.value.get(t)||e.includeChildren&&this.updated.value.findSuperstr(t))||(!r||n.includes(2))&&(this.deleted.value.findSubstr(t)||e.includeChildren&&this.deleted.value.findSuperstr(t)))}gotAdded(){return this.rawAdded.length>0}gotDeleted(){return this.rawDeleted.length>0}gotUpdated(){return this.rawUpdated.length>0}correlates(t){return this.correlationId===t}hasCorrelation(){return typeof this.correlationId=="number"}};function $b(i,t,e){return!i||!t||i===t||t.length>i.length?!1:(t.charAt(t.length-1)!==be&&(t+=be),e?jr(i,t):i.indexOf(t)===0)}var Ke=class extends Error{constructor(e,n,r){super(e);this.fileOperationResult=n;this.options=r}},zo=class extends Ke{constructor(e,n,r,o){super(e,n,o);this.fileOperationResult=n;this.size=r}},jo=class extends Ke{constructor(e,n,r){super(e,2,r);this.stat=n}};var ac="";function am(i){if(!(typeof i.size!="number"||typeof i.mtime!="number"))return i.mtime.toString(29)+i.size.toString(31)}var ic=class i{static{this.KB=1024}static{this.MB=i.KB*i.KB}static{this.GB=i.MB*i.KB}static{this.TB=i.GB*i.KB}static formatSize(t){return Pi(t)||(t=0),t<i.KB?g(2451,null,t.toFixed(0)):t<i.MB?g(2453,null,(t/i.KB).toFixed(2)):t<i.GB?g(2454,null,(t/i.MB).toFixed(2)):t<i.TB?g(2452,null,(t/i.GB).toFixed(2)):g(2455,null,(t/i.TB).toFixed(2))}};var Ir=class{constructor(t,e=[],n=!1){this.ctor=t,this.staticArguments=e,this.supportsDelayedInstantiation=n}};var lm=class{constructor(t,e){this.key=t;this.data=e;this.incoming=new Map;this.outgoing=new Map}},Ya=class{constructor(t){this._hashFn=t;this._nodes=new Map}roots(){let t=[];for(let e of this._nodes.values())e.outgoing.size===0&&t.push(e);return t}insertEdge(t,e){let n=this.lookupOrInsertNode(t),r=this.lookupOrInsertNode(e);n.outgoing.set(r.key,r),r.incoming.set(n.key,n)}removeNode(t){let e=this._hashFn(t);this._nodes.delete(e);for(let n of this._nodes.values())n.outgoing.delete(e),n.incoming.delete(e)}lookupOrInsertNode(t){let e=this._hashFn(t),n=this._nodes.get(e);return n||(n=new lm(e,t),this._nodes.set(e,n)),n}lookup(t){return this._nodes.get(this._hashFn(t))}isEmpty(){return this._nodes.size===0}toString(){let t=[];for(let[e,n]of this._nodes)t.push(`${e}
	(-> incoming)[${[...n.incoming.keys()].join(", ")}]
	(outgoing ->)[${[...n.outgoing.keys()].join(",")}]
`);return t.join(`
`)}findCycleSlow(){for(let[t,e]of this._nodes){let n=new Set([t]),r=this._findCycle(e,n);if(r)return r}}_findCycle(t,e){for(let[n,r]of t.outgoing){if(e.has(n))return[...e,n].join(" -> ");e.add(n);let o=this._findCycle(r,e);if(o)return o;e.delete(n)}}};var ri=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 eE=!1,lc=class extends Error{constructor(t){super("cyclic dependency between services"),this.message=t.findCycleSlow()??`UNABLE to detect cycle, dumping graph: 
${t.toString()}`}},Ko=class i{constructor(t=new ri,e=!1,n,r=eE){this._services=t;this._strict=e;this._parent=n;this._enableTracing=r;this._isDisposed=!1;this._servicesToMaybeDispose=new Set;this._children=new Set;this._activeInstantiations=new Set;this._services.set(ke,this),this._globalGraph=r?n?._globalGraph??new Ya(o=>o):void 0}dispose(){if(!this._isDisposed){this._isDisposed=!0,Tt(this._children),this._children.clear();for(let t of this._servicesToMaybeDispose)So(t)&&t.dispose();this._servicesToMaybeDispose.clear()}}_throwIfDisposed(){if(this._isDisposed)throw new Error("InstantiationService has been disposed")}createChild(t,e){this._throwIfDisposed();let n=this,r=new class extends i{dispose(){n._children.delete(r),super.dispose()}}(t,this._strict,this,this._enableTracing);return this._children.add(r),e?.add(r),r}invokeFunction(t,...e){this._throwIfDisposed();let n=Qa.traceInvocation(this._enableTracing,t),r=!1;try{return t({get:s=>{if(r)throw ud("service accessor is only valid during the invocation of its target method");let a=this._getOrCreateServiceInstance(s,n);return a||this._throwIfStrict(`[invokeFunction] unknown service '${s}'`,!1),a}},...e)}finally{r=!0,n.stop()}}createInstance(t,...e){this._throwIfDisposed();let n,r;return t instanceof Ir?(n=Qa.traceCreation(this._enableTracing,t.ctor),r=this._createInstance(t.ctor,t.staticArguments.concat(e),n)):(n=Qa.traceCreation(this._enableTracing,t),r=this._createInstance(t,e,n)),n.stop(),r}_createInstance(t,e=[],n){let r=Tn.getServiceDependencies(t).sort((a,l)=>a.index-l.index),o=[];for(let a of r){let l=this._getOrCreateServiceInstance(a.id,n);l||this._throwIfStrict(`[createInstance] ${t.name} depends on UNKNOWN service ${a.id}.`,!1),o.push(l)}let s=r.length>0?r[0].index:e.length;if(e.length!==s){console.trace(`[createInstance] First service dependency of ${t.name} at position ${s+1} conflicts with ${e.length} static arguments`);let a=s-e.length;a>0?e=e.concat(new Array(a)):e=e.slice(0,s)}return Reflect.construct(t,e.concat(o))}_setCreatedServiceInstance(t,e){if(this._services.get(t)instanceof Ir)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 Ir?this._safeCreateAndCacheServiceInstance(t,n,e.branch(t,!0)):(e.branch(t,!1),n)}_safeCreateAndCacheServiceInstance(t,e,n){if(this._activeInstantiations.has(t))throw new Error(`illegal state - RECURSIVELY instantiating service '${t}'`);this._activeInstantiations.add(t);try{return this._createAndCacheServiceInstance(t,e,n)}finally{this._activeInstantiations.delete(t)}}_createAndCacheServiceInstance(t,e,n){let r=new Ya(l=>l.id.toString()),o=0,s=[{id:t,desc:e,_trace:n}],a=new Set;for(;s.length;){let l=s.pop();if(!a.has(String(l.id))){if(a.add(String(l.id)),r.lookupOrInsertNode(l),o++>1e3)throw new lc(r);for(let d of Tn.getServiceDependencies(l.desc.ctor)){let c=this._getServiceInstanceOrDescriptor(d.id);if(c||this._throwIfStrict(`[createInstance] ${t} depends on ${d.id} which is NOT registered.`,!0),this._globalGraph?.insertEdge(String(l.id),String(d.id)),c instanceof Ir){let u={id:d.id,desc:c,_trace:l._trace.branch(d.id,!0)};r.insertEdge(l,u),s.push(u)}}}}for(;;){let l=r.roots();if(l.length===0){if(!r.isEmpty())throw new lc(r);break}for(let{data:d}of l){if(this._getServiceInstanceOrDescriptor(d.id)instanceof Ir){let u=this._createServiceInstanceWithOwner(d.id,d.desc.ctor,d.desc.staticArguments,d.desc.supportsDelayedInstantiation,d._trace);this._setCreatedServiceInstance(d.id,u)}r.removeNode(d)}}return this._getServiceInstanceOrDescriptor(t)}_createServiceInstanceWithOwner(t,e,n=[],r,o){if(this._services.get(t)instanceof Ir)return this._createServiceInstance(t,e,n,r,o,this._servicesToMaybeDispose);if(this._parent)return this._parent._createServiceInstanceWithOwner(t,e,n,r,o);throw new Error(`illegalState - creating UNKNOWN service instance ${e.name}`)}_createServiceInstance(t,e,n=[],r,o,s){if(r){let a=new i(void 0,this._strict,this,this._enableTracing);a._globalGraphImplicitDependency=String(t);let l=new Map,d=new Od(()=>{let c=a._createInstance(e,n,o);for(let[u,p]of l){let m=c[u];if(typeof m=="function")for(let h of p)h.disposable=m.apply(c,h.listener)}return l.clear(),s.add(c),c});return new Proxy(Object.create(null),{get(c,u){if(!d.isInitialized&&typeof u=="string"&&(u.startsWith("onDid")||u.startsWith("onWill"))){let h=l.get(u);return h||(h=new wa,l.set(u,h)),(I,b,S)=>{if(d.isInitialized)return d.value[u](I,b,S);{let _={listener:[I,b,S],disposable:void 0},R=h.push(_);return k(()=>{R(),_.disposable?.dispose()})}}}if(u in c)return c[u];let p=d.value,m=p[u];return typeof m!="function"||(m=m.bind(p),c[u]=m),m},set(c,u,p){return d.value[u]=p,!0},getPrototypeOf(c){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 Qa=class i{constructor(t,e){this.type=t;this.name=e;this._start=Date.now();this._dep=[]}static{this.all=new Set}static{this._None=new class extends i{constructor(){super(0,null)}stop(){}branch(){return this}}}static traceInvocation(t,e){return t?new i(2,e.name||new Error().stack.split(`
`).slice(3,4).join(`
`)):i._None}static traceCreation(t,e){return t?new i(1,e.name):i._None}static{this._totals=0}branch(t,e){let n=new i(3,t.toString());return this._dep.push([t,e,n]),n}stop(){let t=Date.now()-this._start;i._totals+=t;let e=!1;function n(o,s){let a=[],l=new Array(o+1).join("	");for(let[d,c,u]of s._dep)if(c&&u){e=!0,a.push(`${l}CREATES -> ${d}`);let p=n(o+1,u);p&&a.push(p)}else a.push(`${l}uses -> ${d}`);return a.join(`
`)}let r=[`${this.type===1?"CREATE":"CALL"} ${this.name}`,`${n(1,this)}`,`DONE, took ${t.toFixed(2)}ms (grand total ${i._totals.toFixed(2)}ms)`];(t>2||e)&&i.all.add(r.join(`
`))}};function rn(i){return cm(i,0)}function cm(i,t){switch(typeof i){case"object":return i===null?_r(349,t):Array.isArray(i)?nE(i,t):rE(i,t);case"string":return qb(i,t);case"boolean":return tE(i,t);case"number":return _r(i,t);case"undefined":return _r(937,t);default:return _r(617,t)}}function _r(i,t){return(t<<5)-t+i|0}function tE(i,t){return _r(i?433:863,t)}function qb(i,t){t=_r(149417,t);for(let e=0,n=i.length;e<n;e++)t=_r(i.charCodeAt(e),t);return t}function nE(i,t){return t=_r(104579,t),i.reduce((e,n)=>cm(n,e),t)}function rE(i,t){return t=_r(181387,t),Object.keys(i).sort().reduce((e,n)=>(e=qb(n,e),cm(i[n],e)),t)}function dm(i,t,e=32){let n=e-t,r=~((1<<n)-1);return(i<<t|(r&i)>>>n)>>>0}function Xa(i,t=32){return i instanceof ArrayBuffer?Zr(A.wrap(new Uint8Array(i))):(i>>>0).toString(16).padStart(t/4,"0")}var Hb=class i{constructor(){this._h0=1732584193;this._h1=4023233417;this._h2=2562383102;this._h3=271733878;this._h4=3285377520;this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}static{this._bigBlock32=new DataView(new ArrayBuffer(320))}update(t){let e=t.length;if(e===0)return;let n=this._buff,r=this._buffLen,o=this._leftoverHighSurrogate,s,a;for(o!==0?(s=o,a=-1,o=0):(s=t.charCodeAt(0),a=0);;){let l=s;if(sS(s))if(a+1<e){let d=t.charCodeAt(a+1);hg(d)?(a++,l=aS(s,d)):l=65533}else{o=s;break}else hg(s)&&(l=65533);if(r=this._push(n,r,l),a++,a<e)s=t.charCodeAt(a);else break}this._buffLen=r,this._leftoverHighSurrogate=o}_push(t,e,n){return n<128?t[e++]=n:n<2048?(t[e++]=192|(n&1984)>>>6,t[e++]=128|(n&63)>>>0):n<65536?(t[e++]=224|(n&61440)>>>12,t[e++]=128|(n&4032)>>>6,t[e++]=128|(n&63)>>>0):(t[e++]=240|(n&1835008)>>>18,t[e++]=128|(n&258048)>>>12,t[e++]=128|(n&4032)>>>6,t[e++]=128|(n&63)>>>0),e>=64&&(this._step(),e-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),e}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),Xa(this._h0)+Xa(this._h1)+Xa(this._h2)+Xa(this._h3)+Xa(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,this._buff.subarray(this._buffLen).fill(0),this._buffLen>56&&(this._step(),this._buff.fill(0));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=i._bigBlock32,e=this._buffDV;for(let u=0;u<64;u+=4)t.setUint32(u,e.getUint32(u,!1),!1);for(let u=64;u<320;u+=4)t.setUint32(u,dm(t.getUint32(u-12,!1)^t.getUint32(u-32,!1)^t.getUint32(u-56,!1)^t.getUint32(u-64,!1),1),!1);let n=this._h0,r=this._h1,o=this._h2,s=this._h3,a=this._h4,l,d,c;for(let u=0;u<80;u++)u<20?(l=r&o|~r&s,d=1518500249):u<40?(l=r^o^s,d=1859775393):u<60?(l=r&o|r&s|o&s,d=2400959708):(l=r^o^s,d=3395469782),c=dm(n,5)+l+a+d+t.getUint32(u*4,!1)&4294967295,a=s,s=o,o=dm(r,30),r=n,n=c;this._h0=this._h0+n&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+o&4294967295,this._h3=this._h3+s&4294967295,this._h4=this._h4+a&4294967295}};function um(...i){switch(i.length){case 1:return g(2254,null,i[0]);case 2:return g(2255,null,i[0],i[1]);case 3:return g(2256,null,i[0],i[1],i[2]);default:return}}var iE=g(2253,null),oE=g(2252,null),ii=class i{constructor(){this._input="";this._start=0;this._current=0;this._tokens=[];this._errors=[];this.stringRe=/[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy}static getLexeme(t){switch(t.type){case 0:return"(";case 1:return")";case 2:return"!";case 3:return t.isTripleEq?"===":"==";case 4:return t.isTripleEq?"!==":"!=";case 5:return"<";case 6:return"<=";case 7:return">";case 8:return">=";case 9:return"=~";case 10:return t.lexeme;case 11:return"true";case 12:return"false";case 13:return"in";case 14:return"not";case 15:return"&&";case 16:return"||";case 17:return t.lexeme;case 18:return t.lexeme;case 19:return t.lexeme;case 20:return"EOF";default:throw ud(`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(um("==","=~"));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(um("&&"));break;case 124:this._match(124)?this._addToken(16):this._error(um("||"));break;case 32:case 13:case 9:case 10:case 160:break;default:this._string()}return this._start=this._current,this._addToken(20),Array.from(this._tokens)}_match(t){return this._isAtEnd()||this._input.charCodeAt(this._current)!==t?!1:(this._current++,!0)}_advance(){return this._input.charCodeAt(this._current++)}_peek(){return this._isAtEnd()?0:this._input.charCodeAt(this._current)}_addToken(t){this._tokens.push({type:t,offset:this._start})}_error(t){let e=this._start,n=this._input.substring(this._start,this._current),r={type:19,offset:this._start,lexeme:n};this._errors.push({offset:e,lexeme:n,additionalInfo:t}),this._tokens.push(r)}_string(){this.stringRe.lastIndex=this._start;let t=this.stringRe.exec(this._input);if(t){this._current=this._start+t[0].length;let e=this._input.substring(this._start,this._current),n=i._keywords.get(e);n?this._addToken(n):this._tokens.push({type:17,lexeme:e,offset:this._start})}}_quotedString(){for(;this._peek()!==39&&!this._isAtEnd();)this._advance();if(this._isAtEnd()){this._error(iE);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(oE);return}let o=this._input.charCodeAt(t);if(e)e=!1;else if(o===47&&!n){t++;break}else o===91?n=!0:o===92?e=!0:o===93&&(n=!1);t++}for(;t<this._input.length&&i._regexFlags.has(this._input.charCodeAt(t));)t++;this._current=t;let r=this._input.substring(this._start,this._current);this._tokens.push({type:10,lexeme:r,offset:this._start})}_isAtEnd(){return this._current>=this._input.length}};var rt=new Map;rt.set("false",!1);rt.set("true",!0);rt.set("isMac",et);rt.set("isLinux",Se);rt.set("isWindows",G);rt.set("isWeb",Et);rt.set("isMacNative",et&&!Et);rt.set("isEdge",$v);rt.set("isFirefox",Fv);rt.set("isChrome",ig);rt.set("isSafari",Wv);var sE=Object.prototype.hasOwnProperty;var aE={regexParsingWithErrorRecovery:!0},lE=g(2233,null),dE=g(2234,null),cE=g(2236,null),Bb=g(2232,null),uE=g(2239,null),pE=g(2240,null),fE=g(2237,null),gE=g(2238,null),pm=class i{constructor(t=aE){this._config=t;this._scanner=new ii;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:lE,offset:0,lexeme:"",additionalInfo:dE});return}this._tokens=this._scanner.reset(t).scan(),this._current=0,this._parsingErrors=[];try{let e=this._expr();if(!this._isAtEnd()){let n=this._peek(),r=n.type===17?pE:void 0;throw this._parsingErrors.push({message:uE,offset:n.offset,lexeme:ii.getLexeme(n),additionalInfo:r}),i._parseError}return e}catch(e){if(e!==i._parseError)throw e;return}}_expr(){return this._or()}_or(){let t=[this._and()];for(;this._matchOne(16);){let e=this._and();t.push(e)}return t.length===1?t[0]:pt.or(...t)}_and(){let t=[this._term()];for(;this._matchOne(15);){let e=this._term();t.push(e)}return t.length===1?t[0]:pt.and(...t)}_term(){if(this._matchOne(2)){let t=this._peek();switch(t.type){case 11:return this._advance(),bt.INSTANCE;case 12:return this._advance(),wt.INSTANCE;case 0:{this._advance();let e=this._expr();return this._consume(1,Bb),e?.negate()}case 17:return this._advance(),ji.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(),pt.true();case 12:return this._advance(),pt.false();case 0:{this._advance();let e=this._expr();return this._consume(1,Bb),e}case 17:{let e=t.lexeme;if(this._advance(),this._matchOne(9)){let r=this._peek();if(!this._config.regexParsingWithErrorRecovery){if(this._advance(),r.type!==10)throw this._errExpectedButGot("REGEX",r);let o=r.lexeme,s=o.lastIndexOf("/"),a=s===o.length-1?void 0:this._removeFlagsGY(o.substring(s+1)),l;try{l=new RegExp(o.substring(1,s),a)}catch{throw this._errExpectedButGot("REGEX",r)}return ol.create(e,l)}switch(r.type){case 10:case 19:{let o=[r.lexeme];this._advance();let s=this._peek(),a=0;for(let p=0;p<r.lexeme.length;p++)r.lexeme.charCodeAt(p)===40?a++:r.lexeme.charCodeAt(p)===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 p=0;p<s.lexeme.length;p++)s.lexeme.charCodeAt(p)===40?a++:r.lexeme.charCodeAt(p)===41&&a--}if(a<0)break;o.push(ii.getLexeme(s)),this._advance(),s=this._peek()}let l=o.join(""),d=l.lastIndexOf("/"),c=d===l.length-1?void 0:this._removeFlagsGY(l.substring(d+1)),u;try{u=new RegExp(l.substring(1,d),c)}catch{throw this._errExpectedButGot("REGEX",r)}return pt.regex(e,u)}case 18:{let o=r.lexeme;this._advance();let s=null;if(!tS(o)){let a=o.indexOf("/"),l=o.lastIndexOf("/");if(a!==l&&a>=0){let d=o.slice(a+1,l),c=o[l+1]==="i"?"i":"";try{s=new RegExp(d,c)}catch{throw this._errExpectedButGot("REGEX",r)}}}if(s===null)throw this._errExpectedButGot("REGEX",r);return ol.create(e,s)}default:throw this._errExpectedButGot("REGEX",this._peek())}}if(this._matchOne(14)){this._consume(13,cE);let r=this._value();return pt.notIn(e,r)}switch(this._peek().type){case 3:{this._advance();let r=this._value();if(this._previous().type===18)return pt.equals(e,r);switch(r){case"true":return pt.has(e);case"false":return pt.not(e);default:return pt.equals(e,r)}}case 4:{this._advance();let r=this._value();if(this._previous().type===18)return pt.notEquals(e,r);switch(r){case"true":return pt.not(e);case"false":return pt.has(e);default:return pt.notEquals(e,r)}}case 5:return this._advance(),rl.create(e,this._value());case 6:return this._advance(),il.create(e,this._value());case 7:return this._advance(),Go.create(e,this._value());case 8:return this._advance(),nl.create(e,this._value());case 13:return this._advance(),pt.in(e,this._value());default:return pt.has(e)}}case 20:throw this._parsingErrors.push({message:fE,offset:t.offset,lexeme:"",additionalInfo:gE}),i._parseError;default:throw this._errExpectedButGot(`true | false | KEY 
	| KEY '=~' REGEX 
	| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`,this._peek())}}_value(){let t=this._peek();switch(t.type){case 17:case 18:return this._advance(),t.lexeme;case 11:return this._advance(),"true";case 12:return this._advance(),"false";case 13:return this._advance(),"in";default:return""}}_removeFlagsGY(t){return t.replaceAll(this._flagsGYRe,"")}_previous(){return this._tokens[this._current-1]}_matchOne(t){return this._check(t)?(this._advance(),!0):!1}_advance(){return this._isAtEnd()||this._current++,this._previous()}_consume(t,e){if(this._check(t))return this._advance();throw this._errExpectedButGot(e,this._peek())}_errExpectedButGot(t,e,n){let r=g(2235,null,t,ii.getLexeme(e)),o=e.offset,s=ii.getLexeme(e);return this._parsingErrors.push({message:r,offset:o,lexeme:s,additionalInfo:n}),i._parseError}_check(t){return this._peek().type===t}_peek(){return this._tokens[this._current]}_isAtEnd(){return this._peek().type===20}},pt=class{static false(){return bt.INSTANCE}static true(){return wt.INSTANCE}static has(t){return zi.create(t)}static equals(t,e){return el.create(t,e)}static notEquals(t,e){return tl.create(t,e)}static regex(t,e){return ol.create(t,e)}static in(t,e){return dc.create(t,e)}static notIn(t,e){return cc.create(t,e)}static not(t){return ji.create(t)}static and(...t){return uc.create(t,null,!0)}static or(...t){return sl.create(t,null,!0)}static greater(t,e){return Go.create(t,e)}static greaterEquals(t,e){return nl.create(t,e)}static smaller(t,e){return rl.create(t,e)}static smallerEquals(t,e){return il.create(t,e)}static{this._parser=new pm({regexParsingWithErrorRecovery:!1})}static deserialize(t){return t==null?void 0:this._parser.parse(t)}};function Za(i,t){return i.cmp(t)}var bt=class i{constructor(){this.type=0}static{this.INSTANCE=new i}cmp(t){return this.type-t.type}equals(t){return t.type===this.type}substituteConstants(){return this}evaluate(t){return!1}serialize(){return"false"}keys(){return[]}map(t){return this}negate(){return wt.INSTANCE}},wt=class i{constructor(){this.type=1}static{this.INSTANCE=new i}cmp(t){return this.type-t.type}equals(t){return t.type===this.type}substituteConstants(){return this}evaluate(t){return!0}serialize(){return"true"}keys(){return[]}map(t){return this}negate(){return bt.INSTANCE}},zi=class i{constructor(t,e){this.key=t;this.negated=e;this.type=2}static create(t,e=null){let n=rt.get(t);return typeof n=="boolean"?n?wt.INSTANCE:bt.INSTANCE:new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:jb(this.key,t.key)}equals(t){return t.type===this.type?this.key===t.key:!1}substituteConstants(){let t=rt.get(this.key);return typeof t=="boolean"?t?wt.INSTANCE:bt.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=ji.create(this.key,this)),this.negated}},el=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=4}static create(t,e,n=null){if(typeof e=="boolean")return e?zi.create(t,n):ji.create(t,n);let r=rt.get(t);return typeof r=="boolean"?e===(r?"true":"false")?wt.INSTANCE:bt.INSTANCE:new i(t,e,n)}cmp(t){return t.type!==this.type?this.type-t.type:Ki(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=rt.get(this.key);if(typeof t=="boolean"){let e=t?"true":"false";return this.value===e?wt.INSTANCE:bt.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=tl.create(this.key,this.value,this)),this.negated}},dc=class i{constructor(t,e){this.key=t;this.valueKey=e;this.type=10;this.negated=null}static create(t,e){return new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:Ki(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(G&&typeof n=="string"&&n.startsWith("file:///")){let r=n.toLowerCase();return e.some(o=>typeof o=="string"&&o.toLowerCase()===r)}return!1}if(typeof n=="string"&&typeof e=="object"&&e!==null){if(sE.call(e,n))return!0;if(G&&n.startsWith("file:///")){let r=n.toLowerCase();return Object.keys(e).some(o=>o.toLowerCase()===r)}return!1}return!1}serialize(){return`${this.key} in '${this.valueKey}'`}keys(){return[this.key,this.valueKey]}map(t){return t.mapIn(this.key,this.valueKey)}negate(){return this.negated||(this.negated=cc.create(this.key,this.valueKey)),this.negated}},cc=class i{constructor(t,e){this.key=t;this.valueKey=e;this.type=11;this._negated=dc.create(t,e)}static create(t,e){return new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:this._negated.cmp(t._negated)}equals(t){return t.type===this.type?this._negated.equals(t._negated):!1}substituteConstants(){return this}evaluate(t){return!this._negated.evaluate(t)}serialize(){return`${this.key} not in '${this.valueKey}'`}keys(){return this._negated.keys()}map(t){return t.mapNotIn(this.key,this.valueKey)}negate(){return this._negated}},tl=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=5}static create(t,e,n=null){if(typeof e=="boolean")return e?ji.create(t,n):zi.create(t,n);let r=rt.get(t);return typeof r=="boolean"?e===(r?"true":"false")?bt.INSTANCE:wt.INSTANCE:new i(t,e,n)}cmp(t){return t.type!==this.type?this.type-t.type:Ki(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=rt.get(this.key);if(typeof t=="boolean"){let e=t?"true":"false";return this.value===e?bt.INSTANCE:wt.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=el.create(this.key,this.value,this)),this.negated}},ji=class i{constructor(t,e){this.key=t;this.negated=e;this.type=3}static create(t,e=null){let n=rt.get(t);return typeof n=="boolean"?n?bt.INSTANCE:wt.INSTANCE:new i(t,e)}cmp(t){return t.type!==this.type?this.type-t.type:jb(this.key,t.key)}equals(t){return t.type===this.type?this.key===t.key:!1}substituteConstants(){let t=rt.get(this.key);return typeof t=="boolean"?t?bt.INSTANCE:wt.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=zi.create(this.key,this)),this.negated}};function fc(i,t){if(typeof i=="string"){let e=parseFloat(i);isNaN(e)||(i=e)}return typeof i=="string"||typeof i=="number"?t(i):bt.INSTANCE}var Go=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=12}static create(t,e,n=null){return fc(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Ki(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=il.create(this.key,this.value,this)),this.negated}},nl=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=13}static create(t,e,n=null){return fc(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Ki(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=rl.create(this.key,this.value,this)),this.negated}},rl=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=14}static create(t,e,n=null){return fc(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Ki(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=nl.create(this.key,this.value,this)),this.negated}},il=class i{constructor(t,e,n){this.key=t;this.value=e;this.negated=n;this.type=15}static create(t,e,n=null){return fc(e,r=>new i(t,r,n))}cmp(t){return t.type!==this.type?this.type-t.type:Ki(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=Go.create(this.key,this.value,this)),this.negated}},ol=class i{constructor(t,e){this.key=t;this.regexp=e;this.type=7;this.negated=null}static create(t,e){return new i(t,e)}cmp(t){if(t.type!==this.type)return this.type-t.type;if(this.key<t.key)return-1;if(this.key>t.key)return 1;let e=this.regexp?this.regexp.source:"",n=t.regexp?t.regexp.source:"";return e<n?-1:e>n?1:0}equals(t){if(t.type===this.type){let e=this.regexp?this.regexp.source:"",n=t.regexp?t.regexp.source:"";return this.key===t.key&&e===n}return!1}substituteConstants(){return this}evaluate(t){let e=t.getValue(this.key);return this.regexp?this.regexp.test(e):!1}serialize(){let t=this.regexp?`/${this.regexp.source}/${this.regexp.flags}`:"/invalid/";return`${this.key} =~ ${t}`}keys(){return[this.key]}map(t){return t.mapRegex(this.key,this.regexp)}negate(){return this.negated||(this.negated=fm.create(this)),this.negated}},fm=class i{constructor(t){this._actual=t;this.type=8}static create(t){return new i(t)}cmp(t){return t.type!==this.type?this.type-t.type:this._actual.cmp(t._actual)}equals(t){return t.type===this.type?this._actual.equals(t._actual):!1}substituteConstants(){return this}evaluate(t){return!this._actual.evaluate(t)}serialize(){return`!(${this._actual.serialize()})`}keys(){return this._actual.keys()}map(t){return new i(this._actual.map(t))}negate(){return this._actual}};function zb(i){let t=null;for(let e=0,n=i.length;e<n;e++){let r=i[e].substituteConstants();if(i[e]!==r&&t===null){t=[];for(let o=0;o<e;o++)t[o]=i[o]}t!==null&&(t[e]=r)}return t===null?i:t}var uc=class i{constructor(t,e){this.expr=t;this.negated=e;this.type=6}static create(t,e,n){return i._normalizeArr(t,e,n)}cmp(t){if(t.type!==this.type)return this.type-t.type;if(this.expr.length<t.expr.length)return-1;if(this.expr.length>t.expr.length)return 1;for(let e=0,n=this.expr.length;e<n;e++){let r=Za(this.expr[e],t.expr[e]);if(r!==0)return r}return 0}equals(t){if(t.type===this.type){if(this.expr.length!==t.expr.length)return!1;for(let e=0,n=this.expr.length;e<n;e++)if(!this.expr[e].equals(t.expr[e]))return!1;return!0}return!1}substituteConstants(){let t=zb(this.expr);return t===this.expr?this:i.create(t,this.negated,!1)}evaluate(t){for(let e=0,n=this.expr.length;e<n;e++)if(!this.expr[e].evaluate(t))return!1;return!0}static _normalizeArr(t,e,n){let r=[],o=!1;for(let s of t)if(s){if(s.type===1){o=!0;continue}if(s.type===0)return bt.INSTANCE;if(s.type===6){r.push(...s.expr);continue}r.push(s)}if(r.length===0&&o)return wt.INSTANCE;if(r.length!==0){if(r.length===1)return r[0];r.sort(Za);for(let s=1;s<r.length;s++)r[s-1].equals(r[s])&&(r.splice(s,1),s--);if(r.length===1)return r[0];for(;r.length>1;){let s=r[r.length-1];if(s.type!==9)break;r.pop();let a=r.pop(),l=r.length===0,d=sl.create(s.expr.map(c=>i.create([c,a],null,n)),null,l);d&&(r.push(d),r.sort(Za))}if(r.length===1)return r[0];if(n){for(let s=0;s<r.length;s++)for(let a=s+1;a<r.length;a++)if(r[s].negate().equals(r[a]))return bt.INSTANCE;if(r.length===1)return r[0]}return new i(r,e)}}serialize(){return this.expr.map(t=>t.serialize()).join(" && ")}keys(){let t=[];for(let e of this.expr)t.push(...e.keys());return t}map(t){return new i(this.expr.map(e=>e.map(t)),null)}negate(){if(!this.negated){let t=[];for(let e of this.expr)t.push(e.negate());this.negated=sl.create(t,this,!0)}return this.negated}},sl=class i{constructor(t,e){this.expr=t;this.negated=e;this.type=9}static create(t,e,n){return i._normalizeArr(t,e,n)}cmp(t){if(t.type!==this.type)return this.type-t.type;if(this.expr.length<t.expr.length)return-1;if(this.expr.length>t.expr.length)return 1;for(let e=0,n=this.expr.length;e<n;e++){let r=Za(this.expr[e],t.expr[e]);if(r!==0)return r}return 0}equals(t){if(t.type===this.type){if(this.expr.length!==t.expr.length)return!1;for(let e=0,n=this.expr.length;e<n;e++)if(!this.expr[e].equals(t.expr[e]))return!1;return!0}return!1}substituteConstants(){let t=zb(this.expr);return t===this.expr?this:i.create(t,this.negated,!1)}evaluate(t){for(let e=0,n=this.expr.length;e<n;e++)if(this.expr[e].evaluate(t))return!0;return!1}static _normalizeArr(t,e,n){let r=[],o=!1;if(t){for(let s=0,a=t.length;s<a;s++){let l=t[s];if(l){if(l.type===0){o=!0;continue}if(l.type===1)return wt.INSTANCE;if(l.type===9){r=r.concat(l.expr);continue}r.push(l)}}if(r.length===0&&o)return bt.INSTANCE;r.sort(Za)}if(r.length!==0){if(r.length===1)return r[0];for(let s=1;s<r.length;s++)r[s-1].equals(r[s])&&(r.splice(s,1),s--);if(r.length===1)return r[0];if(n){for(let s=0;s<r.length;s++)for(let a=s+1;a<r.length;a++)if(r[s].negate().equals(r[a]))return wt.INSTANCE;if(r.length===1)return r[0]}return new i(r,e)}}serialize(){return this.expr.map(t=>t.serialize()).join(" || ")}keys(){let t=[];for(let e of this.expr)t.push(...e.keys());return t}map(t){return new i(this.expr.map(e=>e.map(t)),null)}negate(){if(!this.negated){let t=[];for(let e of this.expr)t.push(e.negate());for(;t.length>1;){let e=t.shift(),n=t.shift(),r=[];for(let o of Vb(e))for(let s of Vb(n))r.push(uc.create([o,s],null,!1));t.unshift(i.create(r,null,!1))}this.negated=i.create(t,this,!0)}return this.negated}},pc=class i extends zi{static{this._info=[]}static all(){return i._info.values()}constructor(t,e,n){super(t,null),this._defaultValue=e,typeof n=="object"?i._info.push({...n,key:t}):n!==!0&&i._info.push({key:t,description:n,type:e!=null?typeof e:void 0})}bindTo(t){return t.createKey(this.key,this._defaultValue)}getValue(t){return t.getContextKeyValue(this.key)}toNegated(){return this.negate()}isEqualTo(t){return el.create(this.key,t)}notEqualsTo(t){return tl.create(this.key,t)}greater(t){return Go.create(this.key,t)}},Z3=$("contextKeyService");function jb(i,t){return i<t?-1:i>t?1:0}function Ki(i,t,e,n){return i<e?-1:i>e?1:t<n?-1:t>n?1:0}function Vb(i){return i.type===9?i.expr:[i]}var O=$("logService"),Gb=$("loggerService");function mm(i){return Pi(i)}var Jb=3;function mE(i,t){return i!==0&&i<=t}function hE(i,t,e){switch(t){case 1:i.trace(e);break;case 2:i.debug(e);break;case 3:i.info(e);break;case 4:i.warn(e);break;case 5:i.error(e);break;case 0:break;default:throw new Error(`Invalid log level ${t}`)}}var Yb=!1,Kb=!1,yE=!1;function al(i,t){switch(i){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 Qb(i){let t={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn},e=(r,o,s)=>{if(!yE){Kb=!0;try{hE(i,o,Cr(s))}catch{}finally{Kb=!1}}t[r].apply(console,s)},n={debug:(...r)=>e("debug",2,r),error:(...r)=>e("error",5,r),info:(...r)=>e("info",3,r),log:(...r)=>e("log",3,r),warn:(...r)=>e("warn",4,r)};return al("debug",n.debug),al("error",n.error),al("info",n.info),al("log",n.log),al("warn",n.warn),k(()=>{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 Cr(i,t=!1){let e="";for(let n=0;n<i.length;n++){let r=i[n];if(r instanceof Error&&(r=xt(r,t)),typeof r=="object")try{r=JSON.stringify(r)}catch{}e+=(n>0?" ":"")+r}return e}var gc=class extends T{constructor(){super(...arguments);this.level=Jb;this._onDidChangeLogLevel=this._register(new w)}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 mE(this.level,e)}canLog(e){return this._store.isDisposed?!1:this.checkLogLevel(e)}},Gi=class extends gc{constructor(e){super();this.logAlways=e}checkLogLevel(e){return this.logAlways||super.checkLogLevel(e)}trace(e,...n){this.canLog(1)&&this.log(1,Cr([e,...n],!0))}debug(e,...n){this.canLog(2)&&this.log(2,Cr([e,...n]))}info(e,...n){this.canLog(3)&&this.log(3,Cr([e,...n]))}warn(e,...n){this.canLog(4)&&this.log(4,Cr([e,...n]))}error(e,...n){if(this.canLog(5))if(e instanceof Error){let r=Array.prototype.slice.call(arguments);r[0]=e.stack,this.log(5,Cr(r))}else this.log(5,Cr([e,...n]))}flush(){}};var mc=class extends gc{constructor(e){super();this.loggers=e;e.length&&this.setLevel(e[0].getLevel())}setLevel(e){for(let n of this.loggers)n.setLevel(e);super.setLevel(e)}trace(e,...n){for(let r of this.loggers)r.trace(e,...n)}debug(e,...n){for(let r of this.loggers)r.debug(e,...n)}info(e,...n){for(let r of this.loggers)r.info(e,...n)}warn(e,...n){for(let r of this.loggers)r.warn(e,...n)}error(e,...n){for(let r of this.loggers)r.error(e,...n)}flush(){for(let e of this.loggers)e.flush()}dispose(){for(let e of this.loggers)e.dispose();super.dispose()}},ll=class extends T{constructor(e,n,r){super();this.logLevel=e;this.logsHome=n;this._loggers=new Oe;this._onDidChangeLoggers=this._register(new w);this.onDidChangeLoggers=this._onDidChangeLoggers.event;this._onDidChangeLogLevel=this._register(new w);this.onDidChangeLogLevel=this._onDidChangeLogLevel.event;this._onDidChangeVisibility=this._register(new w);this.onDidChangeVisibility=this._onDidChangeVisibility.event;if(r)for(let o of r)this._loggers.set(o.resource,{logger:void 0,info:o})}getLoggerEntry(e){return Ne(e)?[...this._loggers.values()].find(n=>n.info.id===e):this._loggers.get(e)}getLogger(e){return this.getLoggerEntry(e)?.logger}createLogger(e,n){let r=this.toResource(e),o=Ne(e)?e:n?.id??rn(r.toString()).toString(16),s=this._loggers.get(r)?.logger,a=n?.logLevel==="always"?1:n?.logLevel;s||(s=this.doCreateLogger(r,a??this.getLogLevel(r)??this.logLevel,{...n,id:o}));let l={logger:s,info:{resource:r,id:o,logLevel:a,name:n?.name,hidden:n?.hidden,group:n?.group,extensionId:n?.extensionId,when:n?.when}};return this.registerLogger(l.info),this._loggers.set(r,l),s}toResource(e){return Ne(e)?X(this.logsHome,`${e.replace(/[\\/:\*\?"<>\|]/g,"")}.log`):e}setLogLevel(e,n){if(y.isUri(e)){let r=e,o=n,s=this._loggers.get(r);s&&o!==s.info.logLevel&&(s.info.logLevel=o===this.logLevel?void 0:o,s.logger?.setLevel(o),this._loggers.set(s.info.resource,s),this._onDidChangeLogLevel.fire([r,o]))}else{this.logLevel=e;for(let[r,o]of this._loggers.entries())this._loggers.get(r)?.info.logLevel===void 0&&o.logger?.setLevel(this.logLevel);this._onDidChangeLogLevel.fire(this.logLevel)}}setVisibility(e,n){let r=this.getLoggerEntry(e);r&&n!==!r.info.hidden&&(r.info.hidden=!n,this._loggers.set(r.info.resource,r),this._onDidChangeVisibility.fire([r.info.resource,n]))}getLogLevel(e){let n;return e&&(n=this._loggers.get(e)?.info.logLevel),n??this.logLevel}registerLogger(e){let n=this._loggers.get(e.resource);n?n.info.hidden!==e.hidden&&this.setVisibility(e.resource,!e.hidden):(this._loggers.set(e.resource,{info:e,logger:void 0}),this._onDidChangeLoggers.fire({added:[e],removed:[]}))}deregisterLogger(e){let n=this.toResource(e),r=this._loggers.get(n);r&&(r.logger&&r.logger.dispose(),this._loggers.delete(n),this._onDidChangeLoggers.fire({added:[],removed:[r.info]}))}*getRegisteredLoggers(){for(let e of this._loggers.values())yield e.info}getRegisteredLogger(e){return this._loggers.get(e)?.info}dispose(){this._loggers.forEach(e=>e.logger?.dispose()),this._loggers.clear(),super.dispose()}},gm=class{constructor(){this.onDidChangeLogLevel=new w().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(){}},hc=class extends gm{};function Xb(i){if(i.verbose)return 1;if(typeof i.logLevel=="string"){let t=SE(i.logLevel.toLowerCase());if(t!==void 0)return t}return Jb}function vE(i){switch(i){case 1:return"trace";case 2:return"debug";case 3:return"info";case 4:return"warn";case 5:return"error";case 0:return"off"}}function SE(i){switch(i){case"trace":return 1;case"debug":return 2;case"info":return 3;case"warn":return 4;case"error":return 5;case"critical":return 5;case"off":return 0}}var mW=new pc("logLevel",vE(3));var ft=$("sessionDataService"),dl="session.db",yc="attachments";var Zb="branch",eI="uncommitted",tI="session",vc="turn/",nI="{turnId}",Sc="compare/",rI="{originalTurnId}",iI="{modifiedTurnId}",bE=()=>g(1887,null),IE=()=>g(1891,null),_E=()=>g(1890,null),CE=()=>g(1895,null),TE=()=>g(1894,null),xE=()=>g(1893,null),wE=()=>g(1892,null),RE=()=>g(1889,null),EE=()=>g(1888,null);function oI(i){let{baseBranchName:t,branchName:e,upstreamBranchName:n}=i;return t&&e?`${e} \u2192 ${t}`:n&&e?`${e} \u2192 ${n}`:e}var Tr="/changeset/";function oi(i){return`${i}${Tr}${Zb}`}function Bt(i){return`${i}${Tr}${tI}`}function xn(i){return`${i}${Tr}${eI}`}function PE(i){return`${i}${Tr}${vc}${nI}`}function sI(i,t){if(!t||t.includes("/"))throw new Error(`buildTurnChangesetUri: turnId must be non-empty and not contain '/' (got ${JSON.stringify(t)})`);return`${i}${Tr}${vc}${t}`}function AE(i){return`${i}${Tr}${Sc}${rI}/${iI}`}function aI(i,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`${i}${Tr}${Sc}${t}/${e}`}function Vt(i){let t=i.lastIndexOf(Tr);if(t<0)return;let e=i.slice(t+Tr.length);if(!e)return;let n=i.slice(0,t);if(e===Zb)return{sessionUri:n,changesetId:e,kind:"branch"};if(e===eI)return{sessionUri:n,changesetId:e,kind:"uncommitted"};if(e===tI)return{sessionUri:n,changesetId:e,kind:"session"};if(e.startsWith(vc)){let r=e.slice(vc.length);return!r||r.includes("/")||r===nI?void 0:{sessionUri:n,changesetId:e,kind:"turn",turnId:r}}if(e.startsWith(Sc)){let o=e.slice(Sc.length).split("/");if(o.length!==2)return;let[s,a]=o;return!s||!a||s===rI||a===iI?void 0:{sessionUri:n,changesetId:e,kind:"compare-turns",originalTurnId:s,modifiedTurnId:a}}if(!e.includes("/"))return{sessionUri:n,changesetId:e,kind:"unknown"}}function bc(i){return[{label:bE(),uriTemplate:oi(i),changeKind:"branch"},{label:CE(),description:TE(),uriTemplate:xn(i),changeKind:"uncommitted"},{label:IE(),description:_E(),uriTemplate:Bt(i),changeKind:"session"},{label:xE(),description:wE(),uriTemplate:PE(i),changeKind:"turn"},{label:RE(),description:EE(),uriTemplate:AE(i),changeKind:"compare-turns"}]}function lI(i){return i.type.startsWith("root/")}function Ic(i){return i.type.startsWith("session/")}function _c(i){return i.type.startsWith("terminal/")}function dI(i){return i.type.startsWith("changeset/")}function cI(i){return i.type.startsWith("annotations/")}var fe={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603},ue={SessionNotFound:-32001,ProviderNotFound:-32002,SessionAlreadyExists:-32003,TurnInProgress:-32004,UnsupportedProtocolVersion:-32005,ContentNotFound:-32006,AuthRequired:-32007,NotFound:-32008,PermissionDenied:-32009,AlreadyExists:-32010,Conflict:-32011};var uI=-32700,Jo=-32603,At=-32001,pI=-32002;var fI=-32005;var on=-32007;function gI(i){return"method"in i&&"id"in i}function mI(i){return"method"in i&&!("id"in i)}var D=class extends Error{constructor(e,n,r){super(n);this.code=e;this.data=r}};var Be="ahp-root://",LE="ahp-root",Cm="ahp-resource-watch";function _I(i){let t={root:i.root};i.recursive&&(t.recursive=!0),i.excludes&&i.excludes.items.length>0&&(t.excludes=[...i.excludes.items]),i.includes&&i.includes.items.length>0&&(t.includes=[...i.includes.items]);let e=Fi(A.fromString(JSON.stringify(t)),!1,!0);return`${Cm}://r/${e}`}function CI(i){let t;try{t=y.parse(i)}catch{return}if(t.scheme!==Cm)return;let e=t.path.replace(/^\//,"");if(e)try{let n=JSON.parse(Ln(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(r=>typeof r=="string")}}:{},...Array.isArray(n.includes)?{includes:{items:n.includes.filter(r=>typeof r=="string")}}:{}}}catch{return}}function TI(i){try{return y.parse(i).scheme===Cm}catch{return!1}}function ul(i){if(i===Be)return!0;try{return y.parse(i).scheme===LE}catch{return!1}}function Rn(i,t){return t?`${i.replace(/#/g,"%23")}#range=${t.start.line}:${t.start.character}-${t.end.line}:${t.end.character}`:i}function xI(i){if(!i.content||i.content.length===0)return[];let t=[];for(let e of i.content)ye(e,{type:!0})&&e.type==="fileEdit"&&t.push(e);return t}var NE="subagent",UE=`/${NE}/`,FE=/^(?<parentPath>.+)\/subagent\/(?<toolCallId>.+)$/;function wI(i){return typeof i=="string"?y.parse(i):i}function RI(i){let t=wI(i),e=t.path.endsWith("/")?t.path.slice(0,-1):t.path;return{parent:t,path:`${e}${UE}`}}function Qo(i,t){let{parent:e,path:n}=RI(i);return e.with({path:`${n}${t}`}).toString()}function Xe(i){let t=wI(i),e=FE.exec(t.path);if(e?.groups)return{parentSession:t.with({path:e.groups.parentPath}),toolCallId:e.groups.toolCallId}}function Xo(i){return Xe(i)!==void 0}function EI(i){let{parent:t,path:e}=RI(i);return t.with({path:e}).toString()}function PI(){return{agents:[],activeSessions:0}}function Tm(i){return{summary:i,lifecycle:"creating",turns:[],activeTurn:void 0}}var ym="git";function hn(i){let t=i?.[ym];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 AI(i,t){let e={...i};return t!==void 0?e[ym]=t:delete e[ym],Object.keys(e).length>0?e:void 0}var hI="hostBuild";function kI(i){return{version:i.version,commit:i.commit,date:i.date,quality:i.quality}}function DI(i,t){let e={...i};return t!==void 0?e[hI]=t:delete e[hI],Object.keys(e).length>0?e:void 0}var gt=$("productService");import*as ml from"fs";var ai=$("telemetryService");var A$=$("customEndpointTelemetryService");var OI="telemetry",Zo="telemetry.telemetryLevel",wc="telemetry.enableCrashReporter",pl="telemetry.enableTelemetry";function Ve(i){let t=xm(i);return{protocol:i,validate:r=>{try{return t(r,""),!0}catch{return!1}},assertValid:(r,o="")=>t(r,o)}}function zt(i){return{definition:i,toProtocol(){let t={};for(let e of Object.keys(i))t[e]=i[e].protocol;return{type:"object",properties:t}},values(t){let e=t;for(let n of Object.keys(i)){let r=e[n];if(r===void 0)continue;i[n].assertValid(r,n)}return{...e}},validate(t,e){let n=i[t];return n?n.validate(e):!1},assertValid(t,e){let n=i[t];if(!n)throw new D(fe.InvalidParams,`Unknown schema key '${t}'`);n.assertValid(e,t)},validateOrDefault(t,e){let n={},r=t??{};for(let o of Object.keys(i)){let s=i[o],a=r[o];a!==void 0&&s.validate(a)?n[o]=a:Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o])}return n}}}function xm(i){if(i.type==="object"&&i.properties){let t={};for(let n of Object.keys(i.properties))t[n]=xm(i.properties[n]);let e=new Set(i.required??[]);return(n,r)=>{if(typeof n!="object"||n===null||Array.isArray(n))throw Ji(r,"object",n);let o=n;for(let s of Object.keys(t)){let a=$E(r,s);if(o[s]===void 0){if(e.has(s))throw new D(fe.InvalidParams,`Missing required property at '${a}'`);continue}t[s](o[s],a)}}}if(i.type==="array"&&i.items){let t=xm(i.items);return(e,n)=>{if(!Array.isArray(e))throw Ji(n,"array",e);for(let r=0;r<e.length;r++)t(e[r],`${n}[${r}]`)}}return WE(i)}function WE(i){let t=i.enumDynamic===!0;return(e,n)=>{switch(i.type){case"string":if(typeof e!="string")throw Ji(n,"string",e);break;case"number":if(typeof e!="number")throw Ji(n,"number",e);break;case"boolean":if(typeof e!="boolean")throw Ji(n,"boolean",e);break;case"array":if(!Array.isArray(e))throw Ji(n,"array",e);break;case"object":if(typeof e!="object"||e===null||Array.isArray(e))throw Ji(n,"object",e);break}if(i.enum&&!t&&!i.enum.includes(e))throw new D(fe.InvalidParams,`Invalid value at '${n||"<root>"}': ${LI(e)} is not one of [${i.enum.map(r=>JSON.stringify(r)).join(", ")}]`)}}function Ji(i,t,e){return new D(fe.InvalidParams,`Invalid value at '${i||"<root>"}': expected ${t}, got ${LI(e)}`)}function $E(i,t){return i?`${i}.${t}`:t}function LI(i){try{return JSON.stringify(i)}catch{return String(i)}}var NI=Ve({type:"object",title:g(1870,null),description:g(1874,null),properties:{allow:{type:"array",title:g(1871,null),items:{type:"string",title:g(1873,null)}},deny:{type:"array",title:g(1872,null),items:{type:"string",title:g(1873,null)}}},default:{allow:[],deny:[]},sessionMutable:!0}),It=zt({autoApprove:Ve({type:"string",title:g(1856,null),description:g(1863,null),enum:["default","autoApprove","autopilot"],enumLabels:[g(1861,null),g(1859,null),g(1857,null)],enumDescriptions:[g(1862,null),g(1860,null),g(1858,null)],default:"default",sessionMutable:!0}),permissions:NI,mode:Ve({type:"string",title:g(1864,null),description:g(1869,null),enum:["interactive","plan"],enumLabels:[g(1865,null),g(1867,null)],enumDescriptions:[g(1866,null),g(1868,null)],default:"interactive",sessionMutable:!0})}),fl="telemetryLevel",gl="sessionSyncEnabled";function UI(i){switch(i){case 0:return"off";case 1:return"crash";case 2:return"error";case 3:return"all"}}function FI(i){switch(i){case"off":return 0;case"crash":return 1;case"error":return 2;case"all":return 3;default:return}}var Qi=zt({permissions:NI,[fl]:Ve({type:"string",title:g(1855,null),description:g(1854,null),enum:["all","error","crash","off"],default:"all"}),[gl]:Ve({type:"boolean",title:g(1853,null),description:g(1852,null),default:!1})});var jt=zt({customizations:Ve({type:"array",title:g(1844,null),description:g(1840,null),default:[],items:{type:"object",title:g(1843,null),properties:{uri:{type:"string",title:g(1845,null)},displayName:{type:"string",title:g(1842,null)},description:{type:"string",title:g(1841,null)}},required:["uri","displayName"]}}),defaultShell:Ve({type:"string",title:g(1847,null),description:g(1846,null)}),enableCustomTerminalTool:Ve({type:"boolean",title:g(1849,null),description:g(1848,null),default:!1}),rubberDuck:Ve({type:"boolean",title:g(1851,null),description:g(1850,null),default:!1})}),WI={customizations:[]};function $I(i){return{type:"plugin",id:Rn(i.uri),uri:i.uri,name:i.displayName,enabled:!0}}var Rr=zt({sandbox:Ve({type:"object",title:g(1913,null),properties:{enabled:{type:"string",title:g(1910,null),enum:["off","on","allowNetwork"]},"enabled.windows":{type:"string",title:g(1914,null),enum:["off","on","allowNetwork"]},allowUnsandboxedCommands:{type:"boolean",title:g(1906,null)},autoApproveUnsandboxedCommands:{type:"boolean",title:g(1907,null)},"fileSystem.linux":{type:"object",title:g(1911,null)},"fileSystem.mac":{type:"object",title:g(1912,null)},"fileSystem.windows":{type:"object",title:g(1915,null)},"advanced.runtime":{type:"object",title:g(1903,null)},allowedNetworkDomains:{type:"array",title:g(1905,null),items:{type:"string",title:g(1904,null)}},deniedNetworkDomains:{type:"array",title:g(1909,null),items:{type:"string",title:g(1908,null)}}}})}),qI={"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 $e=$("agentConfigurationService"),es=class extends T{constructor(e,n,r){super();this._stateManager=e;this._logService=n;this._rootConfigResource=r;this._rootConfigWrite=Promise.resolve();this._onDidRootConfigChange=this._register(new w);this.onDidRootConfigChange=this._onDidRootConfigChange.event;let o=this._stateManager.rootState.config,s=jt.toProtocol(),a=Rr.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,r){for(let o of this._effectiveChain(e)){let s=o[r];if(s!==void 0)try{return n.assertValid(r,s),s}catch(a){let l=a instanceof D?a.message:String(a);this._logService.warn(`[AgentConfigurationService] Value for '${r}' 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 r=Xe(e);if(r)return this._stateManager.getSessionState(r.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 D?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(Be,{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,"	"),r=this._rootConfigResource;this._rootConfigWrite=this._rootConfigWrite.catch(o=>{this._logService.warn("[AgentConfigurationService] Previous host config write failed",o)}).then(async()=>{await ml.promises.mkdir(se(r.fsPath),{recursive:!0}),await ml.promises.writeFile(r.fsPath,`${n}
`,"utf8")}).catch(o=>{this._logService.error(`[AgentConfigurationService] Failed to persist host config to ${r.fsPath}`,o)})}async whenIdle(){await this._rootConfigWrite}*_effectiveChain(e){let n=this._stateManager.getSessionState(e)?.config?.values;n&&(yield n);let r=Xe(e);if(r){let s=this._stateManager.getSessionState(r.parentSession.toString())?.config?.values;s&&(yield s)}let o=this._stateManager.rootState.config?.values;o&&(yield o)}_loadPersistedRootConfig(){let e=WI;if(!this._rootConfigResource)return{...e};try{let n=ml.readFileSync(this._rootConfigResource.fsPath,"utf8"),r=JSON.parse(n);return{...jt.validateOrDefault(r,e),...Rr.validateOrDefault(r,{})}}catch(n){return(n&&typeof n=="object"&&ye(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}}}};es=x([C(1,O)],es);import*as eo from"fs";import{userInfo as QE}from"os";import*as wm from"os";var BI=/^\d+$/,BE=/^Microsoft.PowerShell_.*/,VE=/^Microsoft.PowerShellPreview_.*/;var hl;switch(process.arch){case"ia32":hl=1;break;case"arm":case"arm64":hl=2;break;default:hl=0;break}var ts;process.env.PROCESSOR_ARCHITEW6432?ts=process.env.PROCESSOR_ARCHITEW6432==="ARM64"?2:0:process.env.PROCESSOR_ARCHITECTURE==="ARM64"?ts=2:process.env.PROCESSOR_ARCHITECTURE==="X86"?ts=1:ts=0;var Xi=class{constructor(t,e,n){this.exePath=t;this.displayName=e;this.knownToExist=n}async exists(){return this.knownToExist===void 0&&(this.knownToExist=await Pt.existsFile(this.exePath)),this.knownToExist}};function zE({useAlternateBitness:i=!1}={}){return i?hl===0?process.env["ProgramFiles(x86)"]||null:ts===0&&process.env.ProgramW6432||null:process.env.ProgramFiles||null}async function Pc({useAlternateBitness:i=!1,findPreview:t=!1}={}){let e=zE({useAlternateBitness:i});if(!e)return null;let n=W(e,"PowerShell");if(!await Pt.existsDirectory(n))return null;let r=-1,o=null;for(let l of await Ae.readdir(n)){let d=-1;if(t){let u=l.indexOf("-");if(u<0)continue;let p=l.substring(0,u);if(!BI.test(p)||l.substring(u+1)!=="preview")continue;d=parseInt(p,10)}else{if(!BI.test(l))continue;d=parseInt(l,10)}if(d<=r)continue;let c=W(n,l,"pwsh.exe");await Pt.existsFile(c)&&(o=c,r=d)}if(!o)return null;let s=e.includes("x86")?" (x86)":"",a=t?" Preview":"";return new Xi(o,`PowerShell${a}${s}`,!0)}async function VI({findPreview:i}={}){if(!process.env.LOCALAPPDATA)return null;let t=W(process.env.LOCALAPPDATA,"Microsoft","WindowsApps");if(!await Pt.existsDirectory(t))return null;let{pwshMsixDirRegex:e,pwshMsixName:n}=i?{pwshMsixDirRegex:VE,pwshMsixName:"PowerShell Preview (Store)"}:{pwshMsixDirRegex:BE,pwshMsixName:"PowerShell (Store)"};for(let r of await Ae.readdir(t))if(e.test(r)){let o=W(t,r,"pwsh.exe");return new Xi(o,n)}return null}function jE(){let i=W(wm.homedir(),".dotnet","tools","pwsh.exe");return new Xi(i,".NET Core PowerShell Global Tool")}function KE(){let i=W(wm.homedir(),"scoop","apps"),t=W(i,"pwsh","current","pwsh.exe");return new Xi(t,"PowerShell (Scoop)")}function GE(){let i=W(process.env.windir,hl===1&&ts!==1?"SysNative":"System32","WindowsPowerShell","v1.0","powershell.exe");return new Xi(i,"Windows PowerShell",!0)}async function*JE(){let i=await Pc();i&&(yield i),i=await Pc({useAlternateBitness:!0}),i&&(yield i),i=await VI(),i&&(yield i),i=jE(),i&&(yield i),i=await Pc({findPreview:!0}),i&&(yield i),i=await VI({findPreview:!0}),i&&(yield i),i=await Pc({useAlternateBitness:!0,findPreview:!0}),i&&(yield i),i=await KE(),i&&(yield i),i=GE(),i&&(yield i)}async function*YE(){for await(let i of JE())await i.exists()&&(yield i)}async function zI(){for await(let i of YE())return i;return null}async function Ac(i,t){return i===1?G?ZE():ob(t):XE(i,t)}var Rm=null;function XE(i,t){if(Se&&i===2||et&&i===3)return"/bin/bash";if(!Rm){let e;if(G)e="/bin/bash";else{if(e=t.SHELL,!e)try{e=QE().shell}catch{}e||(e="sh"),e==="/bin/false"&&(e="/bin/bash")}Rm=e}return Rm}var Em=null;async function ZE(){return Em||(Em=(await zI()).exePath),Em}import*as ns from"os";var Pm=class{constructor(){this.data=new Map}add(t,e){fd(Ne(t)),fd(Ue(e)),fd(!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=>{xa(t.dispose)&&t.dispose()}),this.data.clear()}},mt=new Pm;var hH=$("ptyService");var tP={Backend:"workbench.contributions.terminal.processBackend"},Am=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()??""}};mt.add(tP.Backend,new Am);var yH=$("localPtyService"),vH=$("terminalLogService");function nP(i){return new Map(i)}function rP(i){return new Map(i??[])}function jI(i){return new Map(i.map(t=>[t[0],{map:nP(t[1]),descriptionMap:rP(t[2])}]))}var oP=new Map([[2,"APPEND"],[3,"PREPEND"],[1,"REPLACE"]]),sP=/^VSCODE_PYTHON_(PWSH|ZSH|BASH|FISH)_ACTIVATE/,aP="ms-python.vscode-python-envs",kc=class{constructor(t){this.collections=t;this.map=new Map;this.descriptionMap=new Map;t.forEach((e,n)=>{this.populateDescriptionMap(e,n);let r=e.map.entries(),o=r.next();for(;!o.done;){let s=o.value[1],a=o.value[0];if(this.blockPythonActivationVar(a,n)){o=r.next();continue}let l=this.map.get(a);if(l||(l=[],this.map.set(a,l)),l.length>0&&l[0].type===1){o=r.next();continue}let d={extensionIdentifier:n,value:s.value,type:s.type,scope:s.scope,variable:s.variable,options:s.options};d.scope||delete d.scope,l.unshift(d),o=r.next()}})}async applyToProcessEnvironment(t,e,n){let r;G&&(r={},Object.keys(t).forEach(o=>r[o.toLowerCase()]=o));for(let[o,s]of this.getVariableMap(e)){let a=G&&r[o.toLowerCase()]||o;for(let l of s){let d=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]||"")+d;break;case 3:t[a]=d+(t[a]||"");break;case 1:t[a]=d;break}if(l.options?.applyAtShellIntegration??!1){let c=`VSCODE_ENV_${oP.get(l.type)}`;t[c]=(t[c]?t[c]+":":"")+o+"="+this._encodeColons(d)}}}}}_encodeColons(t){return t.replaceAll(":","\\x3a")}blockPythonActivationVar(t,e){return!!(sP.test(t)&&aP!==e)}diff(t,e){let n=new Map,r=new Map,o=new Map;if(t.getVariableMap(e).forEach((s,a)=>{let l=this.getVariableMap(e).get(a),d=GI(s,l);d&&n.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=t.getVariableMap(e).get(a),d=GI(s,l);d&&o.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=t.getVariableMap(e).get(a),d=lP(s,l);d&&r.set(a,d)}),!(n.size===0&&r.size===0&&o.size===0))return{added:n,changed:r,removed:o}}getVariableMap(t){let e=new Map;for(let n of this.map.values()){let r=n.filter(o=>KI(o,t));r.length>0&&e.set(r[0].variable,r)}return e}getDescriptionMap(t){let e=new Map;for(let n of this.descriptionMap.values()){let r=n.filter(o=>KI(o,t,!0));for(let o of r)e.set(o.extensionIdentifier,o.description)}return e}populateDescriptionMap(t,e){if(!t.descriptionMap)return;let n=t.descriptionMap.entries(),r=n.next();for(;!r.done;){let o=r.value[1],s=r.value[0],a=this.descriptionMap.get(s);a||(a=[],this.descriptionMap.set(s,a));let l={extensionIdentifier:e,scope:o.scope,description:o.description};l.scope||delete l.scope,a.push(l),r=n.next()}}};function KI(i,t,e=!1){return i.scope?!!(i.scope.workspaceFolder&&t?.workspaceFolder&&i.scope.workspaceFolder.index===t.workspaceFolder.index):e?t===i.scope:!0}function GI(i,t){if(!t)return i;let e=new Set;t.forEach(r=>e.add(r.extensionIdentifier));let n=[];return i.forEach(r=>{e.has(r.extensionIdentifier)||n.push(r)}),n.length===0?void 0:n}function lP(i,t){if(!t)return;let e=new Map;t.forEach(r=>e.set(r.extensionIdentifier,r));let n=[];return i.forEach(r=>{let o=e.get(r.extensionIdentifier);o&&(r.type!==o.type||r.value!==o.value||r.scope?.workspaceFolder?.index!==o.scope?.workspaceFolder?.index)&&n.push(o)}),n.length===0?void 0:n}import{chmod as YI,realpathSync as uP,mkdirSync as pP}from"fs";import{promisify as QI}from"util";import*as Dc from"os";var yl;async function dP(){if(yl)return;if(!G){yl={release:Dc.release(),buildNumber:0};return}let i,t;try{let e=await import("@vscode/windows-registry"),n="SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",r=e.GetStringRegKey("HKEY_LOCAL_MACHINE",n,"CurrentBuild");r!==void 0&&(i=parseInt(r,10),isNaN(i)&&(i=void 0));let o=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",n,"CurrentMajorVersionNumber"),s=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",n,"CurrentMinorVersionNumber");o!==void 0&&s!==void 0&&r!==void 0&&(t=`${o}.${s}.${r}`)}catch{}finally{yl={release:t||Dc.release(),buildNumber:i||cP()}}}async function JI(){return yl||await dP(),yl.buildNumber}function cP(){let i=/(\d+)\.(\d+)\.(\d+)/g.exec(Dc.release());return i&&i.length===4?parseInt(i[3],10):0}async function t_(i,t,e,n,r,o=!1){if(!t.shellIntegration.enabled)return{type:"failure",reason:"injectionSettingDisabled"};if(!i.executable)return{type:"failure",reason:"noExecutable"};if(i.isFeatureTerminal&&!i.forceShellIntegration)return{type:"failure",reason:"featureTerminal"};if(i.ignoreShellIntegration)return{type:"failure",reason:"ignoreShellIntegrationFlag"};let s=G?await JI():0;if(G&&s<18309)return{type:"failure",reason:"unsupportedWindowsBuild"};let a=i.args,l=bo==="win32"?Ce(i.executable).toLowerCase():Ce(i.executable),d=se(dt.asFileUri("").fsPath),c="injection",u,p={VSCODE_INJECTION:"1"};t.shellIntegration.nonce&&(p.VSCODE_NONCE=t.shellIntegration.nonce);let m=["PATH","VIRTUAL_ENV","HOME","SHELL","PWD"];if(i.shellIntegrationEnvironmentReporting&&(G?(t.windowsUseConptyDll||s>=22631&&l!=="bash.exe")&&(p.VSCODE_SHELL_ENV_REPORTING=m.join(",")):p.VSCODE_SHELL_ENV_REPORTING=m.join(",")),G)return l==="pwsh.exe"||l==="powershell.exe"?(p.VSCODE_A11Y_MODE=t.isScreenReaderOptimized?"1":"0",!a||e_(a)?u=He.get("windows-pwsh"):ZI(a)&&(u=He.get("windows-pwsh-login")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d,""),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"}):l==="bash.exe"?(!a||a.length===0?u=He.get("bash"):Lc(a)&&(p.VSCODE_SHELL_LOGIN="1",Oc(t,p,l),u=He.get("bash")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"}):(n.warn(`Shell integration cannot be enabled for executable "${i.executable}" and args`,i.args),{type:"failure",reason:"unsupportedShell"});switch(l){case"bash":return!a||a.length===0?u=He.get("bash"):Lc(a)&&(p.VSCODE_SHELL_LOGIN="1",Oc(t,p,l),u=He.get("bash")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"fish":return!a||a.length===0?u=He.get("fish"):Lc(a)?u=He.get("fish-login"):(a===He.get("fish")||a===He.get("fish-login"))&&(u=a),u?(Oc(t,p,l),u=[...u],u[u.length-1]=Mi(u[u.length-1],d),{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"pwsh":return!a||e_(a)?u=He.get("pwsh"):ZI(a)&&(u=He.get("pwsh-login")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d,""),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"zsh":{if(!a||a.length===0?u=He.get("zsh"):Lc(a)?(u=He.get("zsh-login"),Oc(t,p,l)):(a===He.get("zsh")||a===He.get("zsh-login"))&&(u=a),!u)return{type:"failure",reason:"unsupportedArgs"};u=[...u],u[u.length-1]=Mi(u[u.length-1],d);let h;try{h=ns.userInfo().username}catch{h="unknown"}let v=uP(ns.tmpdir()),I=W(v,`${h}-${r.applicationName}-zsh`);if(!o)try{await QI(YI)(I,960)}catch(_){if(_.message.includes("ENOENT")){try{pP(I)}catch(R){return n.error(`Failed to create zdotdir at ${I}: ${R}`),{type:"failure",reason:"failedToCreateTmpDir"}}try{await QI(YI)(I,960)}catch{return n.error(`Failed to set sticky bit on ${I}: ${_}`),{type:"failure",reason:"failedToSetStickyBit"}}}return n.error(`Failed to set sticky bit on ${I}: ${_}`),{type:"failure",reason:"failedToSetStickyBit"}}p.ZDOTDIR=I;let b=e?.ZDOTDIR??ns.homedir()??"~";p.USER_ZDOTDIR=b;let S=[];return S.push({source:W(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-rc.zsh"),dest:W(I,".zshrc")}),S.push({source:W(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-profile.zsh"),dest:W(I,".zprofile")}),S.push({source:W(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-env.zsh"),dest:W(I,".zshenv")}),S.push({source:W(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-login.zsh"),dest:W(I,".zlogin")}),{type:c,newArgs:u,envMixin:p,filesToCopy:S}}}return n.warn(`Shell integration cannot be enabled for executable "${i.executable}" and args`,i.args),{type:"failure",reason:"unsupportedShell"}}function Oc(i,t,e){if((et||e==="fish")&&i.environmentVariableCollections){let n=jI(i.environmentVariableCollections),o=new kc(n).getVariableMap({workspaceFolder:i.workspaceFolder}).get("PATH"),s=[];if(o)for(let a of o)a.type===3&&s.push(a.value);s.length>0&&(t.VSCODE_PATH_PREFIX=s.join(""))}}var He=new Map;He.set("windows-pwsh",["-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);He.set("windows-pwsh-login",["-l","-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);He.set("pwsh",["-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"{1}']);He.set("pwsh-login",["-l","-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"']);He.set("zsh",["-i"]);He.set("zsh-login",["-il"]);He.set("bash",["--init-file","{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh"]);He.set("fish",["--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);He.set("fish-login",["-l","--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);var Mc=["-login","-l"],XI=["--login","-l"],fP=["-i","--interactive"],Nc=["-nol","-nologo"];function ZI(i){return Ne(i)?Mc.includes(i.toLowerCase()):i.length===1&&Mc.includes(i[0].toLowerCase())||i.length===2&&(Mc.includes(i[0].toLowerCase())||Mc.includes(i[1].toLowerCase()))&&(Nc.includes(i[0].toLowerCase())||Nc.includes(i[1].toLowerCase()))}function e_(i){return Ne(i)?Nc.includes(i.toLowerCase()):i.length===0||i?.length===1&&Nc.includes(i[0].toLowerCase())}function Lc(i){return Ne(i)||(i=i.filter(t=>!fP.includes(t.toLowerCase()))),Ne(i)&&XI.includes(i.toLowerCase())||!Ne(i)&&i.length===1&&XI.includes(i[0].toLowerCase())}import gP from"@xterm/headless";var{Terminal:mP}=gP,Uc=class extends T{constructor(e){super();this._onResponseData=this._register(new w);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 mP(n),this._register(this._terminal.onData(r=>{this._isCursorPositionReportResponse(r)?(this._logService.debug(`[AgentHostHeadlessTerminal] Forwarding terminal response ${JSON.stringify(r)}`),this._onResponseData.fire(r)):this._logService.debug(`[AgentHostHeadlessTerminal] Dropping terminal response ${JSON.stringify(r)}`)})),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 Ie,r=()=>{n.isSettled||(this._logService.debug("[AgentHostHeadlessTerminal] Detected alternate buffer entry"),n.complete())};return this.isInAltBuffer()?r():e.add(this._terminal.buffer.onBufferChange(()=>{this.isInAltBuffer()&&r()})),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 Fc(i){return at===1?/^zsh(?:\.exe)?$/i.test(le.basename(i)):/^zsh$/.test(Z.basename(i))}function n_(i){return i.indexOf("\\")===-1?i:i.replaceAll(/\\(\\|x([0-9a-f]{2}))/gi,(t,e,n)=>n?String.fromCharCode(parseInt(n,16)):e)}function hP(i){let t=i.indexOf(";");if((t===-1?i.length:t)!==1)return;let e=i[0],n=t===-1?"":i.substring(t+1);switch(e){case"A":return{type:0};case"B":return{type:1};case"C":return{type:2};case"D":{let r=n.length>0?parseInt(n,10):void 0;return{type:3,exitCode:r!==void 0&&!isNaN(r)?r:void 0}}case"E":{let r=n.indexOf(";"),o=n_(r===-1?n:n.substring(0,r)),s=r===-1?void 0:n.substring(r+1);return{type:4,commandLine:o,nonce:s}}case"P":{let r=n_(n),o=r.indexOf("=");return o===-1?void 0:{type:5,key:r.substring(0,o),value:r.substring(o+1)}}default:return}}var Om="\x1B",km=Om+"]",Dm="\x07",r_=Om+"\\",Wc=class{constructor(){this._pendingOsc="";this._inOsc=!1;this._pendingEscInOsc=!1}parse(t){let e=[];if(!this._inOsc&&t.indexOf(km)===-1)return{cleanedData:t,events:e};let n="",r=0;for(;r<t.length;){if(this._inOsc){if(this._pendingEscInOsc){if(this._pendingEscInOsc=!1,t[r]==="\\"){r++,this._inOsc=!1;let d=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(d,e,{value:n,append(c){n=c}},r_);continue}this._inOsc=!1;let l=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(l,e,{value:n,append(d){n=d}});continue}let a=this._consumeOscBody(t,r);if(r=a.nextIndex,a.complete){this._inOsc=!1;let l=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(l,e,{value:n,append(d){n=d}},a.terminator)}else a.pendingEsc&&(this._pendingEscInOsc=!0);continue}let o=t.indexOf(km,r);if(o===-1){n+=t.substring(r),r=t.length;continue}n+=t.substring(r,o),r=o+2,this._pendingOsc="",this._inOsc=!0;let s=this._consumeOscBody(t,r);if(r=s.nextIndex,s.complete){this._inOsc=!1;let a=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(a,e,{value:n,append(l){n=l}},s.terminator)}else s.pendingEsc&&(this._pendingEscInOsc=!0)}return{cleanedData:n,events:e}}_consumeOscBody(t,e){let n=t.indexOf(Dm,e),r=t.indexOf(Om,e);return n!==-1&&(r===-1||n<r)?(this._pendingOsc+=t.substring(e,n),{nextIndex:n+1,complete:!0,terminator:Dm}):r!==-1?r+1>=t.length?(this._pendingOsc+=t.substring(e,r),{nextIndex:t.length,complete:!1,pendingEsc:!0}):(this._pendingOsc+=t.substring(e,r),t[r+1]==="\\"?{nextIndex:r+2,complete:!0,terminator:r_}:{nextIndex:r,complete:!0}):(this._pendingOsc+=t.substring(e),{nextIndex:t.length,complete:!1})}_handleOscPayload(t,e,n,r=Dm){if(t.startsWith("633;")){let o=t.substring(4),s=hP(o);s&&e.push(s)}else n&&n.append(n.value+km+t+r)}};var vP=1e4,SP=0,Mm="\x1B[6n",Lm="\x1B[?6n",bP=["\x1B[?6","\x1B[?","\x1B[6","\x1B[","\x1B"],is=$("agentHostTerminalManager");function IP(i,t){if(!t.pendingData&&!i.includes(Mm)&&!i.includes(Lm)&&!i_(i))return i;let e=t.pendingData+i,n=i_(e),r=n?e.substring(0,e.length-n.length):e;return t.pendingData=n,!r.includes(Mm)&&!r.includes(Lm)?r:r.replaceAll(Lm,"").replaceAll(Mm,"")}function i_(i){for(let t of bP)if(i.endsWith(t))return t;return""}function _P(i,t){return t.forceBracketedPasteMode&&(i=`\x1B[200~${i}\x1B[201~`),i=i.replace(/\r?\n/g,"\r"),t.shouldExecute&&!i.endsWith("\r")&&(i+="\r"),i}var Nm;async function CP(){return Nm||(Nm=await import("node-pty")),Nm}var rs=class extends T{constructor(e,n,r,o){super();this._stateManager=e;this._logService=n;this._productService=r;this._configurationService=o;this._terminals=new Map;this._register(this._stateManager.onDidEmitEnvelope(s=>{let a=s.action;if(!_c(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 r=e.channel;if(this._terminals.has(r))throw new Error(`Terminal already exists: ${r}`);let o=await this._resolveCwd(e.cwd,r),s=e.cols??80,a=e.rows??24,l=n?.shell??await this.getDefaultShell(),d=G?"cmd":"xterm-256color";this._logService.info(`[TerminalManager] Creating terminal ${r}: shell=${l}, cwd=${o}, cols=${s}, rows=${a}`);let c=N(),u={...process.env};n?.preventShellHistory&&(u.VSCODE_PREVENT_SHELL_HISTORY="1"),e.claim?.kind==="session"&&Fc(l)&&(u.VSCODE_AGENT_ZSH_FIXUPS="1"),n?.nonInteractive&&(u.LC_ALL="C.UTF-8",u.PAGER="",u.GIT_PAGER="",u.GH_PAGER="",u.GIT_TERMINAL_PROMPT="0",u.DEBIAN_FRONTEND="noninteractive");let p=[];et&&Yv(l).name.match(/(zsh|bash)/)&&(p=["--login"]);let m=await t_({executable:l,args:p,forceShellIntegration:!0},{shellIntegration:{enabled:!0,suggestEnabled:!1,nonce:c},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 ${r}`),m.envMixin)for(let[ne,xe]of Object.entries(m.envMixin))xe!==void 0&&(u[ne]=xe);if(m.newArgs&&(p=m.newArgs),m.filesToCopy)for(let ne of m.filesToCopy)try{await eo.promises.mkdir(se(ne.dest),{recursive:!0}),await eo.promises.copyFile(ne.source,ne.dest)}catch{}h={parser:new Wc,nonce:c,commandCounter:0,detectionAvailableEmitted:!1}}else this._logService.info(`[TerminalManager] Shell integration not available for ${r}: ${m.reason}`);let v=await this._spawnPty(l,p,{name:d,cwd:o,env:u,cols:s,rows:a}),I=new z,b=e.claim??{kind:"client",clientId:""},S=I.add(new w),_=I.add(new w),R=I.add(new w),P=I.add(new w),q=I.add(new Uc({cols:s,rows:a,scrollback:SP,logService:this._logService})),E={uri:r,store:I,pty:v,onDataEmitter:S,onExitEmitter:_,onClaimChangedEmitter:R,onCommandFinishedEmitter:P,title:e.name??l,cwd:o,cols:s,rows:a,content:[],contentSize:0,claim:b,commandTracker:h,headlessTerminal:q,terminalQueryFilterState:{pendingData:""}};this._terminals.set(r,E),I.add(q.onResponseData(ne=>{this._logService.debug(`[TerminalManager] Writing headless terminal response for ${r}: ${JSON.stringify(ne)}`);try{v.write(ne)}catch(xe){this._logService.debug(`[TerminalManager] Failed to write headless terminal response for ${r}: ${xe instanceof Error?xe.message:String(xe)}`)}})),I.add(k(()=>{try{v.kill()}catch{}}));let L=new Ie,U=v.onData(ne=>{E.headlessTerminal?.writePtyData(ne),this._handlePtyData(E,ne),L.complete()});I.add(k(()=>U.dispose()));let J=v.onExit(ne=>{E.exitCode=ne.exitCode,E.onExitEmitter.fire(ne.exitCode),L.complete(),this._stateManager.dispatchServerAction(r,{type:"terminal/exited",exitCode:ne.exitCode}),this._broadcastTerminalList()});if(I.add(k(()=>J.dispose())),!G){let ne=setInterval(()=>{let xe=v.process;xe&&xe!==E.title&&(E.title=xe,this._stateManager.dispatchServerAction(r,{type:"terminal/titleChanged",title:xe}),this._broadcastTerminalList())},200);I.add(k(()=>clearInterval(ne)))}await PS([L.p,_n(vP)]),this._broadcastTerminalList()}async _spawnPty(e,n,r){return(await CP()).spawn(e,n,r)}_writeInput(e,n){this.writeInput(e,n)}writeInput(e,n){let r=this._terminals.get(e);r&&r.exitCode===void 0&&r.pty.write(n)}async sendText(e,n,r){let o=this._terminals.get(e),s=!1;r.bracketedPasteMode&&(await o?.headlessTerminal?.whenPtyDataFlushed(),s=!!o?.headlessTerminal?.isBracketedPasteMode()),this.writeInput(e,_P(n,{shouldExecute:r.shouldExecute,forceBracketedPasteMode:s}))}onData(e,n){let r=this._terminals.get(e);return r?r.onDataEmitter.event(n):k(()=>{})}onExit(e,n){let r=this._terminals.get(e);return r?r.onExitEmitter.event(n):k(()=>{})}onClaimChanged(e,n){let r=this._terminals.get(e);return r?r.onClaimChangedEmitter.event(n):k(()=>{})}onCommandFinished(e,n){let r=this._terminals.get(e);return r?r.onCommandFinishedEmitter.event(n):k(()=>{})}createAltBufferPromise(e,n){let r=this._terminals.get(e);return r?.headlessTerminal?r.headlessTerminal.createAltBufferPromise(n):new Promise(()=>{})}getContent(e){let n=this._terminals.get(e);if(n)return n.content.map(r=>r.type==="command"?r.output:r.value).join("")}getClaim(e){return this._terminals.get(e)?.claim}hasTerminal(e){return this._terminals.has(e)}supportsCommandDetection(e){return this._terminals.get(e)?.commandTracker?.detectionAvailableEmitted??!1}getExitCode(e){return this._terminals.get(e)?.exitCode}_resize(e,n,r){let o=this._terminals.get(e);o&&o.exitCode===void 0&&(o.cols=n,o.rows=r,o.pty.resize(n,r),o.headlessTerminal?.resize(n,r))}_setClaim(e,n){let r=this._terminals.get(e);r&&(r.claim=n,r.onClaimChangedEmitter.fire(n),this._broadcastTerminalList())}_setTitle(e,n){let r=this._terminals.get(e);r&&(r.title=n,this._broadcastTerminalList())}_clearContent(e){let n=this._terminals.get(e);n&&(n.content=[],n.contentSize=0,n.headlessTerminal?.clear())}_handlePtyData(e,n){let r=e.commandTracker,o;if(r){let s=r.parser.parse(n);o=s.cleanedData;for(let a of s.events)this._handleOsc633Event(e,r,a)}else o=n;o=IP(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,r){switch(n.detectionAvailableEmitted||(n.detectionAvailableEmitted=!0,this._stateManager.dispatchServerAction(e.uri,{type:"terminal/commandDetectionAvailable"})),r.type){case 4:{r.nonce===n.nonce&&(n.pendingCommandLine=r.commandLine);break}case 2:{let o=`cmd-${++n.commandCounter}`,s=n.pendingCommandLine??"",a=Date.now();n.pendingCommandLine=void 0,n.activeCommandId=o,n.activeCommandTimestamp=a,e.content.push({type:"command",commandId:o,commandLine:s,output:"",timestamp:a,isComplete:!1}),this._stateManager.dispatchServerAction(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 d of e.content)if(d.type==="command"&&d.commandId===o){d.isComplete=!0,d.exitCode=r.exitCode,d.durationMs=s,a=d.commandLine,l=d.output;break}n.activeCommandId=void 0,n.activeCommandTimestamp=void 0,e.onCommandFinishedEmitter.fire({commandId:o,exitCode:r.exitCode,command:a,output:l}),this._stateManager.dispatchServerAction(e.uri,{type:"terminal/commandFinished",commandId:o,exitCode:r.exitCode,durationMs:s});break}case 5:{r.key==="Cwd"&&(e.cwd=r.value,this._stateManager.dispatchServerAction(e.uri,{type:"terminal/cwdChanged",cwd:r.value}));break}}}_appendToContent(e,n){let r=e.content.length>0?e.content[e.content.length-1]:void 0;r?.type==="command"&&!r.isComplete?(r.output+=n,e.contentSize+=n.length):r?.type==="unclassified"?(r.value+=n,e.contentSize+=n.length):(e.content.push({type:"unclassified",value:n}),e.contentSize+=n.length)}_getContentPartSize(e){return e.type==="command"?e.output.length:e.value.length}_trimContent(e){if(!(e.contentSize<=1e5)){for(;e.contentSize>8e4&&e.content.length>1;){let o=e.content.shift();e.contentSize-=this._getContentPartSize(o)}if(e.contentSize>8e4&&e.content.length>0){let o=e.content[0],s=e.contentSize-8e4;o.type==="command"?o.output=o.output.slice(s):o.value=o.value.slice(s),e.contentSize-=s}}}disposeTerminal(e){let n=this._terminals.get(e);n&&(this._terminals.delete(e),n.store.dispose(),this._broadcastTerminalList())}async getDefaultShell(){let e=this._configurationService.getRootValue(jt,"defaultShell");if(e)try{return await eo.promises.access(e,eo.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 Ac(at,process.env)}async _resolveCwd(e,n){let r=e;if(e){let s=y.parse(e);s.scheme==="file"&&s.fsPath&&s.fsPath!=="/"?r=s.fsPath:this._logService.warn(`[TerminalManager] Ignoring non-file cwd for ${n}: ${e}`)}try{if(r&&(await eo.promises.stat(r)).isDirectory())return r}catch{}let o=process.env.HOME||process.env.USERPROFILE||process.cwd();return this._logService.warn(`[TerminalManager] cwd '${r}' is not accessible, falling back to ${o}`),o}_broadcastTerminalList(){this._stateManager.dispatchServerAction(Be,{type:"root/terminalsChanged",terminals:this.getTerminalInfos()})}dispose(){for(let e of this._terminals.values())e.store.dispose();this._terminals.clear(),super.dispose()}};rs=x([C(1,O),C(2,gt),C(3,$e)],rs);var $c=$("diffComputeService"),o_=5e3;var a_="session-db";function di(i,t,e,n){return y.from({scheme:a_,authority:Zr(A.fromString(i)).toString(),path:`/${encodeURIComponent(t)}/${Zr(A.fromString(e))}/${n}/${Ce(e)}`}).toString()}function l_(i){let t=y.parse(i);if(t.scheme!==a_)return;let[,e,n,r]=t.path.split("/");if(!(!e||!n||r!=="before"&&r!=="after"))try{return{sessionUri:Mg(t.authority).toString(),toolCallId:decodeURIComponent(e),filePath:Mg(n).toString(),part:r}}catch{return}}var li=class{constructor(t,e,n,r,o){this._sessionUri=t;this._db=e;this._fileService=n;this._logService=r;this._diffComputeService=o;this._pendingEdits=new Map;this._completedEdits=new Map}async trackEditStart(t){let e=this._readFileWithExistence(t),n={beforeContent:A.fromString(""),beforeExisted:!1,snapshotDone:e.then(({content:r,existed:o})=>{n.beforeContent=r,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 r=this._completedEdits.get(n);if(!r)return;this._completedEdits.delete(n);let o=r.beforeContent.buffer,s=r.afterContent.buffer,a=r.beforeContent.toString(),l=r.afterContent.toString(),d=!r.beforeExisted&&s.length>0,c,u;try{let p=await this._diffComputeService.computeDiffCounts(a,l);c=p.added,u=d?0:p.removed}catch(p){this._logService.warn(`[FileEditTracker] Failed to compute diff counts: ${n}`,p)}try{await this._db.storeFileEdit({turnId:t,toolCallId:e,filePath:n,kind:d?"create":"edit",beforeContent:o,afterContent:s,addedLines:c,removedLines:u})}catch(p){this._logService.warn(`[FileEditTracker] Failed to persist file edit to database: ${n}`,p)}return{type:"fileEdit",before:{uri:y.file(n).toString(),content:{uri:di(this._sessionUri,e,n,"before")}},after:{uri:y.file(n).toString(),content:{uri:di(this._sessionUri,e,n,"after")}},diff:c!==void 0?{added:c,removed:u}: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),A.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:A.fromString(""),existed:!1}}}};li=x([C(2,Te),C(3,O),C(4,$c)],li);var d_="git-blob";function Um(i,t,e,n){return y.from({scheme:d_,path:n,query:JSON.stringify({sessionUri:i,sha:t,repoRelativePath:e})}).toString()}function c_(i){let t;try{t=y.parse(i)}catch{return}if(!(t.scheme!==d_||!t.query))try{let e=JSON.parse(t.query);if(typeof e.sessionUri=="string"&&typeof e.sha=="string"&&typeof e.repoRelativePath=="string")return{sessionUri:e.sessionUri,sha:e.sha,repoRelativePath:e.repoRelativePath}}catch{return}}var TP={"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/mcpServerStateChanged":!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/operationStatusChanged":!1,"changeset/cleared":!1,"annotations/set":!0,"annotations/updated":!0,"annotations/removed":!0,"annotations/entrySet":!0,"annotations/entryRemoved":!0,"terminal/data":!1,"terminal/input":!0,"terminal/resized":!0,"terminal/claimed":!0,"terminal/titleChanged":!0,"terminal/cwdChanged":!1,"terminal/exited":!1,"terminal/cleared":!0,"terminal/commandDetectionAvailable":!1,"terminal/commandExecuted":!1,"terminal/commandFinished":!1,"resourceWatch/changed":!1};function En(i,t){let e=`Unhandled action type: ${JSON.stringify(i)}`;(t??console.warn)(e)}function Hc(i,t,e){switch(t.type){case"root/agentsChanged":return{...i,agents:t.agents};case"root/activeSessionsChanged":return{...i,activeSessions:t.activeSessions};case"root/terminalsChanged":return{...i,terminals:t.terminals};case"root/configChanged":return i.config?{...i,config:{...i.config,values:t.replace?{...t.config}:{...i.config.values,...t.config}}}:i;default:return En(t,e),i}}function p_(i){return{toolCallId:i.toolCallId,toolName:i.toolName,displayName:i.displayName,contributor:i.contributor,_meta:i._meta}}function qc(i,t){return{...p_(i),_meta:t??i._meta}}function xP(i,t){if(!(!t||!i))return i.find(e=>e.id===t)}function wP(i){return i.activeTurn?i.activeTurn.responseParts.some(t=>t.kind==="toolCall"&&(t.toolCall.status==="pending-confirmation"||t.toolCall.status==="pending-result-confirmation")):!1}var RP=31;function Vc(i,t,e){return e?i|t:i&~t}function ss(i,t){let e;return t?e=t:(i.inputRequests?.length??0)>0||wP(i)?e=24:i.activeTurn?e=8:e=1,i.summary.status&~RP|e}function Bc(i){let t=ss(i);return t===i.summary.status?i:{...i,summary:{...i.summary,status:t}}}function Fm(i,t,e,n,r){if(!i.activeTurn||i.activeTurn.id!==t)return i;let o=i.activeTurn,s=o.responseParts.map(d=>{if(d.kind!=="toolCall")return d;let c=d.toolCall;return c.status==="completed"||c.status==="cancelled"?d:{kind:"toolCall",toolCall:{status:"cancelled",...p_(c),invocationMessage:c.status==="streaming"?c.invocationMessage??"":c.invocationMessage,toolInput:c.status==="streaming"?void 0:c.toolInput,reason:"skipped"}}}),a={id:o.id,message:o.message,responseParts:s,usage:o.usage,state:e,error:r},l={...i,turns:[...i.turns,a],activeTurn:void 0,summary:{...i.summary,modifiedAt:Date.now()}};return delete l.inputRequests,{...l,summary:{...l.summary,status:ss(l,n)}}}function EP(i,t){let e=i.inputRequests??[],n=e.findIndex(s=>s.id===t.id),r=[...e];if(n>=0){let s=t.answers??r[n].answers;r[n]={...t,answers:s}}else r.push(t);let o={...i,inputRequests:r};return{...o,summary:{...o.summary,status:Vc(ss(o),32,!1),modifiedAt:Date.now()}}}function os(i,t,e,n){let r=i.activeTurn;if(!r||r.id!==t)return i;let o=!1,s=r.responseParts.map(a=>{if(a.kind==="toolCall"&&a.toolCall.toolCallId===e){let l=n(a.toolCall);return l===a.toolCall?a:(o=!0,{...a,toolCall:l})}return a});return o?{...i,activeTurn:{...r,responseParts:s}}:i}function u_(i,t,e,n){let r=i.activeTurn;if(!r||r.id!==t)return i;let o=!1,s=r.responseParts.map(a=>!o&&(a.kind==="toolCall"?a.toolCall.toolCallId:"id"in a?a.id:void 0)===e?(o=!0,n(a)):a);return o?{...i,activeTurn:{...r,responseParts:s}}:i}function zc(i,t,e){switch(t.type){case"session/ready":return{...i,lifecycle:"ready"};case"session/creationFailed":return{...i,lifecycle:"creationFailed",creationError:t.error};case"session/turnStarted":{let n={...i,activeTurn:{id:t.turnId,message:t.message,responseParts:[],usage:void 0}};if(n={...n,summary:{...n.summary,status:Vc(ss(n),32,!1),modifiedAt:Date.now()}},t.queuedMessageId&&(n.steeringMessage?.id===t.queuedMessageId&&(n={...n,steeringMessage:void 0}),n.queuedMessages)){let r=n.queuedMessages.filter(o=>o.id!==t.queuedMessageId);n={...n,queuedMessages:r.length>0?r:void 0}}return n}case"session/delta":return u_(i,t.turnId,t.partId,n=>n.kind==="markdown"?{...n,content:n.content+t.content}:n);case"session/responsePart":return!i.activeTurn||i.activeTurn.id!==t.turnId?i:{...i,activeTurn:{...i.activeTurn,responseParts:[...i.activeTurn.responseParts,t.part]}};case"session/turnComplete":return Fm(i,t.turnId,"complete");case"session/turnCancelled":return Fm(i,t.turnId,"cancelled");case"session/error":return Fm(i,t.turnId,"error",2,t.error);case"session/toolCallStart":return!i.activeTurn||i.activeTurn.id!==t.turnId?i:{...i,activeTurn:{...i.activeTurn,responseParts:[...i.activeTurn.responseParts,{kind:"toolCall",toolCall:{toolCallId:t.toolCallId,toolName:t.toolName,displayName:t.displayName,contributor:t.contributor,_meta:t._meta,status:"streaming"}}]}};case"session/toolCallDelta":return os(i,t.turnId,t.toolCallId,n=>n.status!=="streaming"?n:{...n,...t._meta!==void 0?{_meta:t._meta}:{},partialInput:(n.partialInput??"")+t.content,invocationMessage:t.invocationMessage??n.invocationMessage});case"session/toolCallReady":return Bc(os(i,t.turnId,t.toolCallId,n=>{if(n.status!=="streaming"&&n.status!=="running")return n;let r=qc(n,t._meta);return t.confirmed?{status:"running",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:t.confirmed}:{status:"pending-confirmation",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmationTitle:t.confirmationTitle,edits:t.edits,editable:t.editable,...t.options?{options:t.options}:{}}}));case"session/toolCallConfirmed":return Bc(os(i,t.turnId,t.toolCallId,n=>{if(n.status!=="pending-confirmation")return n;let r=qc(n,t._meta),o=xP(n.options,t.selectedOptionId);return t.approved?{status:"running",...r,invocationMessage:n.invocationMessage,toolInput:t.editedToolInput??n.toolInput,confirmed:t.confirmed,...o?{selectedOption:o}:{}}:{status:"cancelled",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,reason:t.reason,reasonMessage:t.reasonMessage,userSuggestion:t.userSuggestion,...o?{selectedOption:o}:{}}}));case"session/toolCallComplete":return Bc(os(i,t.turnId,t.toolCallId,n=>{if(n.status!=="running"&&n.status!=="pending-confirmation")return n;let r=qc(n,t._meta),o=n.status==="running"?n.confirmed:"not-needed",s=n.status==="running"?n.selectedOption:void 0;return t.requiresResultConfirmation?{status:"pending-result-confirmation",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:o,...s?{selectedOption:s}:{},...t.result}:{status:"completed",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:o,...s?{selectedOption:s}:{},...t.result}}));case"session/toolCallResultConfirmed":return Bc(os(i,t.turnId,t.toolCallId,n=>{if(n.status!=="pending-result-confirmation")return n;let r=qc(n,t._meta);return t.approved?{status:"completed",...r,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",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,reason:"result-denied",...n.selectedOption?{selectedOption:n.selectedOption}:{}}}));case"session/toolCallContentChanged":return os(i,t.turnId,t.toolCallId,n=>n.status!=="running"?n:{...n,...t._meta!==void 0?{_meta:t._meta}:{},content:t.content});case"session/titleChanged":return{...i,summary:{...i.summary,title:t.title,modifiedAt:Date.now()}};case"session/usage":return!i.activeTurn||i.activeTurn.id!==t.turnId?i:{...i,activeTurn:{...i.activeTurn,usage:t.usage}};case"session/reasoning":return u_(i,t.turnId,t.partId,n=>n.kind==="reasoning"?{...n,content:n.content+t.content}:n);case"session/modelChanged":return{...i,summary:{...i.summary,model:t.model,modifiedAt:Date.now()}};case"session/agentChanged":return{...i,summary:{...i.summary,agent:t.agent,modifiedAt:Date.now()}};case"session/isReadChanged":return{...i,summary:{...i.summary,status:Vc(i.summary.status,32,t.isRead)}};case"session/isArchivedChanged":return{...i,summary:{...i.summary,status:Vc(i.summary.status,64,t.isArchived)}};case"session/activityChanged":return{...i,summary:{...i.summary,activity:t.activity}};case"session/changesetsChanged":{let{changesets:n,...r}=i;return t.changesets?{...r,changesets:t.changesets}:r}case"session/configChanged":return i.config?{...i,config:{...i.config,values:t.replace?{...t.config}:{...i.config.values,...t.config}},summary:{...i.summary,modifiedAt:Date.now()}}:i;case"session/metaChanged":return{...i,_meta:t._meta};case"session/serverToolsChanged":return{...i,serverTools:t.tools};case"session/activeClientChanged":return{...i,activeClient:t.activeClient??void 0};case"session/activeClientToolsChanged":return i.activeClient?{...i,activeClient:{...i.activeClient,tools:t.tools}}:i;case"session/customizationsChanged":return{...i,customizations:t.customizations};case"session/customizationToggled":{let n=i.customizations;if(!n)return i;let r=n.findIndex(s=>s.id===t.id);if(r<0)return i;let o=[...n];return o[r]={...n[r],enabled:t.enabled},{...i,customizations:o}}case"session/customizationUpdated":{let n=i.customizations??[],r=n.findIndex(s=>s.id===t.customization.id);if(r<0)return{...i,customizations:[...n,t.customization]};let o=[...n];return o[r]=t.customization,{...i,customizations:o}}case"session/customizationRemoved":{let n=i.customizations;if(!n)return i;let r=n.findIndex(a=>a.id===t.id);if(r>=0){let a=n.slice();return a.splice(r,1),{...i,customizations:a}}let o=!1,s=n.map(a=>{if(a.type==="mcpServer")return a;let l=a.children;if(!l)return a;let d=l.findIndex(u=>u.id===t.id);if(d<0)return a;o=!0;let c=l.slice();return c.splice(d,1),{...a,children:c}});return o?{...i,customizations:s}:i}case"session/mcpServerStateChanged":{let n=i.customizations;if(!n)return i;let r=n.findIndex(a=>a.id===t.id);if(r>=0){let a=n[r];if(a.type!=="mcpServer")return i;let l={...a,state:t.state,channel:t.channel},d=n.slice();return d[r]=l,{...i,customizations:d}}let o=!1,s=n.map(a=>{if(a.type==="mcpServer")return a;let l=a.children;if(!l)return a;let d=l.findIndex(m=>m.id===t.id);if(d<0)return a;let c=l[d];if(c.type!=="mcpServer")return a;o=!0;let u={...c,state:t.state,channel:t.channel},p=l.slice();return p[d]=u,{...a,children:p}});return o?{...i,customizations:s}:i}case"session/truncated":{let n;if(t.turnId===void 0)n=[];else{let o=i.turns.findIndex(s=>s.id===t.turnId);if(o<0)return i;n=i.turns.slice(0,o+1)}let r={...i,turns:n,activeTurn:void 0,summary:{...i.summary,modifiedAt:Date.now()}};return delete r.inputRequests,{...r,summary:{...r.summary,status:ss(r)}}}case"session/inputRequested":return EP(i,t.request);case"session/inputAnswerChanged":{let n=i.inputRequests,r=n?.findIndex(l=>l.id===t.requestId)??-1;if(!n||r<0)return i;let o=n[r],s={...o.answers??{}};t.answer===void 0?delete s[t.questionId]:s[t.questionId]=t.answer;let a=[...n];return a[r]={...o,answers:Object.keys(s).length>0?s:void 0},{...i,inputRequests:a,summary:{...i.summary,modifiedAt:Date.now()}}}case"session/inputCompleted":{let n=i.inputRequests;if(!n?.some(s=>s.id===t.requestId))return i;let r=n.filter(s=>s.id!==t.requestId),o={...i};return r.length>0?o.inputRequests=r:delete o.inputRequests,{...o,summary:{...o.summary,status:ss(o),modifiedAt:Date.now()}}}case"session/pendingMessageSet":{let n={id:t.id,message:t.message};if(t.kind==="steering")return{...i,steeringMessage:n};let r=i.queuedMessages??[],o=r.findIndex(s=>s.id===t.id);if(o>=0){let s=[...r];return s[o]=n,{...i,queuedMessages:s}}return{...i,queuedMessages:[...r,n]}}case"session/pendingMessageRemoved":{if(t.kind==="steering")return!i.steeringMessage||i.steeringMessage.id!==t.id?i:{...i,steeringMessage:void 0};let n=i.queuedMessages;if(!n)return i;let r=n.filter(o=>o.id!==t.id);return r.length===n.length?i:{...i,queuedMessages:r.length>0?r:void 0}}case"session/queuedMessagesReordered":{let n=i.queuedMessages;if(!n)return i;let r=new Map(n.map(a=>[a.id,a])),o=new Set,s=t.order.filter(a=>r.has(a)&&!o.has(a)?(o.add(a),!0):!1).map(a=>r.get(a));for(let a of n)o.has(a.id)||s.push(a);return{...i,queuedMessages:s}}default:return En(t,e),i}}function jc(i,t,e){switch(t.type){case"changeset/statusChanged":{if(t.status==="error")return{...i,status:t.status,error:t.error};let{error:n,...r}=i;return{...r,status:t.status}}case"changeset/fileSet":{let n=i.files.findIndex(o=>o.id===t.file.id);if(n<0)return{...i,files:[...i.files,t.file]};let r=[...i.files];return r[n]=t.file,{...i,files:r}}case"changeset/fileRemoved":{let n=i.files.findIndex(o=>o.id===t.fileId);if(n<0)return i;let r=[...i.files];return r.splice(n,1),{...i,files:r}}case"changeset/operationsChanged":{if(t.operations===void 0){let{operations:n,...r}=i;return r}return{...i,operations:t.operations}}case"changeset/operationStatusChanged":{if(i.operations===void 0)return i;let n=i.operations.findIndex(a=>a.id===t.operationId);if(n<0)return i;let r=i.operations[n],o;if(t.status==="error")o={...r,status:t.status,error:t.error};else{let{error:a,...l}=r;o={...l,status:t.status}}let s=[...i.operations];return s[n]=o,{...i,operations:s}}case"changeset/cleared":return i.files.length===0?i:{...i,files:[]};default:return En(t,e),i}}function Kc(i,t,e){switch(t.type){case"annotations/set":{let n=i.annotations.findIndex(o=>o.id===t.annotation.id);if(n<0)return{...i,annotations:[...i.annotations,t.annotation]};let r=[...i.annotations];return r[n]=t.annotation,{...i,annotations:r}}case"annotations/updated":{let n=i.annotations.findIndex(a=>a.id===t.annotationId);if(n<0)return i;let o={...i.annotations[n]};t.turnId!==void 0&&(o.turnId=t.turnId),t.resource!==void 0&&(o.resource=t.resource),t.range!==void 0&&(o.range=t.range),t.resolved!==void 0&&(o.resolved=t.resolved);let s=[...i.annotations];return s[n]=o,{...i,annotations:s}}case"annotations/removed":{let n=i.annotations.findIndex(o=>o.id===t.annotationId);if(n<0)return i;let r=[...i.annotations];return r.splice(n,1),{...i,annotations:r}}case"annotations/entrySet":{let n=i.annotations.findIndex(l=>l.id===t.annotationId);if(n<0)return i;let r=i.annotations[n],o=r.entries.findIndex(l=>l.id===t.entry.id),s;o<0?s=[...r.entries,t.entry]:(s=[...r.entries],s[o]=t.entry);let a=[...i.annotations];return a[n]={...r,entries:s},{...i,annotations:a}}case"annotations/entryRemoved":{let n=i.annotations.findIndex(l=>l.id===t.annotationId);if(n<0)return i;let r=i.annotations[n],o=r.entries.findIndex(l=>l.id===t.entryId);if(o<0)return i;let s=[...r.entries];s.splice(o,1);let a=[...i.annotations];return a[n]={...r,entries:s},{...i,annotations:a}}default:return En(t,e),i}}var Wm="/annotations";function Gc(i){return`${i}${Wm}`}function AP(i){if(!i.endsWith(Wm))return;let t=i.slice(0,i.length-Wm.length);if(t)return{sessionUri:t}}function f_(i){return AP(i)!==void 0}var kP=500,Jc=class{constructor(t={}){this._states=new Map;this._lru=new _a;this._softLimit=Math.max(0,t.softLimit??kP),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)}}};var as=class extends T{constructor(e,n={}){super();this._logService=e;this._serverSeq=0;this._sessionStates=new Map;this._annotations=new Map;this._sessionsWithActiveTurn=new Set;this._lastNotifiedSummaries=new Map;this._dirtySummaries=new Set;this._summaryNotifyScheduler=this._register(new Yr(()=>this._flushSummaryNotifications(),100));this._onDidEmitEnvelope=this._register(new w);this.onDidEmitEnvelope=this._onDidEmitEnvelope.event;this._onDidEmitNotification=this._register(new w);this.onDidEmitNotification=this._onDidEmitNotification.event;this._onDidChangeSessionActiveTurn=this._register(new w);this.onDidChangeSessionActiveTurn=this._onDidChangeSessionActiveTurn.event;this._log=e=>this._logService.warn(`[AgentHostStateManager] ${e}`);this._changesets=new Jc(n.changesetStateRetention),this._rootState=PI(),this._rootState={...this._rootState,config:{schema:Qi.toProtocol(),values:Qi.validateOrDefault({},{permissions:{allow:[],deny:[]},[fl]:UI(3)})},_meta:DI(this._rootState._meta,n.hostBuildInfo)}}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()]}getOverlaySessionSummaries(){let e=[];for(let n of this._sessionStates.values())n.lifecycle==="creating"&&!n.activeTurn&&n.turns.length===0||e.push(n.summary);return e}getSessionUrisWithPrefix(e){let n=[];for(let r of this._sessionStates.keys())r.startsWith(e)&&n.push(r);return n}getSnapshot(e){if(ul(e))return{resource:Be,state:this._rootState,fromSeq:this._serverSeq};let n=this._changesets.get(e);if(n)return{resource:e,state:n,fromSeq:this._serverSeq};if(f_(e))return{resource:e,state:this._annotations.get(e)??{annotations:[]},fromSeq:this._serverSeq};let r=this._sessionStates.get(e);if(r)return{resource:e,state:r,fromSeq:this._serverSeq}}getChangesetState(e){return this._changesets.get(e)}onChangesetLivenessChanged(){this._changesets.trimEvictableEntries()}createSession(e,n){let r=e.resource;if(this._sessionStates.has(r))return this._logService.warn(`[AgentHostStateManager] Session already exists: ${r}`),this._sessionStates.get(r);let o=Tm(e);return this._sessionStates.set(r,o),this._logService.trace(`[AgentHostStateManager] Created session: ${r}`),n?.emitNotification!==!1&&(this._lastNotifiedSummaries.set(r,e),this._onDidEmitNotification.fire({type:"root/sessionAdded",channel:Be,summary:e})),o}markSessionPersisted(e,n){let r=e.toString(),o=this._sessionStates.get(r);if(!o){this._logService.warn(`[AgentHostStateManager] markSessionPersisted: unknown session ${r}`);return}this._lastNotifiedSummaries.has(r)||(o.summary=n,this._lastNotifiedSummaries.set(r,n),this._onDidEmitNotification.fire({type:"root/sessionAdded",channel:Be,summary:n}))}restoreSession(e,n){let r=e.resource;if(this._sessionStates.has(r))return this._logService.warn(`[AgentHostStateManager] Session already exists (restore): ${r}`),this._sessionStates.get(r);let o={...Tm(e),lifecycle:"ready",turns:n};return this._sessionStates.set(r,o),this._lastNotifiedSummaries.set(r,e),this._logService.trace(`[AgentHostStateManager] Restored session: ${r} (${n.length} turns)`),o}removeSession(e){this._sessionStates.get(e)&&(this._dirtySummaries.has(e)&&this._flushSummaryNotificationFor(e),this._sessionsWithActiveTurn.delete(e)&&(this._onDidChangeSessionActiveTurn.fire({session:e,active:!1}),this.dispatchServerAction(Be,{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.disposeSessionAnnotations(e),this.removeSession(e),n&&this._onDidEmitNotification.fire({type:"root/sessionRemoved",channel:Be,session:e})}setSessionMeta(e,n){this.dispatchServerAction(e,{type:"session/metaChanged",_meta:n})}registerChangeset(e,n="computing"){return this._changesets.register(e,n),e}setSessionSummaryChanges(e,n){let r=this._sessionStates.get(e);if(!r){this._logService.warn(`[AgentHostStateManager] setSessionSummaryChanges: unknown session ${e}`);return}if($i(r.summary.changes,n))return;let o={...r,summary:{...r.summary,changes:n}};this._sessionStates.set(e,o),this._dirtySummaries.add(e),this._summaryNotifyScheduler.schedule()}setSessionChangesets(e,n){let r=this._sessionStates.get(e);if(!r){this._logService.warn(`[AgentHostStateManager] setSessionChangesets: unknown session ${e}`);return}if(jg(r.changesets??[],n??[],$i))return;let o=n?n.slice():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 r of this._changesets.keys()){let o=Vt(r);o&&o.sessionUri===e&&n.push(r)}for(let r of n)this.disposeChangeset(r)}disposeSessionAnnotations(e){this._annotations.delete(Gc(e))}getActiveTurnId(e){return this._sessionStates.get(e)?.activeTurn?.id}dispatchServerAction(e,n){this._applyAndEmit(e,n,void 0)}dispatchClientAction(e,n,r){return this._applyAndEmit(e,n,r)}_applyAndEmit(e,n,r){let o;if(lI(n)){if(n.type==="root/configChanged"&&this._rootState.config){let a=this._rootState.config.values,l=n.config;if(n.replace?We(a,l):We({...a,...l},a))return this._rootState}this._rootState=Hc(this._rootState,n,this._log),o=this._rootState}if(Ic(n)){let a=n,l=e,d=this._sessionStates.get(l);if(d){let c=zc(d,a,this._log);this._sessionStates.set(l,c),d.summary!==c.summary&&(this._dirtySummaries.add(l),this._summaryNotifyScheduler.schedule());let u=!!d.activeTurn,p=!!c.activeTurn;u!==p&&(p?this._sessionsWithActiveTurn.add(l):this._sessionsWithActiveTurn.delete(l),this._onDidChangeSessionActiveTurn.fire({session:l,active:p}),this.dispatchServerAction(Be,{type:"root/activeSessionsChanged",activeSessions:this._sessionsWithActiveTurn.size})),o=c}else this._logService.warn(`[AgentHostStateManager] Action for unknown session: ${l}, type=${n.type}`)}if(dI(n)){let a=n,l=e,d=this._changesets.get(l);if(!d){this._logService.warn(`[AgentHostStateManager] Action for unknown changeset: ${l}, type=${n.type}`);return}let c=jc(d,a,this._log);c!==d&&this._changesets.set(l,c),o=c}if(cI(n)){let a=n,l=e,d=this._annotations.get(l)??{annotations:[]},c=Kc(d,a,this._log);c!==d&&this._annotations.set(l,c),o=c}let s={channel:e,action:n,serverSeq:++this._serverSeq,origin:r};return this._logService.trace(`[AgentHostStateManager] Emitting envelope: seq=${s.serverSeq}, type=${n.type}${r?`, origin=${r.clientId}:${r.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),r=this._lastNotifiedSummaries.get(e);if(!n||!r||n.summary===r)return;let o=n.summary,s={};o.title!==r.title&&(s.title=o.title),o.status!==r.status&&(s.status=o.status),o.activity!==r.activity&&(s.activity=o.activity),o.modifiedAt!==r.modifiedAt&&(s.modifiedAt=o.modifiedAt),o.project!==r.project&&(s.project=o.project),o.model!==r.model&&(s.model=o.model),o.changes!==r.changes&&(s.changes=o.changes),o.workingDirectory!==r.workingDirectory&&(s.workingDirectory=o.workingDirectory),this._lastNotifiedSummaries.set(e,o),Object.keys(s).length>0&&this._onDidEmitNotification.fire({type:"root/sessionSummaryChanged",channel:Be,session:e,changes:s})}};as=x([C(0,O)],as);import*as Yc from"child_process";var vl=$("environmentService"),yn=vl;var tt=$("agentHostGitService"),Qc="agentHost.diffBaseBranch";function g_(i){return i==="main"?0:i==="master"?1:2}function DP(i,t){let e=t?.query?.toLowerCase(),n=e?i.filter(r=>r.toLowerCase().includes(e)):[...i];return n.sort((r,o)=>g_(r)-g_(o)),t?.limit?n.slice(0,t.limit):n}var ls=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 r=await this._runGit(t,n);if(!r)return[];let o=r.split(/\r?\n/g).map(s=>s.trim()).filter(s=>s.length>0);return DP(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,r){let o=await this._resolveRemoteTrackingBranch(t,r)??r;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 commitAll(t,e){await this._runGit(t,["add","-A","--",":/"],{throwOnError:!0}),await this._runGit(t,["commit","--no-verify","--no-gpg-sign","-m",e],{timeout:6e4,throwOnError:!0})}async hasUpstream(t,e){let n=await this._runGit(t,["rev-parse","--abbrev-ref",`${e}@{upstream}`]);return n!==void 0&&n.trim().length>0}async pushBranch(t,e,n){let r=["push"];n&&r.push("--set-upstream"),r.push("origin",e),await this._runGit(t,r,{timeout:6e4,throwOnError:!0})}async computeSessionFileDiffs(t,e){if((await this._runGit(t,["rev-parse","--is-inside-work-tree"]))?.trim()!=="true")return;let r=(await this._runGit(t,["rev-parse","--show-toplevel"]))?.trim();if(!r)return;let o=y.file(r),s;if(e.baseBranch){let c=await this._resolveRemoteTrackingBranch(o,e.baseBranch)??e.baseBranch;s=(await this._runGit(o,["merge-base","HEAD",c]))?.trim()}s||(s=(await this._runGit(o,["rev-parse","HEAD"]))?.trim()),s||(s=$m);let a=await this._runGit(o,["status","--porcelain=v1","-z","--untracked-files=all"]);if(a===void 0)return;let l=LP(a).length>0,d;if(!l)d=await this._runGit(o,["diff","--raw","--numstat","--diff-filter=ADMR","-z",s,"--"]);else{let c=Hm(a);d=await this._runWithTempIndex(o,s,c)}if(d!==void 0)return m_(d,o,e.sessionUri,s)}async _runWithTempIndex(t,e,n){let r=y.joinPath(this._environmentService.tmpDir,`agent-host-git-diff-${N()}`);await this._fileService.createFolder(r);let s={GIT_INDEX_FILE:y.joinPath(r,"index").fsPath};s.COMMAND_HOOK_LOCK="1";try{return await this._runGit(t,["read-tree","HEAD"],{env:s})===void 0&&await this._runGit(t,["read-tree",$m],{env:s}),await this._stageChangedPaths(t,r,n,s)?await this._runGit(t,["diff","--cached","--raw","--numstat","--diff-filter=ADMR","-z",e,"--"],{env:s}):void 0}finally{try{await this._fileService.del(r,{recursive:!0,useTrash:!1})}catch{}}}async _stageChangedPaths(t,e,n,r){if(n.length===0)return!0;let o=y.joinPath(e,"pathspec");return await this._fileService.writeFile(o,A.fromString(n.join("\0")+"\0")),this._logService.debug(`[agentHostGitService] Staging ${n.length} changed path(s) into temp index`),await this._runGit(t,["add","-A",`--pathspec-from-file=${o.fsPath}`,"--pathspec-file-nul"],{env:{...r,GIT_LITERAL_PATHSPECS:"1"}})!==void 0}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=>{Yc.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(A.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 r=y.file(n),o=await this._runGit(r,["status","--porcelain=v1","-z","--untracked-files=all"]);if(o===void 0)return;let s=Hm(o),a=y.joinPath(this._environmentService.tmpDir,`agent-host-checkpoint-${N()}`);await this._fileService.createFolder(a);let d={GIT_INDEX_FILE:y.joinPath(a,"index").fsPath,COMMAND_HOOK_LOCK:"1"};try{return await this._runGit(r,["read-tree","HEAD"],{env:d})===void 0&&await this._runGit(r,["read-tree",$m],{env:d}),await this._stageChangedPaths(r,a,s,d)&&(await this._runGit(r,["write-tree"],{env:d}))?.trim()||void 0}finally{try{await this._fileService.del(a,{recursive:!0,useTrash:!1})}catch{}}}async commitTree(t,e,n,r){let o=["commit-tree",e];return n&&o.push("-p",n),o.push("-m",r),(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(r=>`delete ${r}\0\0`).join("");await new Promise(r=>{Yc.execFile("git",["update-ref","--stdin","-z"],{cwd:t.fsPath,timeout:1e4},()=>{r()}).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 r=y.file(n),o=(await this._runGit(r,["rev-parse","--verify","--quiet",e.fromRef]))?.trim(),s=(await this._runGit(r,["rev-parse","--verify","--quiet",e.toRef]))?.trim();if(!o||!s)return;let a=await this._runGit(r,["diff","--raw","--numstat","--diff-filter=ADMR","-z",o,s,"--"]);if(a!==void 0)return m_(a,r,e.sessionUri,o,s)}async _computeSessionGitState(t){if((await this._runGit(t,["rev-parse","--is-inside-work-tree"]))?.trim()!=="true")return;let[n,r,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=NP(n),a=UP(r),l=$P(o),d=FP(r),c=s.outgoingChanges;if(c===void 0&&l&&s.branchName&&s.branchName!==l){let p=await this._runGit(t,["rev-list","--count",`${l}..HEAD`]),m=p===void 0?NaN:Number(p.trim());Number.isFinite(m)&&(c=m)}let u={hasGitHubRemote:a,branchName:s.branchName,baseBranchName:l,upstreamBranchName:s.upstreamBranchName,incomingChanges:s.incomingChanges,outgoingChanges:c,uncommittedChanges:s.uncommittedChanges,githubOwner:d?.owner,githubRepo:d?.repo};return HP(u)}_runGit(t,e,n){return this._logService.trace(`[agentHostGitService] > git ${e.join(" ")}`),new Promise((r,o)=>{let s=n?.env?{...process.env,...n.env}:void 0,a=n?.timeout??5e3,l=!1,d=Yc.execFile("git",[...e],{cwd:t.fsPath,env:s,maxBuffer:n?.maxBuffer??32*1024*1024},(u,p,m)=>{if(u){if(m&&this._logService.warn(`[agentHostGitService] > git ${e.join(" ")} failed; full stderr:
${m}`),n?.throwOnError){o(new Error(OP(e,a,l,u,m),{cause:u}));return}r(void 0);return}r(p)}),c=setTimeout(()=>{l=!0,d.kill()},a);d.on("exit",()=>clearTimeout(c))})}};ls=x([C(0,Te),C(1,yn),C(2,O)],ls);function OP(i,t,e,n,r){let o=i[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=MP(r);return a?`${s}: ${a}`:s}function MP(i){if(!i)return"";let t=i.split(/[\r\n]+/g).map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0)return"";let e=200,r=t.find(o=>/\bgit-lfs\b/i.test(o)&&/(command not found|not recognized|no such file)/i.test(o))??t[t.length-1];return r.length>e?`${r.slice(0,e-1)}\u2026`:r}var $m="4b825dc642cb6eb9a060e54bf8d69288fbee4904";function LP(i){return Hm(i,t=>t==="??")}function Hm(i,t=()=>!0){if(!i)return[];let e=[],n=new Set,r=s=>{s&&!n.has(s)&&(n.add(s),e.push(s))},o=i.split("\0");for(let s=0;s<o.length;s++){let a=o[s];if(!a)continue;let l=a.substring(0,2),d=a.substring(3),c=l[0]==="R"||l[1]==="R"||l[0]==="C"||l[1]==="C";if(t(l)){if(r(d),c){let u=o[++s];u&&r(u)}}else c&&s++}return e}function m_(i,t,e,n,r){let o=i.split("\0"),s=[],a=new Map,l=0;for(;l<o.length;){let d=o[l++];if(d)if(d.startsWith(":")){let u=d.split(" ")[4]??"",p=o[l++];if(!p)continue;switch(u[0]){case"A":s.push({kind:"create",newPath:p});break;case"M":s.push({kind:"edit",oldPath:p,newPath:p});break;case"D":s.push({kind:"delete",oldPath:p});break;case"R":{let m=o[l++];if(!m)continue;s.push({kind:"rename",oldPath:p,newPath:m});break}default:break}}else{let[c,u,p]=d.split("	"),m;if(p===""||p===void 0){let h=o[l++];m=o[l++]??h??""}else m=p;if(!m)continue;a.set(m,{added:c==="-"?0:Number(c)||0,removed:u==="-"?0:Number(u)||0})}}return s.map(d=>{let c=a.get(d.newPath??d.oldPath??""),u=d.oldPath?y.joinPath(t,d.oldPath):void 0,p=d.newPath?y.joinPath(t,d.newPath):void 0,m=d.kind!=="create"&&d.oldPath&&u?{uri:u.toString(),content:{uri:Um(e,n,d.oldPath,u.path)}}:void 0,h=d.kind!=="delete"&&d.newPath&&p?{uri:p.toString(),content:r!==void 0?{uri:Um(e,r,d.newPath,p.path)}:{uri:p.toString()}}:void 0,v={added:c?.added??0,removed:c?.removed??0};return{...m?{before:m}:{},...h?{after:h}:{},diff:v}})}function NP(i){if(!i)return{};let t,e,n,r,o=0;for(let s of i.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]),r=Number(l[2]))}else a.startsWith("#")||o++}return{branchName:t,upstreamBranchName:e,outgoingChanges:n,incomingChanges:r,uncommittedChanges:o}}function UP(i){if(i!==void 0)return i.trim()?/github\.com[:\/]/i.test(i):!1}function FP(i){if(!i)return;let t=[];for(let n of i.split(/\r?\n/)){let r=n.trim();if(!r)continue;let o=/^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(r);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 r=WP(n);if(r)return r}}function WP(i){let t=/^[^@\s]+@github\.com:([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(i);if(t)return{owner:t[1],repo:t[2]};if(t=/^[a-z+]+:\/\/(?:[^@\/\s]+@)?github\.com(?::\d+)?\/([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(i),t)return{owner:t[1],repo:t[2]}}function $P(i){let t=i?.trim();if(!t)return;let e="refs/remotes/origin/";return t.startsWith(e)?t.substring(e.length):t}function HP(i){let t={};for(let[e,n]of Object.entries(i))n!==void 0&&(t[e]=n);return t}var Wn=$("agentHostCheckpointService"),to="checkpoint.baseRef";function qm(i,t){return`refs/agents/${i}/checkpoints/turn/${t}`}var h_={_serviceBrand:void 0,captureBaseline:async()=>{},captureTurnCheckpoint:async()=>{},getTurnCheckpointPair:async()=>{},getBaselineCheckpointRef:async()=>{},disposeSessionData:async()=>{}};import{Worker as qP}from"worker_threads";var ci=class extends T{constructor(e){super();this._logService=e;this._workerFailures=0;this._nextId=1;this._pending=new Map}async computeDiffCounts(e,n,r=o_){let o=this._ensureWorker(),s=this._nextId++;return new Promise((a,l)=>{this._pending.set(s,{resolve:a,reject:l});try{o.postMessage({id:s,fn:"computeDiffCounts",args:[e,n,r]})}catch(d){this._pending.delete(s),l(d instanceof Error?d:new Error(String(d)))}})}_ensureWorker(){if(this._workerFailures>=3)throw new Error("Diff compute worker failed too many times");if(!this._worker){let e=dt.asFileUri("vs/platform/agentHost/node/diffWorkerMain.js").fsPath,n=new qP(e,{name:"Diff compute worker"});n.on("message",r=>{let o=this._pending.get(r.id);if(o)if(this._pending.delete(r.id),r.err){let s=new Error(r.err.message);r.err.stack&&(s.stack=r.err.stack),o.reject(s)}else o.resolve(r.res)}),n.on("error",r=>{this._logService.error("[DiffComputeService] Worker error",r);for(let[,o]of this._pending)o.reject(r);this._pending.clear(),this._worker=void 0,this._workerFailures++}),this._worker=n}return this._worker}dispose(){this._worker&&(this._worker.terminate(),this._worker=void 0);for(let[,e]of this._pending)e.reject(new Error("DiffComputeService disposed"));this._pending.clear(),super.dispose()}};ci=x([C(0,O)],ci);function y_(i){return i.after?.uri??i.before?.uri}function v_(i,t,e,n){let r=t.firstKind!=="create",o=t.lastKind!=="delete";return{...r?{before:{uri:y.file(t.firstFilePath).toString(),content:{uri:di(i,t.firstToolCallId,t.firstFilePath,"before")}}}:{},...o?{after:{uri:y.file(t.terminalPath).toString(),content:{uri:di(i,t.lastToolCallId,t.lastFilePath,"after")}}}:{},diff:{added:e,removed:n}}}async function S_(i,t,e,n){let r,o=!1;if(n){let p=await t.getFileEditsByTurn(n.changedTurnId);if(p.length===0)return[...n.previousDiffs];let m=new Set(n.previousDiffs.map(y_));p.some(v=>v.kind==="rename"||m.has(y.file(v.filePath).toString()))?r=await t.getAllFileEdits():(r=p,o=!0)}else r=await t.getAllFileEdits();if(r.length===0)return[];let s=new Map,a=new Map,l=n&&!o?new Set:void 0;for(let p of r){let m;p.kind==="rename"&&p.originalPath?(m=s.get(p.originalPath)??p.originalPath,s.set(p.filePath,m),s.delete(p.originalPath)):(m=s.get(p.filePath)??p.filePath,s.set(p.filePath,m)),l&&p.turnId===n.changedTurnId&&l.add(m);let h=a.get(m);h?(h.terminalPath=p.filePath,h.lastToolCallId=p.toolCallId,h.lastFilePath=p.filePath,h.lastKind=p.kind):a.set(m,{terminalPath:p.filePath,firstToolCallId:p.toolCallId,firstFilePath:p.kind==="rename"&&p.originalPath?p.originalPath:p.filePath,firstKind:p.kind,lastToolCallId:p.toolCallId,lastFilePath:p.filePath,lastKind:p.kind})}let d=n&&!o?new Map(n.previousDiffs.map(p=>[y_(p),p])):void 0,c=[],u=[];for(let[p,m]of a){if(l&&!l.has(p)){let h=y.file(m.terminalPath).toString(),v=d.get(h);v&&c.push(v);continue}u.push((async()=>{let h;if(m.firstKind==="create")h="";else{let b=await t.readFileEditContent(m.firstToolCallId,m.firstFilePath);h=b?.beforeContent?new TextDecoder().decode(b.beforeContent):""}let v;if(m.lastKind==="delete")v="";else{let b=await t.readFileEditContent(m.lastToolCallId,m.lastFilePath);v=b?.afterContent?new TextDecoder().decode(b.afterContent):""}if(h===v)return;let I=await e.computeDiffCounts(h,v);c.push(v_(i,m,I.added,I.removed))})())}return await Promise.allSettled(u),o&&c.push(...n.previousDiffs),c}async function b_(i,t,e,n){let r=await t.getFileEditsByTurn(n);if(r.length===0)return[];let o=new Map,s=new Map;for(let d of r){let c;d.kind==="rename"&&d.originalPath?(c=o.get(d.originalPath)??d.originalPath,o.set(d.filePath,c),o.delete(d.originalPath)):(c=o.get(d.filePath)??d.filePath,o.set(d.filePath,c));let u=s.get(c);u?(u.terminalPath=d.filePath,u.lastToolCallId=d.toolCallId,u.lastFilePath=d.filePath,u.lastKind=d.kind):s.set(c,{terminalPath:d.filePath,firstToolCallId:d.toolCallId,firstFilePath:d.kind==="rename"&&d.originalPath?d.originalPath:d.filePath,firstKind:d.kind,lastToolCallId:d.toolCallId,lastFilePath:d.filePath,lastKind:d.kind})}let a=[],l=[];for(let d of s.values())l.push((async()=>{let c;if(d.firstKind==="create")c="";else{let m=await t.readFileEditContent(d.firstToolCallId,d.firstFilePath);c=m?.beforeContent?new TextDecoder().decode(m.beforeContent):""}let u;if(d.lastKind==="delete")u="";else{let m=await t.readFileEditContent(d.lastToolCallId,d.lastFilePath);u=m?.afterContent?new TextDecoder().decode(m.afterContent):""}if(c===u)return;let p=await e.computeDiffCounts(c,u);a.push(v_(i,d,p.added,p.removed))})());return await Promise.allSettled(l),a}var Sl="checkpoint.workingDir",ds=class extends T{constructor(e,n,r){super();this._sessionDataService=e;this._gitService=n;this._logService=r;this._sequencer=new nt;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 r=this._sessionDataService.openDatabase(e);try{let o=await r.object.getMetadata(to);if(o)return o;let s=this._sanitizedSessionId(e),a=qm(s,0),l=await this._writeCheckpointCommit(n,void 0,`Agent host session ${s} - baseline checkpoint`);if(!l)return;let d=await this._gitService.getRepositoryRoot(n);return d?(await this._gitService.updateRef(d,a,l.commitOid),await r.object.setMetadata(to,a),await r.object.setMetadata(Sl,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{r.dispose()}}captureTurnCheckpoint(e,n){return this._sequencer.queue(e.toString(),()=>this._captureTurnCheckpoint(e,n))}async _captureTurnCheckpoint(e,n){let r=this._sessionDataService.openDatabase(e);try{let[o,s,a,l]=await Promise.all([r.object.getMetadata(to),r.object.getMetadata(Sl),r.object.getTurnCheckpointRef(n),r.object.getPreviousCheckpointRef(n)]);if(a)return a;if(!o||!s)return;let d=y.parse(s),c=await this._gitService.getRepositoryRoot(d);if(!c)return;let u=l??o,p=await this._gitService.revParse(c,u);if(!p){this._logService.warn(`[AgentHostCheckpoint] Parent ref ${u} missing for session ${e.toString()}`);return}let m=await this._gitService.captureWorkingTreeAsTree(d);if(!m)return;let h=await this._gitService.revParse(c,`${p}^{tree}`);if(h&&h===m)return await r.object.setTurnCheckpointRef(n,u),this._logService.trace(`[AgentHostCheckpoint] No-op turn ${n} for ${e.toString()}; reusing ${u}`),u;let v=this._sanitizedSessionId(e),I=await this._nextTurnNumber(r.object),b=qm(v,I),S=await this._gitService.commitTree(c,m,p,`Agent host session ${v} - turn ${I}`);return S?(await this._gitService.updateRef(c,b,S),await r.object.setTurnCheckpointRef(n,b),this._logService.trace(`[AgentHostCheckpoint] Captured turn ${I} for ${e.toString()} at ${b}`),b):void 0}catch(o){this._logService.warn(`[AgentHostCheckpoint] Failed to capture turn checkpoint for ${e.toString()}/${n}`,o);return}finally{r.dispose()}}async getTurnCheckpointPair(e,n){let r=this._sessionDataService.openDatabase(e);try{let[o,s,a]=await Promise.all([r.object.getTurnCheckpointRef(n),r.object.getPreviousCheckpointRef(n),r.object.getMetadata(to)]);if(!o)return;let l=s??a;return l?{parent:l,current:o}:void 0}finally{r.dispose()}}async getBaselineCheckpointRef(e){let n=this._sessionDataService.openDatabase(e);try{return await n.object.getMetadata(to)}finally{n.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[r,o,s]=await Promise.all([n.object.getMetadata(Sl),n.object.getMetadata(to),n.object.getAllCheckpointRefs()]);if(!r)return;let a=y.parse(r),l=await this._gitService.getRepositoryRoot(a);if(!l)return;let d=new Set;o&&d.add(o);for(let c of s)d.add(c);if(d.size===0)return;await this._gitService.deleteRefs(l,[...d]),this._logService.trace(`[AgentHostCheckpoint] Deleted ${d.size} checkpoint refs for ${e.toString()}`)}catch(r){this._logService.warn(`[AgentHostCheckpoint] Failed to dispose checkpoint refs for ${e.toString()}`,r)}finally{n.dispose()}}async _writeCheckpointCommit(e,n,r){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,r);if(a)return{commitOid:a}}async _nextTurnNumber(e){let n=await e.getAllCheckpointRefs(),r=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>r&&(r=l)}return r+1}_sanitizedSessionId(e){return F.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};ds=x([C(0,ft),C(1,tt),C(2,O)],ds);var Zc="agentHost.changeset.branch",bl="agentHost.changeset.session",Il="diffs",no="agentHost.changes";function Xc(i,t){return t==="branch"?oi(i):Bt(i)}function BP(i){return i==="branch"?Zc:bl}function Vm(i){if(!i)return;let t=0,e=0;for(let n of i)t+=n.diff?.added??0,e+=n.diff?.removed??0;return{additions:t,deletions:e,files:i.length}}function I_(i){let t=i?.status==="ready"?i.files.map(e=>e.edit):void 0;return Vm(t)}function __(i){return Vm(i)}function Bm(i,t,e,n){if(i)try{return JSON.parse(i)}catch(r){n.warn(`[AgentHostChangesetService] Failed to parse persisted ${e} diffs for ${t}: ${xt(r)}`);return}}var ui=$("agentHostChangesetService"),Er=class extends T{constructor(e,n,r,o,s){super();this._stateManager=e;this._logService=n;this._sessionDataService=r;this._gitService=o;this._checkpointService=s;this._diffComputationSequencer=new nt;this._debouncedDiffTimers=this._register(new ve);this._perTurnDebouncedDiffTimers=this._register(new ve);this._activeStaticComputes=new Set;this._hasTurnSubscribers=()=>!1;this._hasUncommittedSubscribers=()=>!1;this._diffComputeService=this._register(new ci(this._logService))}static{this._DIFF_DEBOUNCE_MS=5e3}setTurnSubscriberProbe(e){this._hasTurnSubscribers=e}setUncommittedSubscriberProbe(e){this._hasUncommittedSubscribers=e}registerStaticChangesets(e){this._stateManager.registerChangeset(oi(e)),this._stateManager.registerChangeset(xn(e)),this._stateManager.registerChangeset(Bt(e))}restoreStaticChangeset(e,n,r){let o=this._stateManager.registerChangeset(Xc(e,n));this._publishChangesetDiffs(e,o,r)}parsePersistedStaticChangesets(e,n){let r=Bm(n.branchRaw,e,"branch",this._logService),o=Bm(n.sessionRaw,e,"session",this._logService)??Bm(n.legacyRaw,e,"session (legacy)",this._logService);return{branch:r,session:o}}applyPersistedStaticChangesets(e,n){this._seedIfEmpty(e,"branch",n.branch),this._seedIfEmpty(e,"session",n.session)}restorePersistedStaticChangesets(e,n){let r=this.parsePersistedStaticChangesets(e,n);return this.applyPersistedStaticChangesets(e,r),r}persistChangesSummary(e,n){this._persistSessionFlag(e,no,JSON.stringify(n))}isStaticChangesetComputeActive(e){return this._activeStaticComputes.has(e)}_seedIfEmpty(e,n,r){if(!r)return;let o=this._stateManager.getChangesetState(Xc(e,n));o&&o.files.length>0||this.restoreStaticChangeset(e,n,r)}refreshBranchChangeset(e){this._scheduleStaticRecompute(e,"branch",void 0,this._markStaticChangesetComputing(e,"branch"))}refreshSessionChangeset(e){this._scheduleStaticRecompute(e,"session",void 0,this._markStaticChangesetComputing(e,"session"))}async computeTurnChangeset(e,n){let r=this._stateManager.registerChangeset(sI(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(r,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:s instanceof Error?s.message:String(s)}}),r}try{let s=await this._computeTurnDiffsPreferCheckpoint(e,o.object,n);this._publishChangesetDiffs(e,r,s)}catch(s){this._logService.warn(`[AgentHostChangesetService] Failed to compute turn diffs for ${e}/${n}`,s),this._stateManager.dispatchServerAction(r,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:s instanceof Error?s.message:String(s)}})}finally{o.dispose()}return r}async computeCompareTurnsChangeset(e,n,r){let o=this._stateManager.registerChangeset(aI(e,n,r)),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,d]=await Promise.all([this._checkpointService.getTurnCheckpointPair(a,n).then(p=>p?.current),this._checkpointService.getTurnCheckpointPair(a,r)]);if(!l||!d){let p=!l&&!d?"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 ${p}; compare requires git-backed sessions.`}}),o}if(l===d.current)return this._publishChangesetDiffs(e,o,[]),o;let c=await this._resolveWorkingDirectory(s.object);if(!c)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 u=await this._gitService.computeFileDiffsBetweenRefs(c,{sessionUri:e,fromRef:l,toRef:d.current});if(u===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}..${d.current}).`}}),o;this._publishChangesetDiffs(e,o,u)}catch(a){this._logService.warn(`[AgentHostChangesetService] Failed to compute compare-turns diffs for ${e}/${n}/${r}`,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 computeUncommittedChangeset(e){let n=this._stateManager.registerChangeset(xn(e));if(!this._hasUncommittedSubscribers(e))return n;this._stateManager.getChangesetState(n)?.status!=="computing"&&this._stateManager.dispatchServerAction(n,{type:"changeset/statusChanged",status:"computing"});try{let o=await this._computeUncommittedDiffs(e);if(o===void 0)return this._stateManager.dispatchServerAction(n,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:"Failed to compute uncommitted diff from git."}}),n;this._publishChangesetDiffs(e,n,o)}catch(o){this._logService.warn(`[AgentHostChangesetService] Failed to compute uncommitted diffs for ${e}`,o),this._stateManager.dispatchServerAction(n,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:o instanceof Error?o.message:String(o)}})}return n}async _computeUncommittedDiffs(e){let n=this._stateManager.getSessionState(e)?.summary.workingDirectory;if(!n)return;let r;try{r=y.parse(n)}catch{return}return this._gitService.computeSessionFileDiffs(r,{sessionUri:e})}async _computeTurnDiffsPreferCheckpoint(e,n,r){let o=await this._checkpointService.getTurnCheckpointPair(y.parse(e),r);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 b_(e,n,this._diffComputeService,r)}async _resolveWorkingDirectory(e){let n=await e.getMetadata(Sl);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._hasUncommittedSubscribers(e)&&this._scheduleUncommittedRecompute(e),this._scheduleStaticRecompute(e,"branch",n),this._scheduleStaticRecompute(e,"session",n)}onSessionTruncated(e){this._scheduleStaticRecompute(e,"branch"),this._scheduleStaticRecompute(e,"session")}_scheduleDebouncedDiffComputation(e,n){this._debouncedDiffTimers.set(e,$t(()=>{this._debouncedDiffTimers.deleteAndDispose(e),this._scheduleStaticRecompute(e,"branch",n),this._scheduleStaticRecompute(e,"session",n)},Er._DIFF_DEBOUNCE_MS))}_cancelDebouncedDiffComputation(e){this._debouncedDiffTimers.deleteAndDispose(e)}_scheduleDebouncedTurnDiffComputation(e,n){let r=`${e}\0${n}`;this._perTurnDebouncedDiffTimers.set(r,$t(()=>{this._perTurnDebouncedDiffTimers.deleteAndDispose(r),this._scheduleTurnRecompute(e,n)},Er._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(()=>{}))}_scheduleUncommittedRecompute(e){this._diffComputationSequencer.queue(`${e}\0uncommitted`,()=>this.computeUncommittedChangeset(e).then(()=>{}))}_scheduleStaticRecompute(e,n,r,o){this._diffComputationSequencer.queue(`${e}\0${n}`,()=>this._doComputeStaticChangeset(e,n,r,o))}_markStaticChangesetComputing(e,n){let r=Xc(e,n);this._stateManager.registerChangeset(r);let o=this._stateManager.getChangesetState(r)?.status;return o!=="computing"&&this._stateManager.dispatchServerAction(r,{type:"changeset/statusChanged",status:"computing"}),o}async _doComputeStaticChangeset(e,n,r,o){let s=Xc(e,n);this._activeStaticComputes.add(s);let a=o??this._stateManager.getChangesetState(s)?.status,l;try{l=this._sessionDataService.openDatabase(y.parse(e))}catch(d){this._logService.warn(`[AgentHostChangesetService] Failed to open session database for ${n} diff computation: ${e}`,d),this._restoreStaticChangesetStatus(s,a),this._activeStaticComputes.delete(s),this._stateManager.onChangesetLivenessChanged();return}this._stateManager.registerChangeset(s);try{let d=await this._tryComputeGitDiffs(e,l.object,n);if(!d){if(n==="branch"){this._logService.debug(`[AgentHostChangesetService] Branch git diff unavailable for ${e}; preserving cached changeset. previousStatus=${a??"unknown"} cachedFiles=${this._stateManager.getChangesetState(s)?.files.length??0}`),this._restoreStaticChangesetStatus(s,a);return}let c;if(r){let u=this._readPreviousChangesetDiffs(s);u&&(c={changedTurnId:r,previousDiffs:[...u]})}d=await S_(e,l.object,this._diffComputeService,c)}if(this._publishChangesetDiffs(e,s,d),this._persistSessionFlag(e,BP(n),JSON.stringify(d)),n==="session"){this._persistSessionFlag(e,Il,JSON.stringify(d));let c=Vm(d)??{additions:0,deletions:0,files:0};this.persistChangesSummary(e,c),this._stateManager.setSessionSummaryChanges(e,c)}}catch(d){this._logService.warn(`[AgentHostChangesetService] Failed to compute ${n} diffs`,d),this._stateManager.dispatchServerAction(s,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:d instanceof Error?d.message:String(d)}})}finally{this._activeStaticComputes.delete(s),this._stateManager.onChangesetLivenessChanged(),l.dispose()}}_restoreStaticChangesetStatus(e,n){!n||n==="computing"||this._stateManager.dispatchServerAction(e,{type:"changeset/statusChanged",status:n})}_readPreviousChangesetDiffs(e){let n=this._stateManager.getChangesetState(e);if(!(!n||n.files.length===0))return n.files.map(r=>r.edit)}_publishChangesetDiffs(e,n,r){let o=this._stateManager.getChangesetState(n),s=new Set(o?.files.map(d=>d.id)??[]),a=new Map;for(let d of r){let c=d.after?.uri??d.before?.uri;if(!c)continue;a.set(c,d);let u={id:c,edit:d};this._stateManager.dispatchServerAction(n,{type:"changeset/fileSet",file:u})}for(let d of s)a.has(d)||this._stateManager.dispatchServerAction(n,{type:"changeset/fileRemoved",fileId:d});this._stateManager.getChangesetState(n)?.status!=="ready"&&this._stateManager.dispatchServerAction(n,{type:"changeset/statusChanged",status:"ready"})}async _tryComputeGitDiffs(e,n,r){let o=this._stateManager.getSessionState(e)?.summary.workingDirectory;if(!o)return;let s;try{s=y.parse(o)}catch{return}if(r==="session"){let c=this._stateManager.getSessionState(e)?.turns.at(-1)?.id;if(!c)return;let u=y.parse(e),[p,m]=await Promise.all([this._checkpointService.getBaselineCheckpointRef(u),this._checkpointService.getTurnCheckpointPair(u,c)]);if(!p||!m)return;try{return await this._gitService.computeFileDiffsBetweenRefs(s,{sessionUri:e,fromRef:p,toRef:m.current})}catch(h){this._logService.warn(`[AgentHostChangesetService] git-driven ${r} diff computation failed; falling back to edit-tracker`,h);return}}let a=await n.getMetadata(Qc),l=hn(this._stateManager.getSessionState(e)?._meta)?.baseBranchName,d=a??l;!a&&l&&this._logService.debug(`[AgentHostChangesetService] Using _meta.git base branch fallback for Branch Changes in ${e}: ${l}`);try{return await this._gitService.computeSessionFileDiffs(s,{sessionUri:e,baseBranch:d})}catch(c){this._logService.warn(`[AgentHostChangesetService] git-driven ${r} diff computation failed; falling back to edit-tracker`,c);return}}_persistSessionFlag(e,n,r){let o=this._sessionDataService.openDatabase(y.parse(e));o.object.setMetadata(n,r).catch(s=>{this._logService.warn(`[AgentHostChangesetService] Failed to persist ${n}`,s)}).finally(()=>{o.dispose()})}};Er=x([C(1,O),C(2,ft),C(3,tt),C(4,Wn)],Er);var eu=$("agentHostCompletions");var cs=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 r of n.triggerCharacters)e.add(r);return[...e]}registerProvider(e){return this._providers.add(e),k(()=>this._providers.delete(e))}async completions(e,n=Ee.None){let r=[...this._providers].filter(a=>a.kinds.has(e.kind));if(r.length===0)return{items:[]};let o=await Promise.allSettled(r.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}}};cs=x([C(0,O)],cs);function tu(i,t){if(i.length===0||i.charCodeAt(0)!==47)return;let e=1;for(;e<i.length&&!zm(i.charCodeAt(e));)e++;if(t<0||t>e)return;let n=i.slice(0,e);return{token:n,typed:n.slice(1),rangeStart:0,rangeEnd:e}}function C_(i,t){if(i.length===0||t<0||t>i.length)return;let e=t;for(;e>0&&!zm(i.charCodeAt(e-1));)e--;if(e>=i.length||i.charCodeAt(e)!==47)return;let n=e+1;for(;n<i.length&&!zm(i.charCodeAt(n));)n++;if(t>n)return;let r=i.slice(e,n);return{token:r,typed:r.slice(1),rangeStart:e,rangeEnd:n}}function zm(i){return i===32||i===9||i===10||i===13}var nu="rename";function T_(i){let t=/^\/rename(?:$|\s+([\s\S]*))/.exec(i);if(t)return(t[1]??"").trim()}var ru=class{constructor(t){this._hasHistory=t;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(t,e){let n=tu(t.text,t.offset);if(!n)return[];if(!this._hasHistory(t.channel))return[];let r=n.typed;return r.length>0&&!nu.startsWith(r)?[]:[{insertText:"/"+nu+" ",rangeStart:n.rangeStart,rangeEnd:n.rangeEnd,attachment:{type:"simple",label:"/"+nu,_meta:{command:nu,description:g(1936,null)}}}]}};import{homedir as uA}from"os";var us="**",x_="/",iu="[/\\\\]",ou="[^/\\\\]",VP=/\//g;function w_(i,t){switch(i){case 0:return"";case 1:return`${ou}*?`;default:return`(?:${iu}|${ou}+${iu}${t?`|${iu}${ou}+`:""})*?`}}function R_(i,t){if(!i)return[];let e=[],n=!1,r=!1,o="";for(let s of i){switch(s){case t:if(!n&&!r){e.push(o),o="";continue}break;case"{":n=!0;break;case"}":n=!1;break;case"[":r=!0;break;case"]":r=!1;break}o+=s}return o&&e.push(o),e}function D_(i){if(!i)return"";let t="",e=R_(i,x_);if(e.every(n=>n===us))t=".*";else{let n=!1;e.forEach((r,o)=>{if(r===us){if(n)return;t+=w_(2,o===e.length-1)}else{let s=!1,a="",l=!1,d="";for(let c of r){if(c!=="}"&&s){a+=c;continue}if(l&&(c!=="]"||!d)){let u;c==="-"?u=c:(c==="^"||c==="!")&&!d?u="^":c===x_?u="":u=Zt(c),d+=u;continue}switch(c){case"{":s=!0;continue;case"[":l=!0;continue;case"}":{let p=`(?:${R_(a,",").map(m=>D_(m)).join("|")})`;t+=p,s=!1,a="";break}case"]":{t+="["+d+"]",l=!1,d="";break}case"?":t+=ou;continue;case"*":t+=w_(1);continue;default:t+=Zt(c)}}o<e.length-1&&(e[o+1]!==us||o+2<e.length)&&(t+=iu)}n=r===us})}return t}var zP=/^\*\*\/\*\.[\w\.-]+$/,jP=/^\*\*\/([\w\.-]+)\/?$/,KP=/^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/,GP=/^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/,JP=/^\*\*((\/[\w\.-]+)+)\/?$/,YP=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,E_=new On(1e4),P_=function(){return!1},$n=function(){return null};function Jm(i,t){if(!i)return $n;let e;typeof i!="string"?e=i.pattern:e=i,e=e.trim();let n=t.ignoreCase??!1,r={...t,equals:n?dr:(l,d)=>l===d,endsWith:n?oS:(l,d)=>l.endsWith(d),isEqualOrParent:(l,d)=>cr(l,d,t.ignoreCase??!Se)},o=`${n?e.toLowerCase():e}_${!!t.trimForExclusions}_${n}`,s=E_.get(o);if(s)return A_(s,i,r);let a;return zP.test(e)?s=QP(e.substring(4),e,r):(a=jP.exec(Gm(e,r)))?s=XP(a[1],e,r):(t.trimForExclusions?GP:KP).test(e)?s=ZP(e,r):(a=JP.exec(Gm(e,r)))?s=k_(a[1].substring(1),e,!0,r):(a=YP.exec(Gm(e,r)))?s=k_(a[1],e,!1,r):s=eA(e,r),E_.set(o,s),A_(s,i,r)}function A_(i,t,e){if(typeof t=="string")return i;let n=function(r,o){return e.isEqualOrParent(r,t.base)?i(fg(r.substring(t.base.length),be),o):null};return n.allBasenames=i.allBasenames,n.allPaths=i.allPaths,n.basenames=i.basenames,n.patterns=i.patterns,n}function Gm(i,t){return t.trimForExclusions&&i.endsWith("/**")?i.substring(0,i.length-2):i}function QP(i,t,e){return function(n,r){return typeof n=="string"&&e.endsWith(n,i)?t:null}}function XP(i,t,e){let n=`/${i}`,r=`\\${i}`,o=function(a,l){return typeof a!="string"?null:l?e.equals(l,i)?t:null:e.equals(a,i)||e.endsWith(a,n)||e.endsWith(a,r)?t:null},s=[i];return o.basenames=s,o.patterns=[t],o.allBasenames=s,o}function ZP(i,t){let e=M_(i.slice(1,-1).split(",").map(a=>Jm(a,t)).filter(a=>a!==$n),i),n=e.length;if(!n)return $n;if(n===1)return e[0];let r=function(a,l){for(let d=0,c=e.length;d<c;d++)if(e[d](a,l))return i;return null},o=e.find(a=>!!a.allBasenames);o&&(r.allBasenames=o.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(r.allPaths=s),r}function k_(i,t,e,n){let r=be===Z.sep,o=r?i:i.replace(VP,be),s=be+o,a=Z.sep+i,l;return e?l=function(d,c){return typeof d=="string"&&(n.equals(d,o)||n.endsWith(d,s)||!r&&(n.equals(d,i)||n.endsWith(d,a)))?t:null}:l=function(d,c){return typeof d=="string"&&(n.equals(d,o)||!r&&n.equals(d,i))?t:null},l.allPaths=[(e?"*/":"./")+i],l}function eA(i,t){try{let e=new RegExp(`^${D_(i)}$`,t.ignoreCase?"i":void 0);return function(n){return e.lastIndex=0,typeof n=="string"&&e.test(n)?i:null}}catch{return $n}}function O_(i,t,e){return!i||typeof t!="string"?!1:_l(i,e)(t)}function _l(i,t={}){if(!i)return P_;if(typeof i=="string"||tA(i)){let e=Jm(i,t);if(e===$n)return P_;let n=function(r,o){return!!e(r,o)};return e.allBasenames&&(n.allBasenames=e.allBasenames),e.allPaths&&(n.allPaths=e.allPaths),n}return nA(i,t)}function tA(i){let t=i;return t?typeof t.base=="string"&&typeof t.pattern=="string":!1}function nA(i,t){let e=M_(Object.getOwnPropertyNames(i).map(a=>rA(a,i[a],t)).filter(a=>a!==$n)),n=e.length;if(!n)return $n;if(!e.some(a=>!!a.requiresSiblings)){if(n===1)return e[0];let a=function(c,u){let p;for(let m=0,h=e.length;m<h;m++){let v=e[m](c,u);if(typeof v=="string")return v;Md(v)&&(p||(p=[]),p.push(v))}return p?(async()=>{for(let m of p){let h=await m;if(typeof h=="string")return h}return null})():null},l=e.find(c=>!!c.allBasenames);l&&(a.allBasenames=l.allBasenames);let d=e.reduce((c,u)=>u.allPaths?c.concat(u.allPaths):c,[]);return d.length&&(a.allPaths=d),a}let r=function(a,l,d){let c,u;for(let p=0,m=e.length;p<m;p++){let h=e[p];h.requiresSiblings&&d&&(l||(l=Ce(a)),c||(c=l.substring(0,l.length-xd(a).length)));let v=h(a,l,c,d);if(typeof v=="string")return v;Md(v)&&(u||(u=[]),u.push(v))}return u?(async()=>{for(let p of u){let m=await p;if(typeof m=="string")return m}return null})():null},o=e.find(a=>!!a.allBasenames);o&&(r.allBasenames=o.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(r.allPaths=s),r}function rA(i,t,e){if(t===!1)return $n;let n=Jm(i,e);if(n===$n)return $n;if(typeof t=="boolean")return n;if(t){let r=t.when;if(typeof r=="string"){let o=(s,a,l,d)=>{if(!d||!n(s,a))return null;let c=r.replace("$(basename)",()=>l),u=d(c);return Md(u)?u.then(p=>p?i:null):u?i:null};return o.requiresSiblings=!0,o}}return n}function M_(i,t){let e=i.filter(a=>!!a.basenames);if(e.length<2)return i;let n=e.reduce((a,l)=>{let d=l.basenames;return d?a.concat(d):a},[]),r;if(t){r=[];for(let a=0,l=n.length;a<l;a++)r.push(t)}else r=e.reduce((a,l)=>{let d=l.patterns;return d?a.concat(d):a},[]);let o=function(a,l){if(typeof a!="string")return null;if(!l){let c;for(c=a.length;c>0;c--){let u=a.charCodeAt(c-1);if(u===47||u===92)break}l=a.substring(c)}let d=n.indexOf(l);return d!==-1?r[d]:null};o.basenames=n,o.patterns=r,o.allBasenames=n;let s=i.filter(a=>!a.basenames);return s.push(o),s}function Ym(i,t){return Xt(i,t,(e,n)=>typeof e=="string"&&typeof n=="string"?e===n:typeof e!="string"&&typeof n!="string"?e.base===n.base&&e.pattern===n.pattern:!1)}function su(i,t){return i.replace(/^~($|\/|\\)/,`${t}$1`)}import*as L_ from"fs";var iA=new Set(["/dev/null","/dev/stdout","/dev/stderr","/dev/tty"]);function oA(i){let t=i.trim();return t.length===0?!1:((t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),/^&[0-9]+-?$/.test(t)?!0:iA.has(t))}function sA(i){if(!i.includes(">"))return{kind:"read"};let t=i.match(/(?:[0-9]+|&)?>>?\|?\s*(.+)$/);if(!t)return{kind:"unsafeWrite",dest:void 0};let e=t[1].trim();if(oA(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 Qm=/(?!.*)/,aA=/^[A-Z_][A-Z0-9_]*=/i,au=class extends T{constructor(e){super();this._logService=e;this._initPromise=this._initTreeSitter()}initialize(){return this._initPromise}shouldAutoApprove(e,n){let r=e.trimStart();if(r.length===0)return"approved";this._ensureRules();let o=this._extractSubCommands(r);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 r of e){if(aA.test(r))return"denied";let o=this._matchSingleCommand(r);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 r=new this._queryClass(this._bashLanguage,"(command) @command (file_redirect) @file_redirect (heredoc_redirect) @heredoc_redirect (herestring_redirect) @herestring_redirect"),o=r.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 d=sA(l.node.text);d.kind==="unsafeWrite"&&a.push(d.dest)}else l.name==="heredoc_redirect"||l.name;return r.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(dt.asFileUri(""),"..","node_modules","@vscode","tree-sitter-wasm","wasm"),r=y.joinPath(n,"tree-sitter.wasm").fsPath;if(await e.Parser.init({locateFile(){return r}}),this._store.isDisposed)return;let o=new e.Parser;this._register(k(()=>{try{o.delete()}catch{}}));let s=y.joinPath(n,"tree-sitter-bash.wasm").fsPath,a=await L_.promises.readFile(s);if(this._store.isDisposed)return;let l=await e.Language.load(new Uint8Array(a.buffer,a.byteOffset,a.byteLength));if(this._store.isDisposed)return;this._parser=o,this._bashLanguage=l,this._queryClass=e.Query,this._logService.info("[CommandAutoApprover] Tree-sitter initialized successfully")}catch(e){this._logService.warn("[CommandAutoApprover] Failed to initialize tree-sitter",e)}}_ensureRules(){if(this._allowRules&&this._denyRules)return;let e=[],n=[];for(let[r,o]of Object.entries(dA)){let s=lA(r);o===!0?e.push({regex:s}):o===!1&&n.push({regex:s})}this._allowRules=e,this._denyRules=n}};function lA(i){let t=i.match(/^\/(?<pattern>.+)\/(?<flags>[dgimsuvy]*)$/),e=t?.groups?.pattern;if(e){let r=t.groups?.flags;if(r&&(r=r.replaceAll("g","")),e===".*")return new RegExp(e);try{let o=new RegExp(e,r||void 0);return rS(o)?Qm:o}catch{return Qm}}if(i==="")return Qm;let n;if(i.includes("/")||i.includes("\\")){let r=i.replace(/[/\\]/g,"%%PATH_SEP%%");r=Zt(r),r=r.replace(/%%PATH_SEP%%*/g,"[/\\\\]"),n=`^(?:\\.[/\\\\])?${r}`}else n=Zt(i);return new RegExp(`^${n}\\b`)}var dA={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 N_="allow-session",pA=[{id:N_,label:g(2219,null),kind:"approve",group:1},{id:"allow-once",label:g(2218,null),kind:"approve"},{id:"skip",label:g(2220,null),kind:"deny",group:2}],fA={"**/*":!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},ps=class extends T{constructor(e,n,r){super();this._stateManager=e;this._configService=n;this._logService=r;this._commandAutoApprover=this._register(new au(this._logService))}initialize(){return this._commandAutoApprover.initialize()}getAutoApproval(e,n){let r=this._configService.getEffectiveWorkingDirectory(n);if(this.isSessionAutoApproveEnabled(n))return"setting";if(this._isToolAllowedByPermissions(n,e.toolCallId))return"setting";if(e.permissionKind==="read"&&e.permissionPath)return this._isPathInWorkingDirectory(e.permissionPath,r)?(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,r)&&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 o=this._commandAutoApprover.shouldAutoApprove(e.toolInput,{isWriteDestApproved:s=>this._isShellWriteDestApproved(s,r)});if(o==="approved")return this._logService.trace("[SessionPermissionManager] Auto-approving shell command"),"not-needed";o==="denied"&&this._logService.trace("[SessionPermissionManager] Shell command denied by rule");return}}isSessionAutoApproveEnabled(e){let n=this._configService.getEffectiveValue(e,It,"autoApprove");return n==="autoApprove"||n==="autopilot"}createToolReadyAction(e,n,r){let o=e.state;return o.confirmationTitle?{type:"session/toolCallReady",turnId:r,toolCallId:o.toolCallId,invocationMessage:o.invocationMessage,toolInput:o.toolInput,confirmationTitle:o.confirmationTitle,edits:o.edits,editable:o.editable,...o._meta?{_meta:o._meta}:{},options:o.options?o.options.slice():pA.slice()}:{type:"session/toolCallReady",turnId:r,toolCallId:o.toolCallId,invocationMessage:o.invocationMessage,toolInput:o.toolInput,confirmed:"not-needed",...o._meta?{_meta:o._meta}:{}}}handleToolCallConfirmed(e,n,r){if(r===N_){let o=this._getToolNameForToolCall(e,n);o&&this._addToolToSessionPermissions(e,o)}}_isPathInWorkingDirectory(e,n){if(!n)return!1;let r=y.parse(n);return Je.isEqualOrParent(en(y.file(e)),r)}_isShellWriteDestApproved(e,n){let r=this._resolveShellRedirectPath(e,n);return r?this._isPathInWorkingDirectory(r,n)&&this._isEditAutoApproved(r):!1}_resolveShellRedirectPath(e,n){let r=su(e.trim(),uA());if(r){if(Wt(r))return r;if(n)return dn(y.parse(n).fsPath,r)}}_isEditAutoApproved(e){let n=!0;for(let[r,o]of Object.entries(fA))o!==n&&O_(r,e)&&(n=o);return n}_isToolAllowedByPermissions(e,n){let r=this._getToolNameForToolCall(e,n);if(!r)return!1;let s=this._configService.getEffectiveValue(e,It,"permissions")?.allow.includes(r)??!1;return s&&this._logService.trace(`[SessionPermissionManager] Auto-approving "${r}" 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 r=this._configService.getEffectiveValue(e,It,"permissions")??{allow:[],deny:[]};r.allow.includes(n)||(this._configService.updateSessionConfig(e,{permissions:{allow:[...r.allow,n],deny:[...r.deny]}}),this._logService.info(`[SessionPermissionManager] Added "${n}" to session permissions for ${e}`))}};ps=x([C(1,$e),C(2,O)],ps);import{CAPIClient as bA,RequestType as Cl}from"@vscode/copilot-api";import{networkInterfaces as yA}from"os";import{networkInterfaces as gA}from"os";var mA=new Set(["00:00:00:00:00:00","ff:ff:ff:ff:ff:ff","ac:de:48:00:11:22"]);function hA(i){let t=i.replace(/\-/g,":").toLowerCase();return!mA.has(t)}function U_(){let i=gA();for(let t in i){let e=i[t];if(e){for(let{mac:n}of e)if(hA(n))return n}}throw new Error("Unable to retrieve mac address (unexpected format)")}var Tj=new class{_isVirtualMachineMacAddress(i){return this._virtualMachineOUIs||(this._virtualMachineOUIs=Fn.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(i)}value(){if(this._value===void 0){let i=0,t=0,e=yA();for(let n in e){let r=e[n];if(r)for(let{mac:o,internal:s}of r)s||(t+=1,this._isVirtualMachineMacAddress(o.toUpperCase())&&(i+=1))}this._value=t>0?i/t:0}return this._value}},Xm;async function lu(i){return Xm||(Xm=(async()=>await vA(i)||N())()),Xm}async function vA(i){try{let t=await import("crypto"),e=U_();return t.createHash("sha256").update(e,"utf8").digest("hex")}catch(t){i(t);return}}var SA="Software\\Microsoft\\SQMClient";async function F_(i){if(G){let t=await import("@vscode/windows-registry");try{return t.GetStringRegKey("HKEY_LOCAL_MACHINE",SA,"MachineId")||""}catch(e){return i(e),""}}return""}async function du(i){try{let e=await(await import("@vscode/deviceid")).getDeviceId();return dS(e)}catch(t){return i(t),N()}}var Tl=520,IA=300,_A=1800,W_="2025-04-01",CA=300,TA="gpt-4o-mini",xA=.1,wA=1,RA="conversation-background",Pn=class extends Error{constructor(e,n,r){super(r??n.error.message);this.status=e;this.envelope=n;this.name="CopilotApiError"}};function cu(i,t,e,n="CAPI request failed"){let r;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"&&(r=o)}}catch{}return r||(r={type:"error",error:{type:"api_error",message:e||`${i} ${t}`},request_id:null}),new Pn(i,r,`${n}: ${i} ${t} \u2014 ${r.error.message}`)}var Kt=$("copilotApiService"),pi=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 r=await n.makeRequest({method:"GET",headers:{...e?.headers,Authorization:`Bearer ${t}`},signal:e?.signal},{type:Cl.Models});if(!r.ok){(r.status===401||r.status===403)&&this._invalidateClientForToken(t);let s=await r.text().catch(()=>"");throw cu(r.status,r.statusText,s,"CAPI models request failed")}return(await r.json()).data??[]}async responses(t,e,n){let r=await this._getClientForToken(t),o=N(),s="<unknown>";try{s=JSON.parse(e).model??"<none>"}catch{}this._logService.info(`[CopilotApiService] POST responses: requestId=${o}, model=${s}`);let a=await r.makeRequest({method:"POST",headers:{...n?.headers,"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-Request-Id":o,"OpenAI-Intent":"conversation"},suppressIntegrationId:n?.suppressIntegrationId,body:e,signal:n?.signal},{type:Cl.ChatResponses});if(this._logService.info(`[CopilotApiService] responses status=${a.status}, requestId=${o}`),!a.ok){(a.status===401||a.status===403)&&this._invalidateClientForToken(t);let l=await a.text().catch(()=>"");throw cu(a.status,a.statusText,l,"CAPI responses request failed")}return a}async utilityChatCompletion(t,e,n){let r=await this._getClientForToken(t),o=await this._getCopilotToken(t),s=await this._resolveUtilityModelId(t,TA),a=N();this._logService.debug("[CopilotApiService] POST chat completions",`model=${s} requestId=${a}`);let l=JSON.stringify({model:s,messages:e.messages.map(p=>({role:p.role,content:p.content})),stream:!1,temperature:e.temperature??xA,top_p:wA}),d=await r.makeRequest({method:"POST",headers:{...n?.headers,"Content-Type":"application/json",Authorization:`Bearer ${o}`,"X-Request-Id":a,"OpenAI-Intent":RA},body:l,signal:n?.signal},{type:Cl.ChatCompletions});if(!d.ok){(d.status===401||d.status===403)&&this._invalidateCopilotTokenForGithub(t);let p=await d.text().catch(()=>"");throw cu(d.status,d.statusText,p,"CAPI chat completion request failed")}let u=(await d.json())?.choices?.[0]?.message?.content;if(typeof u!="string")throw new Error("CAPI chat completion returned no text content");return u}_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([lu(o=>this._logService.warn("[CopilotApiService] getMachineId failed",o)),du(o=>this._logService.warn("[CopilotApiService] getDevDeviceId failed",o))]);return{extensionInfo:{name:"agent-host",sessionId:N(),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 r=await this._sendRequest(t,e,!0,n);if(!r.body)throw new Error("CAPI response has no body");yield*this._readSSE(r.body)}async _messagesNonStreaming(t,e,n){return(await this._sendRequest(t,e,!1,n)).json()}async _sendRequest(t,e,n,r){let o=await this._getClientForToken(t),s=N();this._logService.debug("[CopilotApiService] POST messages",`model=${e.model} stream=${n} requestId=${s}`);let{system:a,...l}=e,d=JSON.stringify({...l,stream:n,...a!==void 0?{system:typeof a=="string"?[{type:"text",text:a}]:a}:{}}),c=await o.makeRequest({method:"POST",headers:{...r?.headers,"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-Request-Id":s,"X-GitHub-Api-Version":"2026-01-09","OpenAI-Intent":"messages-proxy","X-Interaction-Type":"messages-proxy"},suppressIntegrationId:r?.suppressIntegrationId,body:d,signal:r?.signal},{type:Cl.ChatMessages});if(!c.ok){(c.status===401||c.status===403)&&this._invalidateClientForToken(t);let u=await c.text().catch(()=>"");throw cu(c.status,c.statusText,u)}return c}_getClientForToken(t){let e=Date.now()/1e3,n=this._clientsByToken.get(t);if(n)return n.then(o=>o.expiresAt-e>IA?o.capiClient:(this._clientsByToken.delete(t),this._getClientForToken(t))).catch(o=>{throw this._clientsByToken.delete(t),o});let r=this._buildClientForToken(t).catch(o=>{throw this._clientsByToken.delete(t),o});return this._clientsByToken.set(t,r),r.then(o=>o.capiClient)}_invalidateClientForToken(t){this._clientsByToken.delete(t)}async _buildClientForToken(t){let{extensionInfo:e,userUrl:n}=await this._getCapiBase(),r=this._fetch,o=new bA(e,void 0,{fetch:(l,d)=>r(l,{method:d.method??"GET",headers:d.headers,body:d.body,signal:d.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":W_}});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+_A}}_getCopilotToken(t){let e=Date.now()/1e3,n=this._copilotTokensByGithub.get(t);if(n)return n.then(o=>o.expiresAt-e>CA?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 r=this._buildCopilotToken(t).catch(o=>{throw this._copilotTokensByGithub.get(t)===r&&this._copilotTokensByGithub.delete(t),o});return this._copilotTokensByGithub.set(t,r),r.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":W_}},{type:Cl.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 r=await n.json();if(typeof r.token!="string"||typeof r.expires_at!="number")throw new Error("Copilot session token mint returned malformed envelope");let o=Date.now()/1e3,s=typeof r.refresh_in=="number"?r.refresh_in:void 0,a=Math.max(s!==void 0?o+s:r.expires_at,o+60);return{token:r.token,expiresAt:a,modelIdsByFamily:new Map}}async _resolveUtilityModelId(t,e){let n=this._copilotTokensByGithub.get(t),r=n?await n:void 0,o=r?.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 r?.modelIdsByFamily.set(e,a.id),a.id}async*_readSSE(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0});let a=r.split(`
`);r=a.pop()??"";for(let l of a){let d=this._parseDataLine(l);if(d!==void 0&&(yield d,d.type==="message_stop"))return}}if(r.trim()){let o=this._parseDataLine(r);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 Pn(Tl,a)}if(EA.has(o))return n}}};pi=x([C(1,O),C(2,gt)],pi);var EA=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);var uu="VSCODE_PROXY_ERROR:",PA=8*1024,AA=/^[A-Za-z0-9+/]+={0,2}$/;function $_(i){switch(i){case 402:return"quotaExceeded";case 429:return"rateLimited";case 499:return"canceled";case 400:return"badRequest";case 401:case 403:return"agent_unauthorized";case 404:return"notFound";default:return"failed"}}function pu(i){let t=i.status===Tl?502:i.status,e=typeof i.envelope.request_id=="string"?i.envelope.request_id:"",n=kA(i.envelope.error.message)??{code:i.envelope.error.type,message:i.envelope.error.message};return{fetchError:{type:$_(t),reason:n.message??i.envelope.error.message,requestId:e,capiError:n}}}function kA(i){let t;try{t=JSON.parse(i)}catch{return}if(!t||typeof t!="object")return;let e=t.error;if(!e||typeof e!="object")return;let n=e.code,r=e.message;if(!(typeof n!="string"&&typeof r!="string"))return{code:typeof n=="string"?n:void 0,message:typeof r=="string"?r:void 0}}function fu(i){return`${uu}${Buffer.from(JSON.stringify(i)).toString("base64")}`}function DA(i,t){switch(i){case"quota":return"quotaExceeded";case"rate_limit":return"rateLimited";case"context_limit":return"length";case"authentication":case"authorization":return"agent_unauthorized"}return t!==void 0?$_(t):void 0}function OA(i){let t=DA(i.errorType,i.statusCode);if(!t)return;let e=i.errorCode??(t==="quotaExceeded"?"quota_exceeded":void 0),n=e||i.message?{code:e,message:i.message}:void 0;return{fetchError:{type:t,reason:i.message,requestId:i.providerCallId??"",serverRequestId:i.serviceRequestId,...n&&{capiError:n}}}}function gu(i){if(!i)return;let t=i.indexOf(uu);if(t===-1)return;let e=t+uu.length,n=i.slice(e).search(/[\s"']/),r=n===-1?i.slice(e):i.slice(e,e+n);if(!(r.length===0||r.length>PA||!AA.test(r)))try{let o=JSON.parse(Buffer.from(r,"base64").toString());return o&&typeof o=="object"&&o.fetchError&&typeof o.fetchError.type=="string"?o:void 0}catch{return}}function xl(i){let t=i.indexOf(uu);return t===-1?i:i.slice(0,t).trim()||i.slice(0,t)}function wl(i){return{chatError:i}}function H_(i){let t=gu(i);return t?wl(t):void 0}function q_(i){let t=OA(i);return t?wl(t):void 0}function fs(i){let t=gu(i);return t?{message:xl(i),_meta:wl(t)}:{message:i}}import{hostname as nk,release as rk}from"os";var hu;(t=>t.DEFAULT={allowTrailingComma:!0})(hu||={});function eh(i,t=!1){let e=0,n=i.length,r="",o=0,s=16,a=0;function l(v){let I=0,b=0;for(;I<v;){let S=i.charCodeAt(e);if(S>=48&&S<=57)b=b*16+S-48;else if(S>=65&&S<=70)b=b*16+S-65+10;else if(S>=97&&S<=102)b=b*16+S-97+10;else break;e++,I++}return I<v&&(b=-1),b}function d(v){e=v,r="",o=0,s=16,a=0}function c(){let v=e;if(i.charCodeAt(e)===48)e++;else for(e++;e<i.length&&gs(i.charCodeAt(e));)e++;if(e<i.length&&i.charCodeAt(e)===46)if(e++,e<i.length&&gs(i.charCodeAt(e)))for(e++;e<i.length&&gs(i.charCodeAt(e));)e++;else return a=3,i.substring(v,e);let I=e;if(e<i.length&&(i.charCodeAt(e)===69||i.charCodeAt(e)===101))if(e++,(e<i.length&&i.charCodeAt(e)===43||i.charCodeAt(e)===45)&&e++,e<i.length&&gs(i.charCodeAt(e))){for(e++;e<i.length&&gs(i.charCodeAt(e));)e++;I=e}else a=3;return i.substring(v,I)}function u(){let v="",I=e;for(;;){if(e>=n){v+=i.substring(I,e),a=2;break}let b=i.charCodeAt(e);if(b===34){v+=i.substring(I,e),e++;break}if(b===92){if(v+=i.substring(I,e),e++,e>=n){a=2;break}switch(i.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 _=l(4);_>=0?v+=String.fromCharCode(_):a=4;break}default:a=5}I=e;continue}if(b>=0&&b<=31)if(mu(b)){v+=i.substring(I,e),a=2;break}else a=6;e++}return v}function p(){if(r="",a=0,o=e,e>=n)return o=n,s=17;let v=i.charCodeAt(e);if(Zm(v)){do e++,r+=String.fromCharCode(v),v=i.charCodeAt(e);while(Zm(v));return s=15}if(mu(v))return e++,r+=String.fromCharCode(v),v===13&&i.charCodeAt(e)===10&&(e++,r+=`
`),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++,r=u(),s=10;case 47:{let I=e-1;if(i.charCodeAt(e+1)===47){for(e+=2;e<n&&!mu(i.charCodeAt(e));)e++;return r=i.substring(I,e),s=12}if(i.charCodeAt(e+1)===42){e+=2;let b=n-1,S=!1;for(;e<b;){if(i.charCodeAt(e)===42&&i.charCodeAt(e+1)===47){e+=2,S=!0;break}e++}return S||(e++,a=1),r=i.substring(I,e),s=13}return r+=String.fromCharCode(v),e++,s=16}case 45:if(r+=String.fromCharCode(v),e++,e===n||!gs(i.charCodeAt(e)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=c(),s=11;default:for(;e<n&&m(v);)e++,v=i.charCodeAt(e);if(o!==e){switch(r=i.substring(o,e),r){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return r+=String.fromCharCode(v),e++,s=16}}function m(v){if(Zm(v)||mu(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=p();while(v>=12&&v<=15);return v}return{setPosition:d,getPosition:()=>e,scan:t?h:p,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>o,getTokenLength:()=>e-o,getTokenError:()=>a}}function Zm(i){return i===32||i===9||i===11||i===12||i===160||i===5760||i>=8192&&i<=8203||i===8239||i===8287||i===12288||i===65279}function mu(i){return i===10||i===13||i===8232||i===8233}function gs(i){return i>=48&&i<=57}function yu(i,t=[],e=hu.DEFAULT){let n=null,r=[],o=[];function s(l){Array.isArray(r)?r.push(l):n!==null&&(r[n]=l)}return ms(i,{onObjectBegin:()=>{let l={};s(l),o.push(r),r=l,n=null},onObjectProperty:l=>{n=l},onObjectEnd:()=>{r=o.pop()},onArrayBegin:()=>{let l=[];s(l),o.push(r),r=l,n=null},onArrayEnd:()=>{r=o.pop()},onLiteralValue:s,onError:(l,d,c)=>{t.push({error:l,offset:d,length:c})}},e),r[0]}function B_(i,t=[],e=hu.DEFAULT){let n={type:"array",offset:-1,length:-1,children:[],parent:void 0};function r(l){n.type==="property"&&(n.length=l-n.offset,n=n.parent)}function o(l){return n.children.push(l),l}ms(i,{onObjectBegin:l=>{n=o({type:"object",offset:l,length:-1,parent:n,children:[]})},onObjectProperty:(l,d,c)=>{n=o({type:"property",offset:d,length:-1,parent:n,children:[]}),n.children.push({type:"string",value:l,offset:d,length:c,parent:n})},onObjectEnd:(l,d)=>{n.length=l+d-n.offset,n=n.parent,r(l+d)},onArrayBegin:(l,d)=>{n=o({type:"array",offset:l,length:-1,parent:n,children:[]})},onArrayEnd:(l,d)=>{n.length=l+d-n.offset,n=n.parent,r(l+d)},onLiteralValue:(l,d,c)=>{o({type:MA(l),offset:d,length:c,parent:n,value:l}),r(d+c)},onSeparator:(l,d,c)=>{n.type==="property"&&(l===":"?n.colonOffset=d:l===","&&r(d))},onError:(l,d,c)=>{t.push({error:l,offset:d,length:c})}},e);let a=n.children[0];return a&&delete a.parent,a}function th(i,t){if(!i)return;let e=i;for(let n of t)if(typeof n=="string"){if(e.type!=="object"||!Array.isArray(e.children))return;let r=!1;for(let o of e.children)if(Array.isArray(o.children)&&o.children[0].value===n){e=o.children[1],r=!0;break}if(!r)return}else{let r=n;if(e.type!=="array"||r<0||!Array.isArray(e.children)||r>=e.children.length)return;e=e.children[r]}return e}function ms(i,t,e=hu.DEFAULT){let n=eh(i,!1);function r(U){return U?()=>U(n.getTokenOffset(),n.getTokenLength()):()=>!0}function o(U){return U?J=>U(J,n.getTokenOffset(),n.getTokenLength()):()=>!0}let s=r(t.onObjectBegin),a=o(t.onObjectProperty),l=r(t.onObjectEnd),d=r(t.onArrayBegin),c=r(t.onArrayEnd),u=o(t.onLiteralValue),p=o(t.onSeparator),m=r(t.onComment),h=o(t.onError),v=e&&e.disallowComments,I=e&&e.allowTrailingComma;function b(){for(;;){let U=n.scan();switch(n.getTokenError()){case 4:S(14);break;case 5:S(15);break;case 3:S(13);break;case 1:v||S(11);break;case 2:S(12);break;case 6:S(16);break}switch(U){case 12:case 13:v?S(10):m();break;case 16:S(1);break;case 15:case 14:break;default:return U}}}function S(U,J=[],ne=[]){if(h(U),J.length+ne.length>0){let xe=n.getToken();for(;xe!==17;){if(J.indexOf(xe)!==-1){b();break}else if(ne.indexOf(xe)!==-1)break;xe=b()}}}function _(U){let J=n.getTokenValue();return U?u(J):a(J),b(),!0}function R(){switch(n.getToken()){case 11:{let U=0;try{U=JSON.parse(n.getTokenValue()),typeof U!="number"&&(S(2),U=0)}catch{S(2)}u(U);break}case 7:u(null);break;case 8:u(!0);break;case 9:u(!1);break;default:return!1}return b(),!0}function P(){return n.getToken()!==10?(S(3,[],[2,5]),!1):(_(!1),n.getToken()===6?(p(":"),b(),L()||S(4,[],[2,5])):S(5,[],[2,5]),!0)}function q(){s(),b();let U=!1;for(;n.getToken()!==2&&n.getToken()!==17;){if(n.getToken()===5){if(U||S(4,[],[]),p(","),b(),n.getToken()===2&&I)break}else U&&S(6,[],[]);P()||S(4,[],[2,5]),U=!0}return l(),n.getToken()!==2?S(7,[2],[]):b(),!0}function E(){d(),b();let U=!1;for(;n.getToken()!==4&&n.getToken()!==17;){if(n.getToken()===5){if(U||S(4,[],[]),p(","),b(),n.getToken()===4&&I)break}else U&&S(6,[],[]);L()||S(4,[],[4,5]),U=!0}return c(),n.getToken()!==4?S(8,[4],[]):b(),!0}function L(){switch(n.getToken()){case 3:return E();case 1:return q();case 10:return _(!0);default:return R()}}return b(),n.getToken()===17?e.allowEmptyContent?!0:(S(4,[],[]),!1):L()?(n.getToken()!==17&&S(9,[],[]),!0):(S(4,[],[]),!1)}function MA(i){switch(typeof i){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(i){if(Array.isArray(i))return"array"}else return"null";return"object"}default:return"null"}}function z_(i,t,e){let n,r,o,s,a;if(t){for(s=t.offset,a=s+t.length,o=s;o>0&&!Rl(i,o-1);)o--;let _=a;for(;_<i.length&&!Rl(i,_);)_++;r=i.substring(o,_),n=LA(r,e)}else r=i,n=0,o=0,s=0,a=i.length;let l=NA(e,i),d=!1,c=0,u;e.insertSpaces?u=nh(" ",e.tabSize||4):u="	";let p=eh(r,!1),m=!1;function h(){return l+nh(u,n+c)}function v(){let _=p.scan();for(d=!1;_===15||_===14;)d=d||_===14,_=p.scan();return m=_===16||p.getTokenError()!==0,_}let I=[];function b(_,R,P){!m&&R<a&&P>s&&i.substring(R,P)!==_&&I.push({offset:R,length:P-R,content:_})}let S=v();if(S!==17){let _=p.getTokenOffset()+o,R=nh(u,n);b(R,o,_)}for(;S!==17;){let _=p.getTokenOffset()+p.getTokenLength()+o,R=v(),P="";for(;!d&&(R===12||R===13);){let E=p.getTokenOffset()+o;b(" ",_,E),_=p.getTokenOffset()+p.getTokenLength()+o,P=R===12?h():"",R=v()}if(R===2)S!==1&&(c--,P=h());else if(R===4)S!==3&&(c--,P=h());else{switch(S){case 3:case 1:c++,P=h();break;case 5:case 12:P=h();break;case 13:d?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}d&&(R===12||R===13)&&(P=h())}let q=p.getTokenOffset()+o;b(P,_,q),S=R}return I}function nh(i,t){let e="";for(let n=0;n<t;n++)e+=i;return e}function LA(i,t){let e=0,n=0,r=t.tabSize||4;for(;e<i.length;){let o=i.charAt(e);if(o===" ")n++;else if(o==="	")n+=r;else break;e++}return Math.floor(n/r)}function NA(i,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 i&&i.eol||`
`}function Rl(i,t){return`\r
`.indexOf(i.charAt(t))!==-1}function j_(i,t,e,n,r){let o=t.slice(),a=B_(i,[]),l,d;for(;o.length>0&&(d=o.pop(),l=th(a,o),l===void 0&&e!==void 0);)typeof d=="string"?e={[d]:e}:e=[e];if(l)if(l.type==="object"&&typeof d=="string"&&Array.isArray(l.children)){let c=th(l,[d]);if(c!==void 0)if(e===void 0){if(!c.parent)throw new Error("Malformed AST");let u=l.children.indexOf(c.parent),p,m=c.parent.offset+c.parent.length;if(u>0){let h=l.children[u-1];p=h.offset+h.length}else p=l.offset+1,l.children.length>1&&(m=l.children[1].offset);return hs(i,{offset:p,length:m-p,content:""},n)}else return hs(i,{offset:c.offset,length:c.length,content:JSON.stringify(e)},n);else{if(e===void 0)return[];let u=`${JSON.stringify(d)}: ${JSON.stringify(e)}`,p=r?r(l.children.map(h=>h.children[0].value)):l.children.length,m;if(p>0){let h=l.children[p-1];m={offset:h.offset+h.length,length:0,content:","+u}}else l.children.length===0?m={offset:l.offset+1,length:0,content:u}:m={offset:l.offset+1,length:0,content:u+","};return hs(i,m,n)}}else if(l.type==="array"&&typeof d=="number"&&Array.isArray(l.children))if(e!==void 0){let c=`${JSON.stringify(e)}`,u;if(l.children.length===0||d===0)u={offset:l.offset+1,length:0,content:l.children.length===0?c:c+","};else{let p=d===-1||d>l.children.length?l.children.length:d,m=l.children[p-1];u={offset:m.offset+m.length,length:0,content:","+c}}return hs(i,u,n)}else{let c=d,u=l.children[c],p;if(l.children.length===1)p={offset:l.offset+1,length:l.length-2,content:""};else if(l.children.length-1===c){let m=l.children[c-1],h=m.offset+m.length,v=l.offset+l.length;p={offset:h,length:v-2-h,content:""}}else p={offset:u.offset,length:l.children[c+1].offset-u.offset,content:""};return hs(i,p,n)}else throw new Error(`Can not add ${typeof d!="number"?"index":"property"} to parent of type ${l.type}`);else return e===void 0?[]:hs(i,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(e)},n)}function hs(i,t,e){let n=rh(i,t),r=t.offset,o=t.offset+t.content.length;if(t.length===0||t.content.length===0){for(;r>0&&!Rl(n,r-1);)r--;for(;o<n.length&&!Rl(n,o);)o++}let s=z_(n,{offset:r,length:o-r},e);for(let l=s.length-1;l>=0;l--){let d=s[l];n=rh(n,d),r=Math.min(r,d.offset),o=Math.max(o,d.offset+d.length),o+=d.content.length-d.length}let a=i.length-(n.length-o)-r;return[{offset:r,length:a,content:n.substring(r,o)}]}function rh(i,t){return i.substring(0,t.offset)+t.content+i.substring(t.offset+t.length)}function K_(i,t){let e=t.slice(0).sort((r,o)=>{let s=r.offset-o.offset;return s===0?r.length-o.length:s}),n=i.length;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.offset+o.length<=n)i=rh(i,o);else throw new Error("Overlapping edit");n=o.offset}return i}var ys=$("configurationService");function vu(i){let t=i;return t&&typeof t=="object"&&(!t.overrideIdentifier||typeof t.overrideIdentifier=="string")&&(!t.resource||t.resource instanceof y)}function G_(i){let t=i;return t&&typeof t=="object"&&(!t.overrideIdentifiers||Array.isArray(t.overrideIdentifiers))&&!t.overrideIdentifier&&(!t.resource||t.resource instanceof y)}function Su(i,t){let e=Object.create(null);for(let n in i)ih(e,n,i[n],t);return e}function ih(i,t,e,n){let r=t.split("."),o=r.pop(),s=i;for(let a=0;a<r.length;a++){let l=r[a],d=s[l];switch(typeof d){case"undefined":d=s[l]=Object.create(null);break;case"object":if(d===null){n(`Ignoring ${t} as ${r.slice(0,a+1).join(".")} is null`);return}break;default:n(`Ignoring ${t} as ${r.slice(0,a+1).join(".")} is ${JSON.stringify(d)}`);return}s=d}if(typeof s=="object"&&s!==null)try{s[o]=e}catch{n(`Ignoring ${t} as ${r.join(".")} is ${JSON.stringify(s)}`)}else n(`Ignoring ${t} as ${r.join(".")} is ${JSON.stringify(s)}`)}function J_(i,t){let e=t.split(".");Y_(i,e)}function Y_(i,t){if(!i)return;let e=i,n=t.shift();if(t.length===0){delete e[n];return}if(Object.keys(e).indexOf(n)!==-1){let r=e[n];typeof r=="object"&&r!==null&&!Array.isArray(r)&&(Y_(r,t),Object.keys(r).length===0&&delete e[n])}}function El(i,t,e){function n(s,a){let l=s;for(let d of a){if(typeof l!="object"||l===null)return;l=l[d]}return l}let r=t.split("."),o=n(i,r);return typeof o>"u"?e:o}function Q_(i){return i.replace(/^\[/,"").replace(/]$/g,"").replace(/\]\[/g,", ")}function X_(i){let t=!1,e=new Map,n=new Map;if(UA(i,c=>{if(i===c)return!0;let u=JSON.stringify(c);if(u.length<30)return!0;let p=e.get(u);if(!p){let m={schemas:[c]};return e.set(u,m),n.set(c,m),!0}return p.schemas.push(c),n.set(c,p),t=!0,!1}),e.clear(),!t)return JSON.stringify(i);let o="$defs";for(;i.hasOwnProperty(o);)o+="_";let s=[];function a(c){return JSON.stringify(c,(u,p)=>{if(p!==c){let m=n.get(p);if(m&&m.schemas.length>1)return m.id||(m.id=`_${s.length}`,s.push(m.schemas[0])),{$ref:`#/${o}/${m.id}`}}return p})}let l=a(i),d=[];for(let c=0;c<s.length;c++)d.push(`"_${c}":${a(s[c])}`);return d.length?`${l.substring(0,l.length-1)},"${o}":{${d.join(",")}}}`:l}function vs(i){return typeof i=="object"&&i!==null}function UA(i,t){if(!i||typeof i!="object")return;let e=(...l)=>{for(let d of l)vs(d)&&s.push(d)},n=(...l)=>{for(let d of l)if(vs(d))for(let c in d){let u=d[c];vs(u)&&s.push(u)}},r=(...l)=>{for(let d of l)if(Array.isArray(d))for(let c of d)vs(c)&&s.push(c)},o=l=>{if(Array.isArray(l))for(let d of l)vs(d)&&s.push(d);else vs(l)&&s.push(l)},s=[i],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),r(a.anyOf,a.allOf,a.oneOf,a.prefixItems),o(a.items)),a=s.pop()}var sh={JSONContribution:"base.contributions.json"};function Z_(i){return i.length>0&&i.charAt(i.length-1)==="#"?i.substring(0,i.length-1):i}var oh=class extends T{constructor(){super(...arguments);this.schemasById={};this.schemaAssociations={};this._onDidChangeSchema=this._register(new w);this.onDidChangeSchema=this._onDidChangeSchema.event;this._onDidChangeSchemaAssociations=this._register(new w);this.onDidChangeSchemaAssociations=this._onDidChangeSchemaAssociations.event}registerSchema(e,n,r){let o=Z_(e);this.schemasById[o]=n,this._onDidChangeSchema.fire(e),r&&r.add(k(()=>{delete this.schemasById[o],this._onDidChangeSchema.fire(e)}))}registerSchemaAssociation(e,n){let r=Z_(e);return this.schemaAssociations[r]||(this.schemaAssociations[r]=[]),this.schemaAssociations[r].includes(n)||(this.schemaAssociations[r].push(n),this._onDidChangeSchemaAssociations.fire()),k(()=>{let o=this.schemaAssociations[r];if(o){let s=o.indexOf(n);s!==-1&&(o.splice(s,1),o.length===0&&delete this.schemaAssociations[r],this._onDidChangeSchemaAssociations.fire())}})}notifySchemaChanged(e){this._onDidChangeSchema.fire(e)}getSchemaContributions(){return{schemas:this.schemasById}}getSchemaContent(e){let n=this.schemasById[e];return n?X_(n):void 0}hasSchemaContent(e){return!!this.schemasById[e]}getSchemaAssociations(){return this.schemaAssociations}},FA=new oh;mt.add(sh.JSONContribution,FA);var _t,ah=globalThis.vscode;if(typeof ah<"u"&&typeof ah.context<"u"){let i=ah.context.configuration();if(i)_t=i.product;else throw new Error("Sandbox: unable to resolve product configuration from preload script.")}else if(globalThis._VSCODE_PRODUCT_JSON&&globalThis._VSCODE_PACKAGE_JSON){if(_t=globalThis._VSCODE_PRODUCT_JSON,Fe.VSCODE_DEV&&Object.assign(_t,{nameShort:`${_t.nameShort} Dev`,nameLong:`${_t.nameLong} Dev`,dataFolderName:`${_t.dataFolderName}-dev`,serverDataFolderName:_t.serverDataFolderName?`${_t.serverDataFolderName}-dev`:void 0}),!_t.version){let i=globalThis._VSCODE_PACKAGE_JSON;Object.assign(_t,{version:i.version})}Object.assign(_t,{extensionsGallery:Fe.EXTENSIONS_GALLERY?JSON.parse(Fe.EXTENSIONS_GALLERY):_t.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:Fe.CS_TELEMETRY_URL||_t.telemetryEndpoint||"https://v1.telemetry.coder.com/track"})}else _t={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:[],voiceWsUrl:"wss://falcon-caas.mai.microsoft.com/voice-code/api/v1/realtime/voice",enableTelemetry:!0,quality:"stable",codeServerVersion:"4.125.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.125.0",commit:"fade53fcaf82e7c535cb972a7e3d8da4e43b63a4",date:"2026-06-15T22:24:03Z"},Object.keys(_t).length===0&&Object.assign(_t,{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 Gt=_t;var vn={Configuration:"base.contributions.configuration"};function WA(i,t){return i===t?!0:!i||!t?!1:typeof i=="string"||typeof t=="string"?i===t:i.id===t.id}var bu={properties:{},patternProperties:{}},Iu={properties:{},patternProperties:{}},_u={properties:{},patternProperties:{}},Cu={properties:{},patternProperties:{}},Tu={properties:{},patternProperties:{}},xu={properties:{},patternProperties:{}},Pl={properties:{},patternProperties:{}},ro="vscode://schemas/settings/resourceLanguage";var wu=mt.as(sh.JSONContribution),lh=class extends T{constructor(){super();this.registeredConfigurationDefaults=[];this.overrideIdentifiers=new Set;this._onDidSchemaChange=this._register(new w);this.onDidSchemaChange=this._onDidSchemaChange.event;this._onDidUpdateConfiguration=this._register(new w);this.onDidUpdateConfiguration=this._onDidUpdateConfiguration.event;this.configurationDefaultsOverrides=new Map,this.defaultLanguageConfigurationOverridesNode={id:"defaultOverrides",title:g(2228,null),properties:{}},this.configurationContributors=[this.defaultLanguageConfigurationOverridesNode],this.resourceLanguageSettingsSchema={properties:{},patternProperties:{},additionalProperties:!0,allowTrailingCommas:!0,allowComments:!0},this.configurationProperties={},this.policyConfigurations=new Map,this.excludedConfigurationProperties={},wu.registerSchema(ro,this.resourceLanguageSettingsSchema),this.registerOverridePropertyPatternKey()}registerConfiguration(e,n=!0){return this.registerConfigurations([e],n),e}registerConfigurations(e,n=!0){let r=new Set;this.doRegisterConfigurations(e,n,r),wu.registerSchema(ro,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:r})}deregisterConfigurations(e){let n=new Set;this.doDeregisterConfigurations(e,n),wu.registerSchema(ro,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:n})}updateConfigurations({add:e,remove:n}){let r=new Set;this.doDeregisterConfigurations(n,r),this.doRegisterConfigurations(e,!1,r),wu.registerSchema(ro,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:r})}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 r=[];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),d=o[a];if(l.configurationDefaultOverrides.push({value:d,source:s}),Hn.test(a)){let c=this.mergeDefaultConfigurationsForOverrideIdentifier(a,d,s,l.configurationDefaultOverrideValue);if(!c)continue;l.configurationDefaultOverrideValue=c,this.updateDefaultOverrideProperty(a,c,s),r.push(...Ss(a))}else{let c=this.mergeDefaultConfigurationsForConfigurationProperty(a,d,s,l.configurationDefaultOverrideValue);if(!c)continue;l.configurationDefaultOverrideValue=c;let u=this.configurationProperties[a];u&&(this.updatePropertyDefaultValue(a,u),this.updateSchema(a,u))}}this.doRegisterOverrideIdentifiers(r)}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 r of e){let o=this.registeredConfigurationDefaults.indexOf(r);o!==-1&&this.registeredConfigurationDefaults.splice(o,1)}for(let{overrides:r,source:o}of e)for(let s in r){let a=this.configurationDefaultsOverrides.get(s);if(!a)continue;let l=a.configurationDefaultOverrides.findIndex(d=>o?WA(d.source,o):d.value===r[s]);if(l!==-1){if(a.configurationDefaultOverrides.splice(l,1),a.configurationDefaultOverrides.length===0&&this.configurationDefaultsOverrides.delete(s),Hn.test(s)){let d;for(let c of a.configurationDefaultOverrides)d=this.mergeDefaultConfigurationsForOverrideIdentifier(s,c.value,c.source,d);d&&!md(d.value)?(a.configurationDefaultOverrideValue=d,this.updateDefaultOverrideProperty(s,d,o)):(this.configurationDefaultsOverrides.delete(s),delete this.configurationProperties[s],delete this.defaultLanguageConfigurationOverridesNode.properties[s])}else{let d;for(let u of a.configurationDefaultOverrides)d=this.mergeDefaultConfigurationsForConfigurationProperty(s,u.value,u.source,d);a.configurationDefaultOverrideValue=d;let c=this.configurationProperties[s];c&&(this.updatePropertyDefaultValue(s,c),this.updateSchema(s,c))}n.add(s)}}this.updateOverridePropertyPatternKey()}updateDefaultOverrideProperty(e,n,r){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(2227,null,Q_(e)),$ref:ro,defaultDefaultValue:n.value,source:r,defaultValueSource:r};this.configurationProperties[e]=o,this.defaultLanguageConfigurationOverridesNode.properties[e]=o}mergeDefaultConfigurationsForOverrideIdentifier(e,n,r,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 d=n[l];if(Ue(d)&&(go(s[l])||Ue(s[l]))){if(s[l]={...s[l]??{},...d},r)for(let u in d)a.set(`${l}.${u}`,r)}else s[l]=d,r?a.set(l,r):a.delete(l)}return{value:s,source:a}}mergeDefaultConfigurationsForConfigurationProperty(e,n,r,o){let s=this.configurationProperties[e],a=o?.value??s?.defaultDefaultValue,l=r;if(Ue(n)&&(s!==void 0&&s.type==="object"||s===void 0&&(go(a)||Ue(a)))){if(l=o?.source??new Map,!(l instanceof Map)){console.error("defaultValueSource is not a Map");return}for(let c in n)r&&l.set(`${e}.${c}`,r);n={...Ue(a)?a:{},...n}}return{value:n,source:l}}deltaConfiguration(e){let n=!1,r=new Set;e.removedDefaults&&(this.doDeregisterDefaultConfigurations(e.removedDefaults,r),n=!0),e.addedDefaults&&(this.doRegisterDefaultConfigurations(e.addedDefaults,r),n=!0),e.removedConfigurations&&this.doDeregisterConfigurations(e.removedConfigurations,r),e.addedConfigurations&&this.doRegisterConfigurations(e.addedConfigurations,!1,r),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:r,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,r){e.forEach(o=>{this.validateAndRegisterProperties(o,n,o.extensionInfo,o.restrictedProperties,void 0,r),this.configurationContributors.push(o),this.registerJSONConfiguration(o)})}doDeregisterConfigurations(e,n){let r=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=>r(s))};for(let o of e){r(o);let s=this.configurationContributors.indexOf(o);s!==-1&&this.configurationContributors.splice(s,1)}}validateAndRegisterProperties(e,n=!0,r,o,s=4,a){s=bn(e.scope)?s:e.scope;let l=e.properties;if(l)for(let c in l){let u=l[c];if(u.section={id:e.id,title:e.title,order:e.order,extensionInfo:e.extensionInfo},n&&HA(c,u,r?.id)){delete l[c];continue}u.source=r,u.defaultDefaultValue=l[c].default,this.updatePropertyDefaultValue(c,u),Hn.test(c)?u.scope=void 0:(u.scope=bn(u.scope)?s:u.scope,u.restricted=bn(u.restricted)?!!o?.includes(c):u.restricted),u.experiment?u.tags?.some(h=>h.toLowerCase()==="onexp")||(u.tags=u.tags??[],u.tags.push("onExP")):u.tags?.some(h=>h.toLowerCase()==="onexp")&&(console.error(`Invalid tag 'onExP' found for property '${c}'. Please use 'experiment' property instead.`),u.experiment={mode:"startup"});let p=l[c].hasOwnProperty("included")&&!l[c].included,m=l[c].policy?.name;p?(this.excludedConfigurationProperties[c]=l[c],m&&(this.policyConfigurations.set(m,c),a.add(c)),delete l[c]):(a.add(c),m&&this.policyConfigurations.set(m,c),this.configurationProperties[c]=l[c],!l[c].deprecationMessage&&l[c].markdownDeprecationMessage&&(l[c].deprecationMessage=l[c].markdownDeprecationMessage))}let d=e.allOf;if(d)for(let c of d)this.validateAndRegisterProperties(c,n,r,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,r]of this.configurationDefaultsOverrides)r.configurationDefaultOverrideValue&&e.set(n,r.configurationDefaultOverrideValue);return e}registerJSONConfiguration(e){let n=r=>{let o=r.properties;if(o)for(let a in o)this.updateSchema(a,o[a]);r.allOf?.forEach(n)};n(e)}updateSchema(e,n){switch(bu.properties[e]=n,n.scope){case 1:Iu.properties[e]=n;break;case 2:Cu.properties[e]=n;break;case 3:_u.properties[e]=n;break;case 7:Tu.properties[e]=n;break;case 4:xu.properties[e]=n;break;case 5:Pl.properties[e]=n;break;case 6:Pl.properties[e]=n,this.resourceLanguageSettingsSchema.properties[e]=n;break}}removeFromSchema(e,n){switch(delete bu.properties[e],n.scope){case 1:delete Iu.properties[e];break;case 2:delete Cu.properties[e];break;case 3:delete _u.properties[e];break;case 7:delete Tu.properties[e];break;case 4:delete xu.properties[e];break;case 5:case 6:delete Pl.properties[e],delete this.resourceLanguageSettingsSchema.properties[e];break}}updateOverridePropertyPatternKey(){for(let e of this.overrideIdentifiers.values()){let n=`[${e}]`,r={type:"object",description:g(2229,null),errorMessage:g(2230,null),$ref:ro};this.updatePropertyDefaultValue(n,r),bu.properties[n]=r,Iu.properties[n]=r,_u.properties[n]=r,Cu.properties[n]=r,Tu.properties[n]=r,xu.properties[n]=r,Pl.properties[n]=r}}registerOverridePropertyPatternKey(){let e={type:"object",description:g(2229,null),errorMessage:g(2230,null),$ref:ro};bu.patternProperties[fi]=e,Iu.patternProperties[fi]=e,_u.patternProperties[fi]=e,Cu.patternProperties[fi]=e,Tu.patternProperties[fi]=e,xu.patternProperties[fi]=e,Pl.patternProperties[fi]=e,this._onDidSchemaChange.fire()}updatePropertyDefaultValue(e,n){let r=this.configurationDefaultsOverrides.get(e)?.configurationDefaultOverrideValue,o,s;r&&(!n.disallowConfigurationDefault||!r.source)&&(o=r.value,s=r.source),go(o)&&(o=n.defaultDefaultValue,s=void 0),go(o)&&(o=$A(n.type)),n.default=o,n.defaultValueSource=s}},tC="\\[([^\\]]+)\\]",eC=new RegExp(tC,"g"),fi=`^(${tC})+$`,Hn=new RegExp(fi);function Ss(i){let t=[];if(Hn.test(i)){let e=eC.exec(i);for(;e?.length;){let n=e[1].trim();n&&t.push(n),e=eC.exec(i)}}return er(t)}function nC(i){return i.reduce((t,e)=>`${t}[${e}]`,"")}function $A(i){switch(Array.isArray(i)?i[0]:i){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};default:return null}}var Ru=new lh;mt.add(vn.Configuration,Ru);function HA(i,t,e){return i.trim()?Hn.test(i)?g(2226,null,i):Ru.getConfigurationProperties()[i]!==void 0&&(!e||!qA.has(e.toLowerCase()))?g(2224,null,i):t.policy?.name&&Ru.getPolicyConfigurations().get(t.policy?.name)!==void 0?g(2223,null,i,t.policy?.name,Ru.getPolicyConfigurations().get(t.policy?.name)):null:g(2225,null)}var qA=new Set(Gt.defaultChatAgent?[Gt.defaultChatAgent.extensionId,Gt.defaultChatAgent.chatExtensionId].map(i=>i.toLowerCase()):[]);function Al(i){return Object.isFrozen(i)?i:jS(i)}var qe=class i{constructor(t,e,n,r,o){this._contents=t;this._keys=e;this._overrides=n;this._raw=r;this.logService=o;this.overrideConfigurations=new Map}static createEmptyModel(t){return new i({},[],[],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 i)return e;let n=new Eu("",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 i)))return this._raw}isEmpty(){return this._keys.length===0&&Object.keys(this._contents).length===0&&this._overrides.length===0}getValue(t){return t?El(this.contents,t):this.contents}inspect(t,e){let n=this;return{get value(){return Al(n.rawConfiguration.getValue(t))},get override(){return e?Al(n.rawConfiguration.getOverrideValue(t,e)):void 0},get merged(){return Al(e?n.rawConfiguration.override(e).getValue(t):n.rawConfiguration.getValue(t))},get overrides(){let r=[];for(let{contents:o,identifiers:s,keys:a}of n.rawConfiguration.overrides){let l=new i(o,a,[],void 0,n.logService).getValue(t);l!==void 0&&r.push({identifiers:s,value:l})}return r.length?Al(r):void 0}}}getOverrideValue(t,e){let n=this.getContentsForOverrideIdentifer(e);return n?t?El(n,t):n:void 0}getKeysForOverrideIdentifier(t){let e=[];for(let n of this.overrides)n.identifiers.includes(t)&&e.push(...n.keys);return er(e)}getAllOverrideIdentifiers(){let t=[];for(let e of this.overrides)t.push(...e.identifiers);return er(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=cn(this.contents),n=cn(this.overrides),r=[...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(d=>Xt(d.identifiers,a.identifiers));l?(this.mergeContents(l.contents,a.contents),l.keys.push(...a.keys),l.keys=er(l.keys)):n.push(cn(a))}for(let a of s.keys)r.indexOf(a)===-1&&r.push(a)}return new i(e,r,n,!o.length||o.every(s=>s instanceof i)?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 r of er([...Object.keys(this.contents),...Object.keys(e)])){let o=this.contents[r],s=e[r];s&&(typeof o=="object"&&typeof s=="object"?(o=cn(o),this.mergeContents(o,s)):o=s),n[r]=o}return new i(n,this.keys,this.overrides,void 0,this.logService)}mergeContents(t,e){for(let n of Object.keys(e)){if(n in t&&Ue(t[n])&&Ue(e[n])){this.mergeContents(t[n],e[n]);continue}t[n]=cn(e[n])}}getContentsForOverrideIdentifer(t){let e=null,n=null,r=o=>{o&&(n?this.mergeContents(n,o):n=cn(o))};for(let o of this.overrides)o.identifiers.length===1&&o.identifiers[0]===t?e=o.contents:o.identifiers.includes(t)&&r(o.contents);return r(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),J_(this.contents,t),Hn.test(t)&&this.overrides.splice(this.overrides.findIndex(n=>Xt(n.identifiers,Ss(t))),1))}updateValue(t,e,n){if(ih(this.contents,t,e,r=>this.logService.error(r)),n=n||this.keys.indexOf(t)===-1,n&&this.keys.push(t),Hn.test(t)){let r=this.contents[t],o=Ss(t),s={identifiers:o,keys:Object.keys(r),contents:Su(r,l=>this.logService.error(l))},a=this.overrides.findIndex(l=>Xt(l.identifiers,o));a!==-1?this.overrides[a]=s:this.overrides.push(s)}}},Eu=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||qe.createEmptyModel(this.logService)}get restrictedConfigurations(){return this._restrictedConfigurations}get errors(){return this._parseErrors}parse(t,e){if(!bn(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:r,overrides:o,restricted:s,hasExcludedProperties:a}=this.doParseRaw(t,e);this._configurationModel=new qe(n,r,o,a?[t]:void 0,this.logService),this._restrictedConfigurations=s||[]}doParseContent(t){let e={},n=null,r=[],o=[],s=[];function a(d){Array.isArray(r)?r.push(d):n!==null&&(r[n]=d)}let l={onObjectBegin:()=>{let d={};a(d),o.push(r),r=d,n=null},onObjectProperty:d=>{n=d},onObjectEnd:()=>{r=o.pop()},onArrayBegin:()=>{let d=[];a(d),o.push(r),r=d,n=null},onArrayEnd:()=>{r=o.pop()},onLiteralValue:a,onError:(d,c,u)=>{s.push({error:d,offset:c,length:u})}};if(t)try{ms(t,l),e=r[0]||{}}catch(d){this.logService.error(`Error while parsing settings file ${this._name}: ${d}`),this._parseErrors=[d]}return e}doParseRaw(t,e){let n=mt.as(vn.Configuration),r=n.getConfigurationProperties(),o=n.getExcludedConfigurationProperties(),s=this.filter(t,r,o,!0,e);t=s.raw;let a=Su(t,c=>this.logService.error(`Conflict in settings file ${this._name}: ${c}`)),l=Object.keys(t),d=this.toOverrides(t,c=>this.logService.error(`Conflict in settings file ${this._name}: ${c}`));return{contents:a,keys:l,overrides:d,restricted:s.restricted,hasExcludedProperties:s.hasExcludedProperties}}filter(t,e,n,r,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 d in t)if(Hn.test(d)&&r){let c=this.filter(t[d],e,n,!1,o);a[d]=c.raw,s=s||c.hasExcludedProperties,l.push(...c.restricted)}else{let c=e[d];c?.restricted&&l.push(d),this.shouldInclude(d,c,n,o)?a[d]=t[d]:s=!0}return{raw:a,restricted:l,hasExcludedProperties:s}}shouldInclude(t,e,n,r){if(r.exclude?.includes(t))return!1;if(r.include?.includes(t))return!0;if(r.skipRestricted&&e?.restricted||r.skipUnregistered&&!e)return!1;let o=e??n[t],s=o?typeof o.scope<"u"?o.scope:4:void 0;return s===void 0||r.scopes===void 0?!0:r.scopes.includes(s)}toOverrides(t,e){let n=[];for(let r of Object.keys(t))if(Hn.test(r)){let o={},s=t[r];for(let a in s)o[a]=s[a];n.push({identifiers:Ss(r),keys:Object.keys(o),contents:Su(o,e)})}return n}},Pu=class extends T{constructor(e,n,r,o,s){super();this.userSettingsResource=e;this.parseOptions=n;this.fileService=o;this.logService=s;this._onDidChange=this._register(new w);this.onDidChange=this._onDidChange.event;this.parser=new Eu(this.userSettingsResource.toString(),s),this._register(this.fileService.watch(r.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))&&r.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 qe.createEmptyModel(this.logService)}}reparse(e){return e&&(this.parseOptions=e),this.parser.reparse(this.parseOptions),this.parser.configurationModel}getRestrictedSettings(){return this.parser.restrictedConfigurations}},dh=class{constructor(t,e,n,r,o,s,a,l,d,c,u,p,m){this.key=t;this.overrides=e;this._value=n;this.overrideIdentifiers=r;this.defaultConfiguration=o;this.policyConfiguration=s;this.applicationConfiguration=a;this.userConfiguration=l;this.localUserConfiguration=d;this.remoteUserConfiguration=c;this.workspaceConfiguration=u;this.folderConfigurationModel=p;this.memoryConfigurationModel=m}get value(){return Al(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)}},bs=class i{constructor(t,e,n,r,o,s,a,l,d,c){this._defaultConfiguration=t;this._policyConfiguration=e;this._applicationConfiguration=n;this._localUserConfiguration=r;this._remoteUserConfiguration=o;this._workspaceConfiguration=s;this._folderConfigurations=a;this._memoryConfiguration=l;this._memoryConfigurationByResource=d;this.logService=c;this._workspaceConsolidatedConfiguration=null;this._foldersConsolidatedConfigurations=new Oe;this._userConfiguration=null}getValue(t,e,n){return this.getConsolidatedConfigurationModel(t,e,n).getValue(t)}updateValue(t,e,n={}){let r;n.resource?(r=this._memoryConfigurationByResource.get(n.resource),r||(r=qe.createEmptyModel(this.logService),this._memoryConfigurationByResource.set(n.resource,r))):r=this._memoryConfiguration,e===void 0?r.removeValue(t):r.setValue(t,e),n.resource||(this._workspaceConsolidatedConfiguration=null)}inspect(t,e,n){let r=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 r.overrides)for(let d of l.identifiers)r.getOverrideValue(t,d)!==void 0&&a.add(d);return new dh(t,e,r.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:r,updated:o,removed:s}=gi(this._defaultConfiguration,t);e=[...r,...o,...s]}for(let r of e)for(let o of Ss(r)){let s=this._defaultConfiguration.getKeysForOverrideIdentifier(o),a=t.getKeysForOverrideIdentifier(o),l=[...a.filter(d=>s.indexOf(d)===-1),...s.filter(d=>a.indexOf(d)===-1),...s.filter(d=>!We(this._defaultConfiguration.override(o).getValue(d),t.override(o).getValue(d)))];n.push([o,l])}return this.updateDefaultConfiguration(t),{keys:e,overrides:n}}compareAndUpdatePolicyConfiguration(t){let{added:e,updated:n,removed:r}=gi(this._policyConfiguration,t),o=[...e,...n,...r];return o.length&&this.updatePolicyConfiguration(t),{keys:o,overrides:[]}}compareAndUpdateApplicationConfiguration(t){let{added:e,updated:n,removed:r,overrides:o}=gi(this.applicationConfiguration,t),s=[...e,...n,...r];return s.length&&this.updateApplicationConfiguration(t),{keys:s,overrides:o}}compareAndUpdateLocalUserConfiguration(t){let{added:e,updated:n,removed:r,overrides:o}=gi(this.localUserConfiguration,t),s=[...e,...n,...r];return s.length&&this.updateLocalUserConfiguration(t),{keys:s,overrides:o}}compareAndUpdateRemoteUserConfiguration(t){let{added:e,updated:n,removed:r,overrides:o}=gi(this.remoteUserConfiguration,t),s=[...e,...n,...r];return s.length&&this.updateRemoteUserConfiguration(t),{keys:s,overrides:o}}compareAndUpdateWorkspaceConfiguration(t){let{added:e,updated:n,removed:r,overrides:o}=gi(this.workspaceConfiguration,t),s=[...e,...n,...r];return s.length&&this.updateWorkspaceConfiguration(t),{keys:s,overrides:o}}compareAndUpdateFolderConfiguration(t,e){let n=this.folderConfigurations.get(t),{added:r,updated:o,removed:s,overrides:a}=gi(n,e),l=[...r,...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:r,removed:o,overrides:s}=gi(e,void 0);return{keys:[...n,...r,...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 qe(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 r=this.getConsolidatedConfigurationModelForResource(e,n);if(e.overrideIdentifier&&(r=r.override(e.overrideIdentifier)),!this._policyConfiguration.isEmpty()&&this._policyConfiguration.getValue(t)!==void 0){r=r.merge();for(let o of this._policyConfiguration.keys)r.setValue(o,this._policyConfiguration.getValue(o))}return r}getConsolidatedConfigurationModelForResource({resource:t},e){let n=this.getWorkspaceConsolidatedConfiguration();if(e&&t){let r=e.getFolder(t);r&&(n=this.getFolderConsolidatedConfiguration(r.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(),r=this._folderConfigurations.get(t);r?(e=n.merge(r),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:r,keys:o}=this._folderConfigurations.get(e);return t.push([e,{contents:n,overrides:r,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(r=>e.add(r))),[...e.values()]}static parse(t,e){let n=this.parseConfigurationModel(t.defaults,e),r=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),d=t.folders.reduce((c,u)=>(c.set(y.revive(u[0]),this.parseConfigurationModel(u[1],e)),c),new Oe);return new i(n,r,o,s,a,l,d,qe.createEmptyModel(e),new Oe,e)}static parseConfigurationModel(t,e){return new qe(t.contents,t.keys,t.overrides,t.raw,e)}};var Au=class{constructor(t,e,n,r,o){this.change=t;this.previous=e;this.currentConfiguraiton=n;this.currentWorkspace=r;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=bs.parse(this.previous.data,this.logService)),this._previousConfiguration}affectsConfiguration(t,e){let n=this._marker+t,r=this._affectsConfigStr.indexOf(n);if(r<0)return!1;let o=r+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!We(a,l)}return!0}};function gi(i,t){let{added:e,removed:n,updated:r}=rC(t?.rawConfiguration,i?.rawConfiguration),o=[],s=i?.getAllOverrideIdentifiers()||[],a=t?.getAllOverrideIdentifiers()||[];if(t){let l=a.filter(d=>!s.includes(d));for(let d of l)o.push([d,t.getKeysForOverrideIdentifier(d)])}if(i){let l=s.filter(d=>!a.includes(d));for(let d of l)o.push([d,i.getKeysForOverrideIdentifier(d)])}if(t&&i){for(let l of s)if(a.includes(l)){let d=rC({contents:i.getOverrideValue(void 0,l)||{},keys:i.getKeysForOverrideIdentifier(l)},{contents:t.getOverrideValue(void 0,l)||{},keys:t.getKeysForOverrideIdentifier(l)});o.push([l,[...d.added,...d.removed,...d.updated]])}}return{added:e,removed:n,updated:r,overrides:o}}function rC(i,t){let e=i?t?i.keys.filter(o=>t.keys.indexOf(o)===-1):[...i.keys]:[],n=t?i?t.keys.filter(o=>i.keys.indexOf(o)===-1):[...t.keys]:[],r=[];if(i&&t){for(let o of t.keys)if(i.keys.indexOf(o)!==-1){let s=El(t.contents,o),a=El(i.contents,o);We(s,a)||r.push(o)}}return{added:e,removed:n,updated:r}}var ku=$("policy");var mi=class{constructor(){this.onDidChange=Q.None;this.policyDefinitions={}}async updatePolicyDefinitions(){return{}}getPolicyValue(){}serialize(){}};var Du=class extends T{constructor(e){super();this.logService=e;this._onDidChangeConfiguration=this._register(new w);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=qe.createEmptyModel(e)}get configurationModel(){return this._configurationModel}async initialize(){return this.resetConfigurationModel(),this._register(mt.as(vn.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,mt.as(vn.Configuration).getConfigurationProperties()),this._onDidChangeConfiguration.fire({defaults:this.configurationModel,properties:e})}getConfigurationDefaultOverrides(){return{}}resetConfigurationModel(){this._configurationModel=qe.createEmptyModel(this.logService);let e=mt.as(vn.Configuration).getConfigurationProperties();this.updateConfigurationModel(Object.keys(e),e)}updateConfigurationModel(e,n){let r=this.getConfigurationDefaultOverrides();for(let o of e){let s=r[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 cn(n.default)}},Ou=class{constructor(){this.onDidChangeConfiguration=Q.None;this.configurationModel=qe.createEmptyModel(new hc)}async initialize(){return this.configurationModel}},Is=class extends T{constructor(e,n,r){super();this.defaultConfiguration=e;this.policyService=n;this.logService=r;this._onDidChangeConfiguration=this._register(new w);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=qe.createEmptyModel(this.logService),this.configurationRegistry=mt.as(vn.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={},r=[],o=this.configurationRegistry.getConfigurationProperties(),s=this.configurationRegistry.getExcludedConfigurationProperties();for(let a of e){let l=o[a]??s[a];if(!l){r.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:d,managedSettings:c,restrictedValue:u}=l.policy;r.push(a),n[l.policy.name]={type:l.type==="number"?"number":l.type==="boolean"?"boolean":"string",value:d,managedSettings:c,restrictedValue:u}}}return md(n)||await this.policyService.updatePolicyDefinitions(n),r}onDidChangePolicies(e){this.logService.trace("PolicyConfiguration#onDidChangePolicies",e);let n=this.configurationRegistry.getPolicyConfigurations(),r=Wr(e.map(o=>n.get(o)));this.update(r,!0)}update(e,n){this.logService.trace("PolicyConfiguration#update",e);let r=this.configurationRegistry.getConfigurationProperties(),o=this.configurationRegistry.getExcludedConfigurationProperties(),s=[],a=this._configurationModel.isEmpty();for(let l of e){let d=r[l]??o[l],c=d?.policy?.name;if(c){let u=this.policyService.getPolicyValue(c);if(Ne(u)&&d.type!=="string")try{u=this.parse(u)}catch(p){this.logService.error(`Error parsing policy value ${c}:`,Ei(p));continue}(a?u!==void 0:!We(this._configurationModel.getValue(l),u))&&s.push([l,u])}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=qe.createEmptyModel(this.logService);for(let d of l.keys)this._configurationModel.setValue(d,l.getValue(d));for(let[d,c]of s)c===void 0?this._configurationModel.removeValue(d):this._configurationModel.setValue(d,c);n&&this._onDidChangeConfiguration.fire(this._configurationModel)}}parse(e){let n={},r=null,o=[],s=[],a=[];function l(c){if(Array.isArray(o))o.push(c);else if(r!==null){if(o[r]!==void 0)throw new Error(`Duplicate property found: ${r}`);o[r]=c}}if(e&&(ms(e,{onObjectBegin:()=>{let c={};l(c),s.push(o),o=c,r=null},onObjectProperty:c=>{r=c},onObjectEnd:()=>{o=s.pop()},onArrayBegin:()=>{let c=[];l(c),s.push(o),o=c,r=null},onArrayEnd:()=>{o=s.pop()},onLiteralValue:l,onError:(c,u,p)=>{a.push({error:c,offset:u,length:p})}}),n=o[0]||n),a.length>0)throw new Error(a.map(c=>Ei(c.error)).join(`
`));return n}};Is=x([C(1,ku),C(2,O)],Is);var _s=class extends T{constructor(e,n,r,o){super();this.settingsResource=e;this.logService=o;this._onDidChangeConfiguration=this._register(new w);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this.defaultConfiguration=this._register(new Du(o)),this.policyConfiguration=r instanceof mi?new Ou:this._register(new Is(this.defaultConfiguration,r,o)),this.userConfiguration=this._register(new Pu(this.settingsResource,{},Je,n,o)),this.configuration=new bs(this.defaultConfiguration.configurationModel,this.policyConfiguration.configurationModel,qe.createEmptyModel(o),qe.createEmptyModel(o),qe.createEmptyModel(o),qe.createEmptyModel(o),new Oe,qe.createEmptyModel(o),new Oe,o),this.configurationEditing=new ch(e,n,this),this.reloadConfigurationScheduler=this._register(new Yr(()=>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,r]=await Promise.all([this.defaultConfiguration.initialize(),this.policyConfiguration.initialize(),this.userConfiguration.loadConfiguration()]);this.configuration=new bs(e,n,qe.createEmptyModel(this.logService),r,qe.createEmptyModel(this.logService),qe.createEmptyModel(this.logService),new Oe,qe.createEmptyModel(this.logService),new Oe,this.logService)}getConfigurationData(){return this.configuration.toData()}getValue(e,n){let r=typeof e=="string"?e:void 0,o=vu(e)?e:vu(n)?n:{};return this.configuration.getValue(r,o,void 0)}async updateValue(e,n,r,o,s){let a=G_(r)?r:vu(r)?{resource:r.resource,overrideIdentifiers:r.overrideIdentifier?[r.overrideIdentifier]:void 0}:void 0,l=a?o:r;if(l!==void 0&&l!==3&&l!==2)throw new Error(`Unable to write ${e} to target ${l}.`);a?.overrideIdentifiers&&(a.overrideIdentifiers=er(a.overrideIdentifiers),a.overrideIdentifiers=a.overrideIdentifiers.length?a.overrideIdentifiers:void 0);let d=this.inspect(e,{resource:a?.resource,overrideIdentifier:a?.overrideIdentifiers?a.overrideIdentifiers[0]:void 0});if(d.policyValue!==void 0)throw new Error(`Unable to write ${e} because it is configured in system policy.`);if(We(n,d.defaultValue)&&(n=void 0),a?.overrideIdentifiers?.length&&a.overrideIdentifiers.length>1){let u=a.overrideIdentifiers.sort(),p=this.configuration.localUserConfiguration.overrides.find(m=>Xt([...m.identifiers].sort(),u));p&&(a.overrideIdentifiers=p.identifiers)}let c=a?.overrideIdentifiers?.length?[nC(a.overrideIdentifiers),e]:[e];await this.configurationEditing.write(c,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(),r=this.configuration.compareAndUpdateLocalUserConfiguration(e);this.trigger(r,n,2)}onDidDefaultConfigurationChange(e,n){let r=this.configuration.toData(),o=this.configuration.compareAndUpdateDefaultConfiguration(e,n);this.trigger(o,r,7)}onDidPolicyConfigurationChange(e){let n=this.configuration.toData(),r=this.configuration.compareAndUpdatePolicyConfiguration(e);this.trigger(r,n,7)}trigger(e,n,r){let o=new Au(e,{data:n},this.configuration,void 0,this.logService);o.source=r,this._onDidChangeConfiguration.fire(o)}},ch=class{constructor(t,e,n){this.settingsResource=t;this.fileService=e;this.configurationService=n;this.queue=new Jr}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 r=[];if(yu(n,r,{allowTrailingComma:!0,allowEmptyContent:!0}),r.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=K_(n,o),await this.fileService.writeFile(this.settingsResource,A.fromString(n))}getEdits(t,e,n){let{tabSize:r,insertSpaces:o,eol:s}=this.formattingOptions;if(!e.length){let a=JSON.stringify(n,null,o?" ".repeat(r):"	");return[{content:a,length:a.length,offset:0}]}return j_(t,e,n,{tabSize:r,insertSpaces:o,eol:s})}get formattingOptions(){if(!this._formattingOptions){let t=at===3||at===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 Lu=$("requestService"),aC="NO_FETCH_TELEMETRY",fh=class{constructor(t){this.original=t}toJSON(){if(!this.headers){let t=Object.create(null);for(let e in this.original)e.toLowerCase()==="authorization"||e.toLowerCase()==="proxy-authorization"?t[e]="*****":t[e]=this.original[e];this.headers=t}return this.headers}},Mu=class extends T{constructor(e){super();this.logService=e;this.counter=0;this._onDidCompleteRequest=this._register(new w);this.onDidCompleteRequest=this._onDidCompleteRequest.event}async logAndRequest(e,n){let r=`#${++this.counter}: ${e.url}`;this.logService.trace(`${r} - begin`,e.type,new fh(e.headers??{}));let o=Date.now();try{let s=await n();return this.logService.trace(`${r} - end`,e.type,s.res.statusCode,s.res.headers),this._onDidCompleteRequest.fire({callSite:e.callSite,latency:Date.now()-o,statusCode:s.res.statusCode}),s}catch(s){throw this.logService.error(`${r} - error`,e.type,Ei(s)),s}}};var gh=!1,ph=[],oC,sC;function VA(i=!0,t=!0){if(oC===i&&sC===t)return;oC=i,sC=t;let e=mt.as(vn.Configuration),n=ph;ph=[{id:"http",order:15,title:g(2599,null),type:"object",scope:2,properties:{"http.useLocalProxyConfiguration":{type:"boolean",default:t,markdownDescription:g(2614,null),restricted:!0}}},{id:"http",order:15,title:g(2599,null),type:"object",scope:1,properties:{"http.electronFetch":{type:"boolean",default:!1,description:g(2597,null),restricted:!0}}},{id:"http",order:15,title:g(2599,null),type:"object",scope:i?1:2,properties:{"http.proxy":{type:"string",pattern:"^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",markdownDescription:g(2602,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyStrictSSL":{type:"boolean",default:!0,markdownDescription:g(2610,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyKerberosServicePrincipal":{type:"string",markdownDescription:g(2604,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.noProxy":{type:"array",items:{type:"string"},markdownDescription:g(2601,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyAuthorization":{type:["null","string"],default:null,markdownDescription:g(2603,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxySupport":{type:"string",enum:["off","on","fallback","override"],enumDescriptions:[g(2607,null),g(2608,null),g(2606,null),g(2609,null)],default:"override",markdownDescription:g(2605,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificates":{type:"boolean",default:!0,markdownDescription:g(2611,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificatesNode":{type:"boolean",tags:["experimental"],default:gh,markdownDescription:g(2612,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}},"http.experimental.systemCertificatesV2":{type:"boolean",tags:["experimental"],default:!1,markdownDescription:g(2613,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.fetchAdditionalSupport":{type:"boolean",default:!0,markdownDescription:g(2598,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.webSocketAdditionalSupport":{type:"boolean",default:!0,markdownDescription:g(2615,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.experimental.networkInterfaceCheckInterval":{type:"number",default:300,minimum:-1,tags:["experimental"],markdownDescription:g(2600,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}}}}],e.updateConfigurations({add:ph,remove:n})}VA();var zA=!1,hh=class{constructor(t,e,n){this.id=t;this.dependencies=e;this.callback=n}};var yh=class i{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 i}_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 hh(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(`${ie.vscodeFileResource}://${xg}`))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=N();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={},r=[],o=[];if(Array.isArray(e.dependencies))for(let s of e.dependencies)s==="exports"?r.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(...r)??n:e.callback}_rendererLoadScript(t){return new Promise((e,n)=>{let r=document.createElement("script");r.setAttribute("async","async"),r.setAttribute("type","text/javascript");let o=()=>{r.removeEventListener("load",s),r.removeEventListener("error",a)},s=l=>{o(),e(this._defineCalls.pop())},a=l=>{o(),n(l)};r.addEventListener("load",s),r.addEventListener("error",a),this._amdPolicy&&(t=this._amdPolicy.createScriptURL(t)),r.setAttribute("src",t),window.document.getElementsByTagName("head")[0].appendChild(r)})}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,r=(await import("module")).default,o=y.parse(t).fsPath,s=e.readFileSync(o).toString(),a=r.wrap(s.replace(/^#!.*/,""));return new n.Script(a).runInThisContext().apply(),this._defineCalls.pop()}catch(e){throw e}}},mh=new Map;async function vh(i,t,e){e===void 0&&(e=!!(globalThis._VSCODE_PRODUCT_JSON??globalThis.vscode?.context?.configuration()?.product)?.commit);let n=t?`${i}/${t}`:i;if(mh.has(n))return mh.get(n);let r;if(/^\w[\w\d+.-]*:\/\//.test(n))r=n;else{let l=`${zA&&e&&!Et?_S:IS}/${n}`;r=dt.asBrowserUri(l).toString(!0)}let o=yh.INSTANCE.load(r);return mh.set(n,o),o}function jA(i){if(rg===2&&/^penguin(\.|$)/i.test(i))return"chromebook"}function lC(i,t,e,n,r,o,s,a,l,d,c){let u=Object.create(null);u["common.machineId"]=o,u["common.sqmId"]=s,u["common.devDeviceId"]=a,u.sessionID=N()+Date.now(),u.commitHash=n,u.version=r,u["common.releaseDate"]=d,u["common.platformVersion"]=(i||"").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/,"$1$2$3"),u["common.platform"]=Ov(rg),u["common.nodePlatform"]=bo,u["common.nodeArch"]=e,u["common.product"]=c||"desktop",l&&(u["common.msftInternal"]=l);let p=0,m=Date.now();Object.defineProperties(u,{timestamp:{get:()=>new Date,enumerable:!0},"common.timesincesessionstart":{get:()=>Date.now()-m,enumerable:!0},"common.sequence":{get:()=>p++,enumerable:!0}}),Mv&&(u["common.snap"]="true");let h=jA(t);return h&&(u["common.platformDetail"]=h),u}function dC(i){let t=Fe.USERDNSDOMAIN;if(!t)return!1;let e=t.toLowerCase();return i.some(n=>e===n)}var kl=class{constructor(t){this.value=t;this.isTrustedTelemetryValue=!0}},Sh=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(){}},Nu=new Sh;var bh="telemetry",uC={id:bh,name:g(2639,null)};function pC(i,t){return!t.isBuilt&&!t.disableTelemetry?!0:!(t.disableTelemetry||!i.enableTelemetry)}function Uu(i,t){return t.extensionTestsLocationURI?!0:!(t.isBuilt||t.disableTelemetry||i.enableTelemetry&&i.aiConfig?.ariaKey)}function fC(i){let t=i.getValue(Zo),e=i.getValue(wc);if(i.getValue(pl)===!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 Fu(i){let t={},e={},n={};gC(i,n);for(let r in n){r=r.length>150?r.substr(r.length-149):r;let o=n[r];typeof o=="number"?e[r]=o:typeof o=="boolean"?e[r]=o?1:0:typeof o=="string"?(o.length>8192&&console.warn(`Telemetry property: ${r} has been trimmed to 8192, the original length is ${o.length}`),t[r]=o.substring(0,8191)):typeof o<"u"&&o!==null&&(t[r]=String(o))}return{properties:t,measurements:e}}function gC(i,t,e=0,n){if(!i||typeof i!="object"&&typeof i!="function")return;let r=i;for(let o of Object.getOwnPropertyNames(r)){let s=r[o],a=n?n+o:o;Array.isArray(s)?t[a]=Ng(s):s instanceof Date?t[a]=s.toISOString():Ue(s)?e<2?gC(s,t,e+1,a+"."):t[a]=Ng(s):t[a]=s}}function mC(i,t){let e=i.msftInternalDomains||[],n=t.getValue("telemetry.internalTesting");return dC(e)||n}function hC(i){return[i.appRoot,i.extensionsPath,i.userHome.fsPath,i.tmpDir.fsPath,i.userDataPath]}function KA(i,t){if(!i||!i.includes("/")&&!i.includes("\\"))return i;let e=i,n=[];for(let l of t)for(;;){let d=l.exec(i);if(!d)break;n.push([d.index,l.lastIndex])}let r=/(?:^|[\\\/])((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(i);if(!l)break;if(!n.some(([c,u])=>l.index<u&&c<s.lastIndex)){let c=o.exec(l[0]);if(c)e+=i.substring(a,l.index)+"<REDACTED: user-file-path>/"+c[2];else{let u=r.exec(l[0]);u?e+=i.substring(a,l.index)+"<REDACTED: user-file-path>/"+u[1]:e+=i.substring(a,l.index)+"<REDACTED: user-file-path>"}a=s.lastIndex}}return a<i.length&&(e+=i.substr(a)),e}var yC=[{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,}/}];function cC(i,t=i){for(let e of yC)if(e.regex.test(t))return`<REDACTED: ${e.label}>`;return i}function GA(i){if(!i)return i;let t=!1;for(let n of yC)if(n.regex.test(i)){t=!0;break}if(!t)return i;if(!i.includes(`
`))return cC(i);let e=i.split(`
`);for(let n=0;n<e.length;n++){let r=n<e.length-1?e[n]+`
`:e[n];e[n]=cC(e[n],r)}return e.join(`
`)}function vC(i,t){return i?Ha(i,e=>{if(e instanceof kl||Object.hasOwnProperty.call(e,"isTrustedTelemetryValue"))return e.value;if(typeof e=="string"){let n=e.replaceAll("%20"," ");n=KA(n,t);for(let r of t)n=n.replace(r,"");return n=GA(n),n}}):{}}var SC="https://mobile.events.data.microsoft.com/OneCollector/1.0",JA="https://mobile.events.data.microsoft.com/ping";async function YA(i,t,e){let n=Et?await vh("@microsoft/1ds-core-js","bundle/ms.core.min.js"):await import("@microsoft/1ds-core-js"),r=Et?await vh("@microsoft/1ds-post-js","bundle/ms.post.min.js"):await import("@microsoft/1ds-post-js"),o=new n.AppInsightsCore,s=new r.PostChannel,a={instrumentationKey:i,endpointUrl:SC,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 Wu=class{constructor(t,e,n,r,o){this._isInternalTelemetry=t;this._eventPrefix=e;this._defaultData=n;this._xhrOverride=o;this.endPointUrl=SC;this.endPointHealthUrl=JA;this._defaultData||(this._defaultData={}),typeof r=="function"?this._aiCoreOrKey=r():this._aiCoreOrKey=r,this._asyncAiCore=null}_withAIClient(t){if(this._aiCoreOrKey){if(typeof this._aiCoreOrKey!="string"){t(this._aiCoreOrKey);return}this._asyncAiCore||(this._asyncAiCore=YA(this._aiCoreOrKey,this._isInternalTelemetry,this._xhrOverride)),this._asyncAiCore.then(e=>{t(e)},e=>{ze(e),console.error(e)})}}log(t,e){if(!this._aiCoreOrKey)return;e=Wo(e,this._defaultData);let n=Fu(e),r=this._eventPrefix+"/"+t;try{this._withAIClient(o=>{o.pluginVersionString=n?.properties.version??"Unknown",o.track({name:r,baseData:{name:r,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 QA(i,t){let e=await t.request(i,Ee.None),n=(await Xr(e.stream)).toString(),r=e.res.statusCode??200;return{headers:e.res.headers,statusCode:r,responseData:n}}async function XA(i){let t=await import("https"),e={method:i.type,headers:i.headers};return new Promise((r,o)=>{let s=t.request(i.url??"",e,a=>{a.on("data",function(l){r({headers:a.headers,statusCode:a.statusCode??200,responseData:l.toString()})}),a.on("error",function(l){o(l)})});s.write(i.data,a=>{a&&o(a)}),s.end()})}async function ZA(i,t,e){let n=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data),r={type:"POST",headers:{...t.headers,"Content-Type":"application/json","Content-Length":Buffer.byteLength(t.data).toString()},url:t.urlString,data:n,callSite:aC};try{let o=i?await QA(r,i):await XA(r);e(o.statusCode,o.headers,o.responseData)}catch{e(0,{})}}var $u=class extends Wu{constructor(t,e,n,r,o){let s={sendPOST:(a,l)=>{ZA(t,a,l)}};super(e,n,r,o,s)}};var Cs=class extends T{constructor(e,n,r,o,s){super();this.prefix=e;let a=n?"remoteTelemetry":bh,l=r.getLogger(a);if(l)this.logger=this._register(l);else{let c=Uu(s,o)?" (Not Sent)":"";this.logger=this._register(r.createLogger(a,{name:g(2619,null,c),group:uC,hidden:!0}))}}flush(){return Promise.resolve()}log(e,n){this.logger.trace(`${this.prefix}telemetry/${e}`,Fu(n))}};Cs=x([C(2,Gb),C(3,vl),C(4,gt)],Cs);var sY={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 Pr=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 r of this._piiPaths)this._cleanupPatterns.push(new RegExp(Zt(r),"gi")),r.indexOf("\\")>=0&&this._cleanupPatterns.push(new RegExp(Zt(r.replace(/\\/g,"/")),"gi"));this._updateTelemetryLevel(),this._disposables.add(this._configurationService.onDidChangeConfiguration(r=>{(r.affectsConfiguration(Zo)||r.affectsConfiguration(pl)||r.affectsConfiguration(wc))&&this._updateTelemetryLevel()})),t.waitForExperimentProperties?this._flushTimeout=setTimeout(()=>this._flushPendingEvents(),Pr.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 kl(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=fC(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<Pr.MAX_BUFFER_SIZE&&this._pendingEvents.push({eventName:t,eventLevel:e,data:n});return}this._doLog(t,e,n)}}_doLog(t,e,n){n=Wo(n,this._experimentProperties),n=vC(n,this._cleanupPatterns),n=Wo(n,this._commonProperties),e===2&&(n={...n,isError:!0}),this._appenders.forEach(r=>r.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)}};Pr=x([C(1,ys),C(2,gt)],Pr);function ek(){let i=g(2636,null,Gt.nameLong),t=Gt.privacyStatementUrl?g(2622,null,"https://aka.ms/vscode-telemetry",Gt.privacyStatementUrl):g(2623,null,"https://aka.ms/vscode-telemetry"),e=Et?"":g(2628,null),n=g(2621,null),r=g(2626,null),o=g(2637,null),s=g(2635,null),a=`
|       | ${n} | ${r} | ${o} |
|:------|:-------------:|:---------------:|:----------:|
| all   |       \u2713       |        \u2713        |     \u2713      |
| error |       \u2713       |        \u2713        |     -      |
| crash |       \u2713       |        -        |     -      |
| off   |       -       |        -        |     -      |
`,l=g(2631,null);return`
${i} ${t} ${e}

&nbsp;

${s}
${a}

&nbsp;

${l}
`}var tk=mt.as(vn.Configuration);tk.registerConfiguration({id:OI,order:1,type:"object",title:g(2638,null),properties:{[Zo]:{type:"string",enum:["all","error","crash","off"],enumDescriptions:[g(2630,null),g(2632,null),g(2629,null),g(2633,null)],markdownDescription:ek(),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(2634,null)},enumDescriptions:[{key:"telemetry.telemetryLevel.default",value:g(2630,null)},{key:"telemetry.telemetryLevel.error",value:g(2632,null)},{key:"telemetry.telemetryLevel.crash",value:g(2629,null)},{key:"telemetry.telemetryLevel.off",value:g(2633,null)}]}}},"telemetry.feedback.enabled":{type:"boolean",default:!0,description:g(2627,null),policy:{name:"EnableFeedback",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.feedback.enabled",value:g(2627,null)}}}},[pl]:{type:"boolean",markdownDescription:Gt.privacyStatementUrl?g(2625,null,Gt.nameLong,Gt.privacyStatementUrl):g(2624,null,Gt.nameLong),default:!0,restricted:!0,markdownDeprecationMessage:g(2620,null,`\`#${Zo}#\``),scope:1,tags:["usesOnlineServices","telemetry"]}}});var Hu=class extends T{constructor(e){super();this._delegate=e;this._telemetryLevel=3;So(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 qu(i,t){let e=t?.[fl],n=FI(e);!ik(i)||n===void 0||i.updateTelemetryLevel(n)}function ik(i){return typeof i.updateTelemetryLevel=="function"}async function bC(i){let{environmentService:t,productService:e,fileService:n,loggerService:r,logService:o,disposables:s}=i;if(i.disableTelemetry||!r||!pC(e,t))return s.add(new Hu(Nu));let a=s.add(new _s(X(t.appSettingsHome,"settings.json"),n,new mi,o));await a.initialize();let l=[s.add(new Cs("",!1,r,t,e))],d=mC(e,a);if(!Uu(e,t)&&e.aiConfig?.ariaKey){let h=new $u(void 0,d,"monacoworkbench",null,e.aiConfig.ariaKey);s.add(k(()=>{h.flush()})),l.push(h)}let[c,u,p]=await Promise.all([lu(h=>o.error(h)),F_(h=>o.error(h)),du(h=>o.error(h))]),m=new Pr({appenders:l,sendErrorTelemetry:!0,commonProperties:lC(rk(),nk(),process.arch,e.commit,e.version,c,u,p,d,e.date),piiPaths:hC(t)},a,e);return s.add(new Hu(m))}var Bu=class{constructor(t){this._telemetryService=t}userMessageSent(t,e,n,r,o){let s=o?.length??0,a=n?.activeClient;this._telemetryService.publicLog2("agentHost.userMessageSent",{provider:t,agentSessionId:F.id(e),source:r,isSubagentSession:Xo(e),turnCount:n?.turns.length??0,...a?{activeClientId:a.clientId,activeClientToolCount:a.tools.length,activeClientCustomizationCount:a.customizations?.length??0}:{},attachmentCount:s})}turnCompleted(t){this._telemetryService.publicLog2("agentHost.turnCompleted",{provider:t.provider,agentSessionId:F.id(t.session),timeToFirstProgress:t.timeToFirstProgress,totalTime:t.totalTime,result:t.result,model:t.model,permissionLevel:t.permissionLevel})}};var Vu=class{constructor(t){this._reporter=t;this._turnTimings=new Map}turnStarted(t,e,n,r,o){let s=this._key(e,n);this._turnTimings.set(s,{stopWatch:Io.create(!1),provider:t,session:e,model:r,permissionLevel:o,firstProgressMs:void 0})}markFirstProgress(t,e){let n=this._turnTimings.get(this._key(t,e));n&&n.firstProgressMs===void 0&&(n.firstProgressMs=n.stopWatch.elapsed())}turnCompleted(t,e,n){let r=this._key(t,e),o=this._turnTimings.get(r);o&&(this._turnTimings.delete(r),this._reporter.turnCompleted({provider:o.provider,session:o.session,timeToFirstProgress:o.firstProgressMs,totalTime:o.stopWatch.elapsed(),result:n,model:o.model,permissionLevel:o.permissionLevel}))}_key(t,e){return`${t}\0${e}`}};var IC=200,Ts=class extends T{constructor(e,n,r){super();this._stateManager=e;this._options=n;this._logService=r;this._titleGenerationCancellationSources=new Map}seedTitleFromFirstMessage(e,n){let r=this._stateManager.getSessionState(e),o=n.trim().replace(/\s+/g," ").slice(0,IC);!r||r.turns.length!==0||r.summary.title||o.length===0||(this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:o}),this._generateTitleSoon(e,n,o))}cancelTitleGeneration(e){this._cancelTitleGeneration(e)}_generateTitleSoon(e,n,r){this._cancelTitleGeneration(e);let o=new je;this._titleGenerationCancellationSources.set(e,o),this._generateTitle(e,n,r,o.token).catch(s=>{o.token.isCancellationRequested||this._logService.warn(`[AgentHostSessionTitleController] Failed to apply generated title for ${e}`,s)}).finally(()=>{this._titleGenerationCancellationSources.get(e)===o&&(this._titleGenerationCancellationSources.delete(e),o.dispose())})}async _generateTitle(e,n,r,o){let s=await this._generateTitleFromPrompt(n,o);if(o.isCancellationRequested||!s)return;let a=this._stateManager.getSessionState(e);!a||a.summary.title!==r||(s!==r&&this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:s}),this._persistCustomTitle(e,s))}async _generateTitleFromPrompt(e,n){if(n.isCancellationRequested)return;let r=this._options.getGitHubCopilotToken?.(),o=this._options.copilotApiService;if(!r||!o)return;let s=new AbortController,a=n.onCancellationRequested(()=>s.abort());try{let l=await o.utilityChatCompletion(r,{messages:this._buildTitlePrompt(e)},{signal:s.signal});return this._cleanTitle(l)}catch(l){if(n.isCancellationRequested)return;this._logService.warn("[AgentHostSessionTitleController] Failed to generate session title",l);return}finally{a.dispose()}}_buildTitlePrompt(e){return[{role:"system",content:["You are an expert in crafting ultra-compact titles for chatbot conversations.","You are presented with a chat request, and you reply with only a brief title that captures the main topic of that request.","Write the title in sentence case, not title case.","Preserve product names, abbreviations, code symbols, and proper nouns.","Aim for 3-6 words. Prefer the shortest accurate title.",'Drop articles like "a", "an", and "the" unless needed for clarity.','Drop filler and generic framing like "help with", "question about", "request for", or "issue with".',"Prefer short, concrete synonyms and omit unnecessary words.","Do not wrap the title in quotes or add trailing punctuation."].join(" ")},{role:"user",content:`Please write a brief title for the following request:

${e}`}]}_cleanTitle(e){let n=e.trim();if(n=n.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)??"",n.startsWith('"')&&n.endsWith('"')&&n.length>1&&(n=n.slice(1,-1).trim()),n=n.replace(/[.!?]+$/,"").trim(),!(!n||n.includes("can't assist with that")))return n.slice(0,IC)}_persistCustomTitle(e,n){let r=this._options.sessionDataService.openDatabase(y.parse(e));r.object.setMetadata("customTitle",n).catch(o=>{this._logService.warn("[AgentHostSessionTitleController] Failed to persist customTitle",o)}).finally(()=>{r.dispose()})}_cancelTitleGeneration(e){let n=this._titleGenerationCancellationSources.get(e);n&&(n.dispose(!0),this._titleGenerationCancellationSources.delete(e))}dispose(){for(let e of this._titleGenerationCancellationSources.values())e.dispose(!0);this._titleGenerationCancellationSources.clear(),super.dispose()}};Ts=x([C(2,O)],Ts);var xs=class extends T{constructor(e,n,r,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 Bu(this._telemetryService),this._turnTracker=new Vu(this._telemetryReporter),this._permissionManager=this._register(r.createInstance(ps,this._stateManager)),this._titleController=this._register(r.createInstance(Ts,this._stateManager,{sessionDataService:this._options.sessionDataService,getGitHubCopilotToken:this._options.getGitHubCopilotToken,copilotApiService:this._options.copilotApiService})),this._register(Un(d=>{let c=this._options.agents.read(d);this._publishAgentInfos(c,d)})),this._register(this._stateManager.onDidEmitEnvelope(d=>{if(!d.origin&&d.action.type==="session/toolCallComplete"){let c=d.action;this._options.getAgent(d.channel)?.onClientToolCallComplete(y.parse(d.channel),c.toolCallId,c.result)}}))}_publishAgentInfos(e,n){let r=e.map(o=>{let s=o.getDescriptor(),a=o.getProtectedResources(),l=n?o.models.read(n):o.models.get(),d=o.getCustomizations?.();return{provider:s.provider,displayName:s.displayName,description:s.description,models:l.map(c=>({id:c.id,provider:c.provider,name:c.name,maxContextWindow:c.maxContextWindow,supportsVision:c.supportsVision,policyState:c.policyState,configSchema:c.configSchema,_meta:c._meta})),customizations:d?.length?[...d]:void 0,protectedResources:a.length>0?a:void 0}});We(this._lastAgentInfos,r)||(this._lastAgentInfos=r,this._stateManager.dispatchServerAction(Be,{type:"root/agentsChanged",agents:r}))}async _publishSessionCustomizations(e,n){if(!e.getSessionCustomizations)return;let r=await e.getSessionCustomizations(y.parse(n));this._stateManager.dispatchServerAction(n,{type:"session/customizationsChanged",customizations:[...r]})}_publishSessionCustomizationsSoon(e,n){this._publishSessionCustomizations(e,n).catch(r=>{this._logService.error("[AgentSideEffects] getSessionCustomizations failed",r)})}_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(r=>{this._handleAgentSignal(e,r)})),e.onDidCustomizationsChange&&n.add(e.onDidCustomizationsChange(()=>{this._publishAgentInfos(this._options.agents.get()),this._publishSessionCustomizationsForAgent(e)})),n}_handleAgentSignal(e,n){let r=n.session.toString();if(n.kind==="action"&&n.action.type==="session/toolCallStart"&&!n.parentToolCallId&&this._toolCallAgents.set(`${r}:${n.action.toolCallId}`,e.id),n.kind==="subagent_started"){this._handleSubagentStarted(r,n.toolCallId,n.agentName,n.agentDisplayName,n.agentDescription),this._drainPendingSubagentSignals(r,n.toolCallId);return}if(n.kind==="subagent_completed"){this.completeSubagentSession(r,n.toolCallId);return}if(n.kind==="steering_consumed"){this._stateManager.dispatchServerAction(r,{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=`${r}:${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 c=this._stateManager.getActiveTurnId(l);c&&this._dispatchActionForSession(n,l,c,e);return}this._logService.trace(`[AgentSideEffects] Buffering ${this._describeSignal(n)} for pending subagent ${a}`);let d=this._pendingSubagentSignals.get(a);d||(d=[],this._pendingSubagentSignals.set(a,d)),d.push({signal:n,agent:e});return}if(n.kind==="pending_confirmation"){let a=this._findSubagentSessionForToolCall(r,n.state.toolCallId);if(a){let l=this._stateManager.getActiveTurnId(a);l&&this._handleToolReady(n,a,l,e);return}}let s=this._stateManager.getActiveTurnId(r);if(s){this._dispatchActionForSession(n,r,s,e);return}n.kind==="action"&&(this._stateManager.dispatchServerAction(r,n.action),n.action.type==="session/turnComplete"&&this._runTurnCompleteSideEffects(r,void 0))}_dispatchActionForSession(e,n,r,o){if(e.kind==="pending_confirmation"){o&&this._handleToolReady(e,n,r,o);return}if(e.kind!=="action")return;let s=e.action;if(ye(s,{turnId:!0})&&s.turnId!==r&&(s={...s,turnId:r}),s.type==="session/toolCallComplete"){let a=`${n}:${s.toolCallId}`;if(this._subagentSessions.get(a)){let d=this._stateManager.getSessionState(n),u=this._getRunningToolCallContent(d,r,s.toolCallId).find(p=>ye(p,{type:!0})&&p.type==="subagent");if(u){let p=[...s.result.content??[],u];s={...s,result:{...s.result,content:p}}}}}this._stateManager.dispatchServerAction(n,s),(s.type==="session/delta"||s.type==="session/responsePart"||s.type==="session/toolCallStart"||s.type==="session/reasoning")&&this._turnTracker.markFirstProgress(n,r),s.type==="session/toolCallComplete"&&(this._pendingSubagentSignals.delete(`${n}:${s.toolCallId}`),xI(s.result).length>0&&this._changesets.onToolCallEditsApplied(n,r)),s.type==="session/turnComplete"&&(this._turnTracker.turnCompleted(n,r,"success"),this._runTurnCompleteSideEffects(n,r)),s.type==="session/turnCancelled"&&this._turnTracker.turnCompleted(n,r,"cancelled"),s.type==="session/error"&&this._turnTracker.turnCompleted(n,r,"error")}_runTurnCompleteSideEffects(e,n){n!==void 0?this._checkpointService.captureTurnCheckpoint(y.parse(e),n).then(()=>{this._changesets.onTurnComplete(e,n)},r=>{this._logService.warn(`[AgentSideEffects] Turn checkpoint capture failed for ${e}/${n}: ${r instanceof Error?r.message:String(r)}`),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 r=`${e}:${n}`,o=this._pendingSubagentSignals.get(r);if(o){this._pendingSubagentSignals.delete(r),this._logService.trace(`[AgentSideEffects] Draining ${o.length} buffered signal(s) for subagent ${r}`);for(let{signal:s,agent:a}of o)this._handleAgentSignal(a,s)}}_handleSubagentStarted(e,n,r,o,s){let a=Qo(e,n),l=`${e}:${n}`;if(this._subagentSessions.has(l))return;this._logService.info(`[AgentSideEffects] Creating subagent session: ${a} (parent=${e}, toolCallId=${n})`);let d=this._stateManager.getSessionState(e);this._stateManager.restoreSession({resource:a,provider:"subagent",title:o,status:1,createdAt:Date.now(),modifiedAt:Date.now(),...d?.summary.project?{project:d.summary.project}:{}},[]);let c=N();this._stateManager.dispatchServerAction(a,{type:"session/turnStarted",turnId:c,message:{text:"",origin:{kind:"user"}}}),this._subagentSessions.set(l,a);let u=this._stateManager.getActiveTurnId(e);if(u){let p=this._stateManager.getSessionState(e),h=[...this._getRunningToolCallContent(p,u,n),{type:"subagent",resource:a,title:o,agentName:r,description:s}];this._stateManager.dispatchServerAction(e,{type:"session/toolCallContentChanged",turnId:u,toolCallId:n,content:h})}}_getRunningToolCallContent(e,n,r){if(!e?.activeTurn||e.activeTurn.id!==n)return[];for(let o of e.activeTurn.responseParts)if(o.kind==="toolCall"&&o.toolCall.toolCallId===r&&o.toolCall.status==="running")return o.toolCall.content?[...o.toolCall.content]:[];return[]}cancelSubagentSessions(e){for(let[n,r]of this._subagentSessions)if(n.startsWith(`${e}:`)){let o=this._stateManager.getActiveTurnId(r);o&&(this._stateManager.dispatchServerAction(r,{type:"session/turnCancelled",turnId:o}),this._turnTracker.turnCompleted(r,o,"cancelled")),this._subagentSessions.delete(n)}for(let n of[...this._pendingSubagentSignals.keys()])n.startsWith(`${e}:`)&&this._pendingSubagentSignals.delete(n)}completeSubagentSession(e,n){let r=`${e}:${n}`;this._pendingSubagentSignals.delete(r);let o=this._subagentSessions.get(r);if(!o)return;let s=this._stateManager.getActiveTurnId(o);s&&this._stateManager.dispatchServerAction(o,{type:"session/turnComplete",turnId:s}),this._subagentSessions.delete(r)}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 r=`${e}/subagent/`;for(let o of this._stateManager.getSessionUrisWithPrefix(r))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 r=`${e}:`;for(let[o,s]of this._subagentSessions)if(o.startsWith(r)&&this._toolCallAgents.has(`${s}:${n}`))return s}_handleToolReady(e,n,r,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=this._stateManager.getSessionState(n)?.activeTurn?.responseParts.find(m=>m.kind==="toolCall"&&m.toolCall.toolCallId===e.state.toolCallId),d=l?.kind==="toolCall"?l.toolCall:void 0,c=e.state.contributor??d?.contributor,u=e;a!==void 0&&c?.kind==="client"&&!!e.state.confirmationTitle?(this._toolCallAgents.set(`${n}:${e.state.toolCallId}`,o.id),u={...e,state:{...e.state,_meta:{...d?._meta,...e.state._meta,autoApproveBySetting:!0}}}):a!==void 0?(this._toolCallAgents.delete(`${n}:${e.state.toolCallId}`),o.respondToPermissionRequest(e.state.toolCallId,!0),u={...e,state:{...e.state,confirmationTitle:void 0}}):u.state.confirmationTitle&&this._toolCallAgents.set(`${n}:${e.state.toolCallId}`,o.id),this._stateManager.dispatchServerAction(n,this._permissionManager.createToolReadyAction(u,n,r))}handleAction(e,n){switch(n.type){case"session/turnStarted":{if(this._tryHandleRenameCommand(e,n.turnId,n.message.text))break;let r=this._stateManager.getSessionState(e);this._titleController.seedTitleFromFirstMessage(e,n.message.text);let o=this._options.getAgent(e);if(!o){this._stateManager.dispatchServerAction(e,{type:"session/error",turnId:n.turnId,error:{errorType:"noAgent",message:"No agent found for session"}});return}let s=n.message.attachments;this._telemetryReporter.userMessageSent(o.id,e,r,"direct",s);let{model:a,permissionLevel:l}=this._getTurnTelemetryContext(r);this._turnTracker.turnStarted(o.id,e,n.turnId,a,l),o.sendMessage(y.parse(e),n.message.text,s,n.turnId).catch(d=>{let c=d?.code;this._logService.error(`[AgentSideEffects] sendMessage failed for session=${e}: code=${c}, message=${d instanceof Error?d.message:String(d)}, type=${d?.constructor?.name}`,d),this._stateManager.dispatchServerAction(e,{type:"session/error",turnId:n.turnId,error:_C(d)}),this._turnTracker.turnCompleted(e,n.turnId,"error")});break}case"session/toolCallConfirmed":{let r=`${e}:${n.toolCallId}`,o=this._toolCallAgents.get(r);o?(this._toolCallAgents.delete(r),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._turnTracker.turnCompleted(e,n.turnId,"cancelled"),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 r=this._options.getAgent(e);if(!r)break;let o=n.activeClient?.clientId;r.setClientTools(y.parse(e),o,n.activeClient?.tools??[]);let s=n.activeClient?.customizations??[];r.setClientCustomizations(y.parse(e),o??"",s).catch(a=>{this._logService.error("[AgentSideEffects] setClientCustomizations failed",a)});break}case"root/configChanged":{qu(this._telemetryService,n.config),this._publishAgentInfos(this._options.agents.get()),this._publishAllSessionCustomizations();break}case"session/activeClientToolsChanged":{let r=this._options.getAgent(e);if(r){let s=this._stateManager.getSessionState(e)?.activeClient?.clientId;s&&r.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}}}cancelSessionTitleGeneration(e){this._titleController.cancelTitleGeneration(e)}_tryHandleRenameCommand(e,n,r){let o=T_(r);return o===void 0?!1:(o.length>0&&(this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:o}),this._persistSessionFlag(e,"customTitle",o),this._stateManager.dispatchServerAction(e,{type:"session/responsePart",turnId:n,part:{kind:"markdown",id:N(),content:g(1939,null,o)}})),this._stateManager.dispatchServerAction(e,{type:"session/turnComplete",turnId:n}),this._tryConsumeNextQueuedMessage(e),!0)}_persistSessionFlag(e,n,r){let o=this._options.sessionDataService.openDatabase(y.parse(e));o.object.setMetadata(n,r).catch(s=>{this._logService.warn(`[AgentSideEffects] Failed to persist ${n}`,s)}).finally(()=>{o.dispose()})}_syncPendingMessages(e){let n=this._stateManager.getSessionState(e);if(!n)return;this._options.getAgent(e)?.setPendingMessages?.(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 r=n.queuedMessages[0],o=N();if(this._stateManager.dispatchServerAction(e,{type:"session/turnStarted",turnId:o,message:r.message,queuedMessageId:r.id}),this._tryHandleRenameCommand(e,o,r.message.text))return;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=r.message.attachments,l=this._stateManager.getSessionState(e);this._telemetryReporter.userMessageSent(s.id,e,l,"queued",a);let{model:d,permissionLevel:c}=this._getTurnTelemetryContext(l);this._turnTracker.turnStarted(s.id,e,o,d,c),s.sendMessage(y.parse(e),r.message.text,a,o).catch(u=>{this._logService.error("[AgentSideEffects] sendMessage failed (queued)",u),this._stateManager.dispatchServerAction(e,{type:"session/error",turnId:o,error:_C(u)}),this._turnTracker.turnCompleted(e,o,"error")})}_getTurnTelemetryContext(e){let n=e?.summary.model?.id,r=e?.config?.values.autoApprove;return{model:n,permissionLevel:typeof r=="string"?r:void 0}}dispose(){this._toolCallAgents.clear(),super.dispose()}};xs=x([C(2,ke),C(3,O),C(4,ui),C(5,ai),C(6,Wn)],xs);function _C(i){let t=String(i),e=gu(i instanceof Error?i.message:t);return e?{errorType:"sendFailed",message:xl(t),_meta:wl(e)}:{errorType:"sendFailed",message:t}}var zu=class{constructor(t,e){this._stateManager=t;this._groupByToolName=new Map;for(let n of e)for(let r of n.definitions){if(this._groupByToolName.has(r.name))throw new Error(`Duplicate server tool registered: ${r.name}`);this._groupByToolName.set(r.name,n)}this.definitions=e.flatMap(n=>n.definitions),this.toolNames=this.definitions.map(n=>n.name)}advertise(t){this._stateManager.dispatchServerAction(t,{type:"session/serverToolsChanged",tools:[...this.definitions]})}executeTool(t,e,n){let r=this._groupByToolName.get(e);if(!r)throw new Error(`Unknown server tool: ${e}`);return r.execute(this._stateManager,t,e,n)}};var ju="vscode.agentFeedback";var Ar="addComment",xC="listComments",_h="deleteComments",Ju="resolveComments",ok={type:"object",properties:{resourceUri:{type:"string",description:"URI of the file to add a comment to."},range:{type:"object",description:"One-based text range to comment on.",properties:{startLineNumber:{type:"number",description:"One-based start line number."},startColumn:{type:"number",description:"One-based start column."},endLineNumber:{type:"number",description:"One-based end line number."},endColumn:{type:"number",description:"One-based end column."}},required:["startLineNumber","startColumn","endLineNumber","endColumn"]},text:{type:"string",description:"Comment text to add."}},required:["resourceUri","range","text"]},sk={type:"object",properties:{}},ak={type:"object",properties:{commentIds:{type:"array",items:{type:"string"},description:"Comment IDs to delete."}},required:["commentIds"]},lk={type:"object",properties:{commentIds:{type:"array",items:{type:"string"},description:"Comment IDs to update."},resolved:{type:"boolean",description:"Whether the comments should be marked as resolved. Defaults to true."}},required:["commentIds"]},dk=[{name:Ar,title:"Add Comment (Agent Feedback)",description:"Add a comment to a file range.",inputSchema:ok,annotations:{readOnlyHint:!1}},{name:xC,title:"List Comments (Agent Feedback)",description:"List comments for this session.",inputSchema:sk,annotations:{readOnlyHint:!0}},{name:_h,title:"Delete Comments (Agent Feedback)",description:"Delete comments for this session.",inputSchema:ak,annotations:{readOnlyHint:!1,destructiveHint:!0}},{name:Ju,title:"Resolve Comments (Agent Feedback)",description:"Mark comments for this session as resolved or unresolved.",inputSchema:lk,annotations:{readOnlyHint:!1}}];function Ch(i,t,e){if(typeof i!="string"||i.length===0)throw new Error(`Invalid ${e} input: ${t} must be a non-empty string.`);return i}function Ku(i,t,e){if(typeof i!="number"||!Number.isInteger(i)||i<1)throw new Error(`Invalid ${e} input: ${t} must be a positive integer.`);return i}function ck(i){let t=i??{},e=Ch(t.resourceUri,"resourceUri",Ar),n=Ch(t.text,"text",Ar);if(!t.range||typeof t.range!="object"||Array.isArray(t.range))throw new Error(`Invalid ${Ar} input: range must be an object.`);let r=t.range;return{resourceUri:e,text:n,range:{startLineNumber:Ku(r.startLineNumber,"range.startLineNumber",Ar),startColumn:Ku(r.startColumn,"range.startColumn",Ar),endLineNumber:Ku(r.endLineNumber,"range.endLineNumber",Ar),endColumn:Ku(r.endColumn,"range.endColumn",Ar)}}}function CC(i,t){if(!Array.isArray(i)||i.length===0)throw new Error(`Invalid ${t} input: commentIds must be a non-empty string array.`);let e=[];for(let n of i)e.push(Ch(n,"commentIds[]",t));return[...new Set(e)]}function uk(i){if(i===void 0)return!0;if(typeof i!="boolean")throw new Error(`Invalid ${Ju} input: resolved must be a boolean.`);return i}function pk(i){return{start:{line:i.startLineNumber-1,character:i.startColumn-1},end:{line:i.endLineNumber-1,character:i.endColumn-1}}}function fk(i){return i?{startLineNumber:i.start.line+1,startColumn:i.start.character+1,endLineNumber:i.end.line+1,endColumn:i.end.character+1}:{startLineNumber:1,startColumn:1,endLineNumber:1,endColumn:1}}function TC(i){return typeof i=="string"?i:i.markdown}function Th(i){return i._meta?.[ju]}function Gu(i){let t=i.entries??[],e=Th(i),n=t.slice(1).map(r=>TC(r.text));return{id:i.id,resourceUri:i.resource,range:fk(i.range),text:t.length?TC(t[0].text):"",kind:e?.kind??"user",resolved:i.resolved,...n.length?{replies:n}:{}}}function Ih(i){return i.annotations.filter(t=>{let e=Th(t);return!e||!t.entries?.length?!1:(t.resolved?"resolved":e.state??"accepted")!=="created"})}function gk(i){return JSON.stringify({comments:i.map(Gu)},void 0,2)}function mk(i,t,e,n){switch(e){case Ar:{let{resourceUri:r,range:o,text:s}=ck(n),a=N(),l={kind:"codeReview",state:"created",sessionResource:t},d={id:a,turnId:"",resource:r,range:pk(o),resolved:!1,entries:[{id:`${a}:0`,text:s}],_meta:{[ju]:l}};return{actions:[{type:"annotations/set",annotation:d}],result:"Comment added."}}case xC:return{actions:[],result:gk(Ih(i))};case _h:{let r=CC(n?.commentIds,_h),o=Ih(i),s=new Map(o.map(u=>[u.id,u])),a=[],l=[],d=[];for(let u of r)s.has(u)?(a.push({type:"annotations/removed",annotationId:u}),l.push(u)):d.push(u);let c=o.filter(u=>!l.includes(u.id)).map(Gu);return{actions:a,result:JSON.stringify({deletedCommentIds:l,notFoundCommentIds:d,remainingComments:c},void 0,2)}}case Ju:{let r=n??{},o=CC(r.commentIds,Ju),s=uk(r.resolved),a=Ih(i),l=new Map(a.map(m=>[m.id,m])),d=[],c=[],u=[];for(let m of o){let h=l.get(m);if(!h){u.push(m);continue}let v=Th(h),I={...v,kind:v?.kind??"user",state:s?"resolved":"submitted",sessionResource:v?.sessionResource??t},b={...h,resolved:s,_meta:{...h._meta,[ju]:I}};d.push({type:"annotations/set",annotation:b}),c.push(m)}let p=a.map(m=>c.includes(m.id)?Gu({...m,resolved:s}):Gu(m));return{actions:d,result:JSON.stringify({resolved:s,updatedCommentIds:c,notFoundCommentIds:u,comments:p},void 0,2)}}default:throw new Error(`Unknown feedback server tool: ${e}`)}}var wC={definitions:dk,execute(i,t,e,n){let r=Gc(t),s=i.getSnapshot(r)?.state??{annotations:[]},a=mk(s,t,e,n);for(let l of a.actions)i.dispatchServerAction(r,l);return a.result}};var ws=$("agentHostFileMonitorService"),xh=Object.freeze(["**/.git/lfs/**","**/.git/logs/**","**/.git/objects/**","**/.git/subtree-cache/**","**/.git/**/*.lock","**/.git/**/fsmonitor--daemon/**","**/*.watchman-cookie-*"]);function hk(i){return[...i].sort()}function yk(i){let t=Object.create(null);for(let e of i)t[e]=!0;return _l(t)}var qn=class extends T{constructor(e,n){super();this._fileService=e;this._logService=n;this._entries=this._register(new ve);this._register(this._fileService.onDidFilesChange(r=>this._onDidFilesChange(r))),this._register(this._fileService.onDidWatchError(r=>{this._logService.warn("[AgentHostFileMonitorService] File watcher error",r)}))}static{this._DEFAULT_DEBOUNCE_MS=750}acquire(e,n,r={}){let o=this._canonicalizeFolder(e),s=hk(r.excludes??xh),a=r.debounceMs??qn._DEFAULT_DEBOUNCE_MS,l=this._key(o,s,a),d=this._entries.get(l);if(!d){try{d=this._createEntry(l,o,s,a)}catch(c){this._logService.warn(`[AgentHostFileMonitorService] Failed to watch ${o.toString()}`,c);return}this._entries.set(l,d)}return d.callbacks.add(n),k(()=>{let c=this._entries.get(l);c&&(c.callbacks.delete(n),c.callbacks.size===0&&this._entries.deleteAndDispose(l))})}_createEntry(e,n,r,o){let s=new z;try{let a=s.add(new vt),l=new Set,d=yk(r);return s.add(this._fileService.watch(n,{recursive:!0,excludes:[...r]})),{folder:n,callbacks:l,debounce:a,debounceMs:o,excludeMatcher:d,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 r=this._entries.get(e);!r||r.callbacks.size===0||!n.affects(r.folder)||!this._hasRelevantRawChange(r,n)||(r.debounce.value=$t(()=>{r.debounce.clear();for(let o of[...r.callbacks])try{o()}catch(s){this._logService.warn("[AgentHostFileMonitorService] Folder change callback failed",s)}},r.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 r of n)if(Je.isEqualOrParent(r,e.folder)&&!this._isExcluded(e,r))return!0;return!1}_isExcluded(e,n){let r=Je.basename(n),o=Je.relativePath(e.folder,n);return o!==void 0&&this._matchesExclude(e,o,r)?!0:this._matchesExclude(e,n.path,r)}_matchesExclude(e,n,r){return typeof e.excludeMatcher(n,r)=="string"}_canonicalizeFolder(e){return Je.removeTrailingPathSeparator(Je.normalizePath(e))}_key(e,n,r){return`${Je.getComparisonKey(e)}\0${r}\0${n.join(`
`)}`}};qn=x([C(0,Te),C(1,O)],qn);var wh=class extends vo{constructor(e,n){super();this._create=e;this._destroy=n}createReferencedObject(e){return this._create(e),e}destroyReferencedObject(e){this._destroy(e)}},Yu=class extends T{constructor(e,n,r,o,s,a){super();this._stateManager=e;this._changesets=n;this._configurationService=r;this._fileMonitorService=o;this._gitService=s;this._logService=a;this._watchInterestReferences=this._register(new ve);this._watchInterestCollection=new wh(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 ve);this._rootUris=new Map;this._activeSessionRoots=new Map;this._rootActiveSessions=new Map;this._unresolvedActiveSessions=new Set;this._watchAttachmentSequencer=new nt;this._activeTurnSequencer=new nt}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(xn(e)),this.untrackSessionChanges(Bt(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(oi(e))||this._watchInterestReferences.has(xn(e))||this._watchInterestReferences.has(Bt(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 r;try{r=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(r);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,r){let o=n.toString();if(this._sessionRoot.get(e)===o){this._sessionWorkingDirectory.set(e,r),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,r),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 r=this._rootSessions.get(n);r&&(r.delete(e),r.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 r=[...n].filter(o=>this._hasWatchInterest(o)&&this._sessionRoot.get(o)===e&&!this._activeSessionRoots.has(o)&&!this._unresolvedActiveSessions.has(o)&&!!this._stateManager.getSessionState(o));if(r.length!==0)for(let o of r)this._changesets.refreshBranchChangeset(o),this._changesets.refreshSessionChangeset(o),this._changesets.computeUncommittedChangeset(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 r=this._rootSessions.get(e);if(!r||r.size===0)return;let o=this._fileMonitorService.acquire(n,()=>this._onRootChanged(e),{excludes:xh,debounceMs:750});if(!o){for(let s of r)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 r=n.toString(),o=this._rootActiveSessions.get(r);o||(o=new Set,this._rootActiveSessions.set(r,o)),o.add(e),this._activeSessionRoots.set(e,r),this._rootUris.set(r,n),this._suspendRootWatcher(r),this._sessionRoot.get(e)!==r&&this._releaseSessionRoot(e)}_markSessionInactive(e){let n=this._removeActiveSession(e);if(n){let r=this._rootUris.get(n);r&&this._ensureRootWatcher(n,r)}(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 r=this._rootActiveSessions.get(n);return r&&(r.delete(e),r.size===0&&this._rootActiveSessions.delete(n)),n}async _resolveActivityRepositoryRoot(e){let n=this._getActivityWorkingDirectory(e);if(!n)return;let r;try{r=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(r)}_getActivityWorkingDirectory(e){let n=this._configurationService.getEffectiveWorkingDirectory(e);if(n)return n;let r=Xe(e);if(r)return this._configurationService.getEffectiveWorkingDirectory(r.parentSession.toString())}};var Eh={[Zc]:!0,[bl]:!0,[no]:!0,[Il]:!0},Rs=class extends T{constructor(e,n,r,o,s,a){super();this._stateManager=e;this._changesets=n;this._configurationService=r;this._logService=a;this._pendingBranchRefreshes=new Set;this._pendingUncommittedRefreshes=new Set;this._pendingSessionRefreshes=new Set;this._subscribedTurns=new Map;this._subscribedUncommittedSessions=new Set;this._changesetFileMonitor=this._register(new Yu(this._stateManager,this._changesets,this._configurationService,o,s,this._logService)),this._changesets.setTurnSubscriberProbe((l,d)=>this.hasTurnSubscribers(l,d)),this._changesets.setUncommittedSubscriberProbe(l=>this.hasUncommittedSubscribers(l))}hasTurnSubscribers(e,n){return this._subscribedTurns.get(e)?.has(n)??!1}hasUncommittedSubscribers(e){return this._subscribedUncommittedSessions.has(e)}onSessionCreated(e){this._changesets.registerStaticChangesets(e)}onSessionRestored(e,n){this._changesets.registerStaticChangesets(e),this._changesets.restorePersistedStaticChangesets(e,{branchRaw:n[Zc],sessionRaw:n[bl],legacyRaw:n[Il]}),this._drainPendingRefresh(e),this._changesetFileMonitor.onSessionRestored(e)}onSessionMaterialized(e){this._drainPendingRefresh(e),this._changesetFileMonitor.onSessionMaterialized(e)}onSessionGitStateChanged(e){this._logService.debug(`[ChangesetSessionCoordinator] Git state changed for ${e}; refreshing static changesets. hasWorkingDirectory=${!!this._configurationService.getEffectiveWorkingDirectory(e)}`),this._triggerBranchRefresh(e),this._triggerSessionRefresh(e),this._triggerUncommittedRefresh(e)}onSessionDisposed(e){this._pendingBranchRefreshes.delete(e),this._pendingUncommittedRefreshes.delete(e),this._pendingSessionRefreshes.delete(e),this._subscribedTurns.delete(e),this._subscribedUncommittedSessions.delete(e),this._changesetFileMonitor.onSessionDisposed(e)}onSessionTurnActiveChanged(e,n){this._changesetFileMonitor.onSessionTurnActiveChanged(e,n)}onFirstSubscriber(e){let n=e.toString(),r=Vt(n);if(r?.kind==="branch"){this._triggerBranchRefresh(r.sessionUri),this._changesetFileMonitor.trackSessionChanges(n,r.sessionUri);return}if(r?.kind==="uncommitted"){this._subscribedUncommittedSessions.add(r.sessionUri),this._triggerUncommittedRefresh(r.sessionUri),this._changesetFileMonitor.trackSessionChanges(n,r.sessionUri);return}if(r?.kind==="session"){this._triggerSessionRefresh(r.sessionUri),this._changesetFileMonitor.trackSessionChanges(n,r.sessionUri);return}if(r?.kind==="turn"&&r.turnId!==void 0){let o=this._subscribedTurns.get(r.sessionUri);o||(o=new Set,this._subscribedTurns.set(r.sessionUri,o)),o.add(r.turnId);return}!r&&this._stateManager.getSessionState(n)&&(this._triggerBranchRefresh(n),this._triggerSessionRefresh(n),this._changesetFileMonitor.trackSessionChanges(n,n))}onLastSubscriber(e){let n=e.toString(),r=Vt(n);if(r?.kind==="branch"){this._pendingBranchRefreshes.delete(r.sessionUri),this._changesetFileMonitor.untrackSessionChanges(n);return}if(r?.kind==="uncommitted"){this._pendingUncommittedRefreshes.delete(r.sessionUri),this._subscribedUncommittedSessions.delete(r.sessionUri),this._changesetFileMonitor.untrackSessionChanges(n);return}if(r?.kind==="session"){this._pendingSessionRefreshes.delete(r.sessionUri),this._changesetFileMonitor.untrackSessionChanges(n);return}if(r?.kind==="turn"&&r.turnId!==void 0){let o=this._subscribedTurns.get(r.sessionUri);o&&(o.delete(r.turnId),o.size===0&&this._subscribedTurns.delete(r.sessionUri))}r||this._changesetFileMonitor.untrackSessionChanges(n)}async restoreSessionIfChangesetSubscription(e,n){let r=e.toString(),o=Vt(r);if(o){if(o.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${r}`);this._stateManager.getSessionState(o.sessionUri)||await n(y.parse(o.sessionUri))}}async tryHandleSubscribe(e,n){let r=e.toString(),o=Vt(r);if(!o)return!1;if(o.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${r}`);return await this.restoreSessionIfChangesetSubscription(e,n),o.kind==="turn"&&o.turnId?await this._changesets.computeTurnChangeset(o.sessionUri,o.turnId):o.kind==="compare-turns"&&o.originalTurnId&&o.modifiedTurnId?await this._changesets.computeCompareTurnsChangeset(o.sessionUri,o.originalTurnId,o.modifiedTurnId):this._changesets.registerStaticChangesets(o.sessionUri),!0}getListMetadataKeys(e){if(!(this._stateManager.getSessionState(e)?.summary.changes||this._stateManager.getChangesetState(Bt(e))?.status==="ready"))return Eh}decorateListEntry(e,n){let r=e.session.toString();if(this._stateManager.getSessionState(r))return e;let o=n[no];if(o!==void 0){let p;try{p=JSON.parse(o)}catch{}return{...e,changes:p}}let s=this._stateManager.getChangesetState(Bt(r)),a=I_(s);if(a)return this._changesets.persistChangesSummary(r,a),{...e,changes:a};let l=n[bl],d=n[Il];if(l===void 0&&d===void 0)return e;let c=this._changesets.parsePersistedStaticChangesets(r,{sessionRaw:l,legacyRaw:d}),u=__(c.session);return u?(this._changesets.persistChangesSummary(r,u),{...e,changes:u}):e}_triggerBranchRefresh(e){if(!this._configurationService.getEffectiveWorkingDirectory(e)){this._pendingBranchRefreshes.add(e);return}this._changesets.refreshBranchChangeset(e)}_triggerUncommittedRefresh(e){if(!this._configurationService.getEffectiveWorkingDirectory(e)){this._pendingUncommittedRefreshes.add(e);return}this._changesets.computeUncommittedChangeset(e)}_triggerSessionRefresh(e){if(!this._configurationService.getEffectiveWorkingDirectory(e)){this._pendingSessionRefreshes.add(e);return}this._changesets.refreshSessionChangeset(e)}_drainPendingRefresh(e){this._pendingBranchRefreshes.delete(e)&&this._triggerBranchRefresh(e),this._pendingUncommittedRefreshes.delete(e)&&this._triggerUncommittedRefresh(e),this._pendingSessionRefreshes.delete(e)&&this._triggerSessionRefresh(e)}};Rs=x([C(1,ui),C(2,$e),C(3,ws),C(4,tt),C(5,O)],Rs);var vk=60,Sk=vk*60,Ph=Sk*24,TX=Ph*7,xX=Ph*30,wX=Ph*365;function RC(i){return i.getFullYear()+"-"+String(i.getMonth()+1).padStart(2,"0")+"-"+String(i.getDate()).padStart(2,"0")+"T"+String(i.getHours()).padStart(2,"0")+":"+String(i.getMinutes()).padStart(2,"0")+":"+String(i.getSeconds()).padStart(2,"0")+"."+(i.getMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"}var Qu={DateTimeFormat(i,t){return new Le(()=>{try{return new Intl.DateTimeFormat(i,t)}catch{return new Intl.DateTimeFormat(void 0,t)}})},Collator(i,t){return new Le(()=>{try{return new Intl.Collator(i,t)}catch{return new Intl.Collator(void 0,t)}})},Segmenter(i,t){return new Le(()=>{try{return new Intl.Segmenter(i,t)}catch{return new Intl.Segmenter(void 0,t)}})},Locale(i,t){return new Le(()=>{try{return new Intl.Locale(i,t)}catch{return new Intl.Locale(Br,t)}})},NumberFormat(i,t){return new Le(()=>{try{return new Intl.NumberFormat(i,t)}catch{return new Intl.NumberFormat(void 0,t)}})}};var EC=new Le(()=>{let i=Qu.Collator(void 0,{numeric:!0,sensitivity:"base"}).value;return{collator:i,collatorIsNumeric:i.resolvedOptions().numeric}}),kX=new Le(()=>({collator:Qu.Collator(void 0,{numeric:!0}).value})),DX=new Le(()=>({collator:Qu.Collator(void 0,{numeric:!0,sensitivity:"accent"}).value}));function bk(i,t,e=!1){let n=i||"",r=t||"",o=EC.value.collator.compare(n,r);return EC.value.collatorIsNumeric&&o===0&&n!==r?n<r?-1:1:o}function Xu(i,t,e){let n=i.toLowerCase(),r=t.toLowerCase(),o=Ik(i,t,e);if(o)return o;let s=n.endsWith(e),a=r.endsWith(e);if(s!==a)return s?-1:1;let l=bk(n,r);return l!==0?l:n.localeCompare(r)}function Ik(i,t,e){let n=i.toLowerCase(),r=t.toLowerCase(),o=n.startsWith(e),s=r.startsWith(e);if(o!==s)return o?-1:1;if(o&&s){if(n.length<r.length)return-1;if(n.length>r.length)return 1}return 0}var MX=new Uint32Array(10);var LX=new Uint8Array([114,82,115,101,69,102,97,113,81,116,84,100,119,87,99,122,120,118,103]),NX=new Uint16Array([107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]),UX=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]),FX=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 AC(...i){return function(t,e){for(let n=0,r=i.length;n<r;n++){let o=i[n](t,e);if(o)return o}return null}}var KX=kC.bind(void 0,!1),ep=kC.bind(void 0,!0);function kC(i,t,e){if(!e||e.length<t.length)return null;let n;return i?n=jr(e,t):n=e.indexOf(t)===0,n?t.length>0?[{start:0,end:t.length}]:[]:null}function _k(i,t){if(i.length>t.length)return null;let e=t.toLowerCase().indexOf(i.toLowerCase());return e===-1?null:[{start:e,end:e+i.length}]}function Ck(i,t){return i.length>t.length?null:Ah(i.toLowerCase(),t.toLowerCase(),0,0)}function Ah(i,t,e,n){if(e===i.length)return[];if(n===t.length)return null;if(i[e]===t[n]){let r=null;return(r=Ah(i,t,e+1,n+1))?OC({start:n,end:n+1},r):null}return Ah(i,t,e,n+1)}function Dh(i){return 97<=i&&i<=122}function Es(i){return 65<=i&&i<=90}function Oh(i){return 48<=i&&i<=57}function Tk(i){return i===32||i===9||i===10||i===13}var xk=new Set;"()[]{}<>`'\"-/;:,.?!".split("").forEach(i=>xk.add(i.charCodeAt(0)));function DC(i){return Dh(i)||Es(i)||Oh(i)}function OC(i,t){return t.length===0?t=[i]:i.end===t[0].start?t[0].start=i.start:t.unshift(i),t}function MC(i,t){for(let e=t;e<i.length;e++){let n=i.charCodeAt(e);if(Es(n)||Oh(n)||e>0&&!DC(i.charCodeAt(e-1)))return e}return i.length}function kh(i,t,e,n){if(e===i.length)return[];if(n===t.length)return null;if(i[e]!==t[n].toLowerCase())return null;{let r=null,o=n+1;for(r=kh(i,t,e+1,n+1);!r&&(o=MC(t,o))<t.length;)r=kh(i,t,e+1,o),o++;return r===null?null:OC({start:n,end:n+1},r)}}function wk(i){let t=0,e=0,n=0,r=0,o=0;for(let c=0;c<i.length;c++)o=i.charCodeAt(c),Es(o)&&t++,Dh(o)&&e++,DC(o)&&n++,Oh(o)&&r++;let s=t/i.length,a=e/i.length,l=n/i.length,d=r/i.length;return{upperPercent:s,lowerPercent:a,alphaPercent:l,numericPercent:d}}function Rk(i){let{upperPercent:t,lowerPercent:e}=i;return e===0&&t>.6}function Ek(i){let{upperPercent:t,lowerPercent:e,alphaPercent:n,numericPercent:r}=i;return e>.2&&t<.8&&n>.6&&r<.2}function Pk(i){let t=0,e=0,n=0,r=0;for(let o=0;o<i.length;o++)n=i.charCodeAt(o),Es(n)&&t++,Dh(n)&&e++,Tk(n)&&r++;return(t===0||e===0)&&r===0?i.length<=30:t<=5}function LC(i,t){if(!t||(t=t.trim(),t.length===0)||!Pk(i))return null;t.length>60&&(t=t.substring(0,60));let e=wk(t);if(!Ek(e)){if(!Rk(e))return null;t=t.toLowerCase()}let n=null,r=0;for(i=i.toLowerCase();r<t.length&&(n=kh(i,t,0,r))===null;)r=MC(t,r+1);return n}var GX=AC(ep,LC,_k),JX=AC(ep,LC,Ck),YX=new On(1e4);var Zu=128;function Mh(){let i=[],t=[];for(let e=0;e<=Zu;e++)t[e]=0;for(let e=0;e<=Zu;e++)i.push(t.slice(0));return i}function NC(i){let t=[];for(let e=0;e<=i;e++)t[e]=0;return t}var QX=NC(2*Zu),XX=NC(2*Zu),ZX=Mh(),eZ=Mh(),tZ=Mh();var Ak;(e=>{e.Default=[-100,0];function t(n){return!n||n.length===2&&n[0]===-100&&n[1]===0}e.isDefault=t})(Ak||={});var PC=class{constructor(t,e){this.firstMatchCanBeWeak=t;this.boostFullMatch=e}static{this.default={boostFullMatch:!0,firstMatchCanBeWeak:!1}}};var np=0,UC=[np,[]];function FC(i,t,e,n){if(!i||!t)return UC;let r=i.length,o=t.length;if(r<o)return UC;let s=i.toLowerCase();return kk(t,e,o,i,s,r,n)}function kk(i,t,e,n,r,o,s){let a=[],l=[];for(let p=0;p<e;p++){let m=p*o,h=m-o,v=p>0,I=i[p],b=t[p];for(let S=0;S<o;S++){let _=S>0,R=m+S,P=R-1,q=h+S-1,E=_?a[P]:0,L=v&&_?a[q]:0,U=v&&_?l[q]:0,J;!L&&v?J=0:J=Dk(I,b,n,r,S,U),J&&L+J>=E&&(s||v||r.startsWith(t,S))?(l[R]=U+1,a[R]=L+J):(l[R]=np,a[R]=E)}}let d=[],c=e-1,u=o-1;for(;c>=0&&u>=0;){let p=c*o+u;l[p]===np||(d.push(u),c--),u--}return[a[e*o-1],d.reverse()]}function Dk(i,t,e,n,r,o){let s=0;if(!Ok(t,n[r]))return s;if(s+=1,o>0&&(s+=Math.min(o,3)*6+Math.max(0,o-3)*3),i===e[r]&&(s+=1),r===0)s+=8;else{let a=Mk(e.charCodeAt(r-1));a?s+=a:Es(e.charCodeAt(r))&&o===0&&(s+=2)}return s}function Ok(i,t){return i===t?!0:i==="/"||i==="\\"?t==="/"||t==="\\":!1}function Mk(i){switch(i){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 rp=Object.freeze({score:0}),tp=1<<18,Lh=1<<17,Nh=65536;function Lk(i,t,e,n){let r=n.values?n.values:[n];return rn({[n.normalized]:{values:r.map(s=>({value:s.normalized,expectContiguousMatch:s.expectContiguousMatch})),label:i,description:t,allowNonContiguousMatches:e}})}function ip(i,t,e,n,r){if(!i||!t.normalized)return rp;let o=n.getItemLabel(i);if(!o)return rp;let s=n.getItemDescription(i),a=Lk(o,s,e,t),l=r[a];if(l)return l;let d=Nk(o,s,n.getItemPath(i),t,e);return r[a]=d,d}function Nk(i,t,e,n,r){let o=!e||!n.containsPathSeparator;return e&&(Se?n.pathNormalized===e:dr(n.pathNormalized,e))?{score:tp,labelMatch:[{start:0,end:i.length}],descriptionMatch:t?[{start:0,end:t.length}]:void 0}:n.values&&n.values.length>1?Uk(i,t,e,n.values,o,r):VC(i,t,e,n,o,r)}function Uk(i,t,e,n,r,o){let s=0,a=[],l=[];for(let d of n){let{score:c,labelMatch:u,descriptionMatch:p}=VC(i,t,e,d,r,o);if(c===np)return rp;s+=c,u&&a.push(...u),p&&l.push(...p)}return{score:s,labelMatch:$C(a),descriptionMatch:$C(l)}}function VC(i,t,e,n,r,o){if(r||!t){let[s,a]=FC(i,n.normalized,n.normalizedLowercase,o&&!n.expectContiguousMatch);if(s){let l=ep(n.normalized,i),d;if(l){d=Lh;let c=Math.round(n.normalized.length/i.length*100);d+=c}else d=Nh;return{score:d+s,labelMatch:l||WC(a)}}}if(t){let s=t;e&&(s=`${t}${be}`);let a=s.length,l=`${s}${i}`,[d,c]=FC(l,n.normalized,n.normalizedLowercase,o&&!n.expectContiguousMatch);if(d){let u=WC(c),p=[],m=[];return u.forEach(h=>{h.start<a&&h.end>a?(p.push({start:0,end:h.end-a}),m.push({start:h.start,end:a})):h.start>=a?p.push({start:h.start-a,end:h.end-a}):m.push(h)}),{score:d,labelMatch:p,descriptionMatch:m}}}return rp}function WC(i){let t=[];if(!i)return t;let e;for(let n of i)e&&e.end===n?e.end+=1:(e={start:n,end:n+1},t.push(e));return t}function $C(i){let t=i.sort((r,o)=>r.start-o.start),e=[],n;for(let r of t)!n||!Fk(n,r)?(n=r,e.push(r)):(n.start=Math.min(n.start,r.start),n.end=Math.max(n.end,r.end));return e}function Fk(i,t){return!(i.end<t.start||t.end<i.start)}function zC(i,t,e,n,r,o){let s=ip(i,e,n,r,o),a=ip(t,e,n,r,o),l=s.score,d=a.score;if((l===tp||d===tp)&&l!==d)return l===tp?-1:1;if(l>Nh||d>Nh){if(l!==d)return l>d?-1:1;if(l<Lh&&d<Lh){let I=Wk(s.labelMatch,a.labelMatch);if(I!==0)return I}let h=r.getItemLabel(i)||"",v=r.getItemLabel(t)||"";if(h.length!==v.length)return h.length-v.length}if(l!==d)return l>d?-1:1;let c=Array.isArray(s.labelMatch)&&s.labelMatch.length>0,u=Array.isArray(a.labelMatch)&&a.labelMatch.length>0;if(c&&!u)return-1;if(u&&!c)return 1;let p=HC(i,s,r),m=HC(t,a,r);return p&&m&&p!==m?m>p?-1:1:$k(i,t,e,r)}function HC(i,t,e){let n=-1,r=-1;if(t.descriptionMatch?.length?n=t.descriptionMatch[0].start:t.labelMatch?.length&&(n=t.labelMatch[0].start),t.labelMatch?.length){if(r=t.labelMatch[t.labelMatch.length-1].end,t.descriptionMatch?.length){let o=e.getItemDescription(i);o&&(r+=o.length)}}else t.descriptionMatch?.length&&(r=t.descriptionMatch[t.descriptionMatch.length-1].end);return r-n}function Wk(i,t){if(!i&&!t||!i?.length&&!t?.length)return 0;if(!t?.length)return-1;if(!i?.length)return 1;let e=i[0].start,r=i[i.length-1].end-e,o=t[0].start,a=t[t.length-1].end-o;return r===a?0:a<r?1:-1}function $k(i,t,e,n){let r=n.getItemLabel(i)||"",o=n.getItemLabel(t)||"",s=n.getItemDescription(i),a=n.getItemDescription(t),l=r.length+(s?s.length:0),d=o.length+(a?a.length:0);if(l!==d)return l-d;let c=n.getItemPath(i),u=n.getItemPath(t);return c&&u&&c.length!==u.length?c.length-u.length:r!==o?Xu(r,o,e.normalized):s&&a&&s!==a?Xu(s,a,e.normalized):c&&u&&c!==u?Xu(c,u,e.normalized):0}function qC(i){return i.startsWith('"')&&i.endsWith('"')}var Hk=" ";function jC(i){typeof i!="string"&&(i="");let t=i.toLowerCase(),{pathNormalized:e,normalized:n,normalizedLowercase:r}=BC(i),o=e.indexOf(be)>=0,s=qC(i),a,l=i.split(Hk);if(l.length>1)for(let d of l){let c=qC(d),{pathNormalized:u,normalized:p,normalizedLowercase:m}=BC(d);p&&(a||(a=[]),a.push({original:d,originalLowercase:d.toLowerCase(),pathNormalized:u,normalized:p,normalizedLowercase:m,expectContiguousMatch:c}))}return{original:i,originalLowercase:t,pathNormalized:e,normalized:n,normalizedLowercase:r,values:a,containsPathSeparator:o,expectContiguousMatch:s}}function BC(i){let t;G?t=i.replace(/\//g,be):t=i.replace(/\\/g,be);let e=t.replace(/[\*\u2026\s"]/g,"").replace(/(?<=.)#$/,"");return{pathNormalized:t,normalized:e,normalizedLowercase:e.toLowerCase()}}var KC=50;function qk(i,t){if(!(t<0||t>i.length))for(let e=t-1;e>=0;e--){let n=i.charCodeAt(e);if(n===32||n===9||n===10||n===13)return;if(i[e]==="@"||i[e]==="#"){if(e>0){let r=i.charCodeAt(e-1);if(!(r===32||r===9||r===10||r===13))return}return{token:i.slice(e+1,t),triggerChar:i[e],rangeStart:e,rangeEnd:t}}}}var Uh=class{constructor(t){this._workingDirectory=t}getItemLabel(t){return pe(t)}getItemDescription(t){let e=Rg(this._workingDirectory,t);if(!e)return;let n=e.lastIndexOf("/");return n>0?e.slice(0,n):void 0}getItemPath(t){return Rg(this._workingDirectory,t)??t.fsPath}},op=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 r=y.parse(n);if(r.scheme!==ie.file)return[];let o=qk(t.text,t.offset);if(!o)return[];let s;try{s=await this._workspaceFiles.getFiles(r,e)}catch(u){if(Zn(u))return[];throw u}if(e.isCancellationRequested||s.length===0)return[];let a=new Uh(r),l=jC(o.token),d=Object.create(null),c;if(!l.normalized)c=s.slice(0,KC);else{let u=s.filter(p=>ip(p,l,!0,a,d).score>0);u.sort((p,m)=>zC(p,m,l,!0,a,d)),c=u.slice(0,KC)}return c.map(u=>{let p=pe(u);return{insertText:o.triggerChar+p,rangeStart:o.rangeStart,rangeEnd:o.rangeEnd,attachment:{type:"resource",uri:u.toString(),label:p,displayKind:"document"}}})}};var sp=class extends T{constructor(e){super();this._getAgent=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(e,n){let r=C_(e.text,e.offset);if(!r)return[];let o=typeof e.channel=="string"?y.parse(e.channel):e.channel,s=this._getAgent(o);if(!s)return[];let a=await this._getCandidates(s,o);if(n.isCancellationRequested||a.length===0)return[];let l=r.typed,d=new Set;return a.filter(c=>{let u=c.uri.toString();return(!l.length||c.name.startsWith(l))&&!d.has(u)?(d.add(u),!0):!1}).map(c=>({insertText:"/"+c.name+" ",rangeStart:r.rangeStart,rangeEnd:r.rangeEnd,attachment:{type:"simple",label:"/"+c.name,_meta:{uri:c.uri.toString(),name:c.name,displayName:c.name,...c.description!==void 0?{description:c.description}:{}}}}))}async _getCandidates(e,n){if(!e.getSessionCustomizations)return[];let r=await e.getSessionCustomizations(n),o=[];for(let s of r)if(!(s.type==="mcpServer"||!s.enabled||!s.children))for(let a of s.children)a.type==="skill"&&o.push(a);return o}};import*as GC from"child_process";var Bk=new Le(async()=>(await import("@vscode/ripgrep-universal")).rgPath.replace(/\bnode_modules\.asar\b/,"node_modules.asar.unpacked"));function Ps(){return Bk.value}var Vk=5e4,zk=3e4,As=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!==ie.file)return[];let r=e.toString(),o=Date.now(),s=this._cache.get(r),a;if(s&&s.expiresAt>o)a=s.promise;else{a=this._enumerate(e);let l={promise:a,expiresAt:o+zk};this._cache.set(r,l),a.catch(()=>{this._cache.get(r)===l&&this._cache.delete(r)})}if(n.isCancellationRequested)throw new K;return n===Ee.None?a:new Promise((l,d)=>{let c=n.onCancellationRequested(()=>{c.dispose(),d(new K)});a.then(u=>{c.dispose(),l(u)},u=>{c.dispose(),d(u)})})}async _enumerate(e){let n=await Ps();return new Promise(r=>{let o=e.fsPath,s=["--files","--hidden","--no-require-git","--follow","--no-config","--glob","!.git"],a;try{a=GC.spawn(n,s,{cwd:o})}catch(h){this._logService.warn(`[AgentHostWorkspaceFiles] Failed to spawn ripgrep: ${h}`),r([]);return}this._activeChildren.add(a);let l=[],d="",c=!1,u=!1,p=h=>{u||(u=!0,this._activeChildren.delete(a),r(h))};a.stdout.setEncoding("utf8"),a.stdout.on("data",h=>{if(c)return;d+=h;let v;for(;(v=d.indexOf(`
`))>=0;){let I=d.slice(0,v).replace(/\r$/,"");if(d=d.slice(v+1),!!I&&(l.push(y.joinPath(e,I)),l.length>=Vk)){c=!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}`),p([])}),a.on("close",()=>{if(!c&&d.length>0){let h=d.replace(/\r$/,"");h&&l.push(y.joinPath(e,h)),d=""}m&&this._logService.trace(`[AgentHostWorkspaceFiles] ripgrep stderr: ${m}`),p(l)})})}};As=x([C(0,O)],As);var JC={serverTools:{listChanged:!0},serverResources:{},sampling:{}},ap={capabilities:JC};var lp=class extends T{constructor(e){super();this._options=e;this._live=new Map}topLevelCustomizations(){let e=[];for(let n of this._live.values())n.topLevelId!==void 0&&e.push(this._buildTopLevel(n.topLevelId,n.serverName,n.state));return e}readyChannels(){let e=[];for(let n of this._live.values()){if(n.state.kind!=="ready")continue;let r=this._buildChannel(n.serverName,n.state);r!==void 0&&e.push({serverName:n.serverName,channel:r})}return e}customizationIdForServer(e){let n=this._live.get(e);return n?.topLevelId!==void 0?n.topLevelId:this._options.resolveChildId(e)}channelForServer(e){let n=this._live.get(e);if(!(!n||n.state.kind!=="ready"))return this._buildChannel(e,n.state)}applyAll(e){let n=new Set;for(let r of e)n.add(r.name),this.applyOne(r);for(let r of[...this._live.keys()])n.has(r)||this.remove(r)}applyOne(e){let r=this._live.get(e.name)?.topLevelId;if(r===void 0){let o=this._options.resolveChildId(e.name);if(o!==void 0){this._live.set(e.name,{serverName:e.name,state:e.state,topLevelId:void 0}),this._options.emit({type:"session/mcpServerStateChanged",id:o,state:e.state,channel:this._buildChannel(e.name,e.state)});return}r=this._mintTopLevelId(e.name)}this._live.set(e.name,{serverName:e.name,state:e.state,topLevelId:r}),this._options.emit({type:"session/customizationUpdated",customization:this._buildTopLevel(r,e.name,e.state)})}remove(e){let n=this._live.get(e);if(!n)return;if(this._live.delete(e),n.topLevelId!==void 0){this._options.emit({type:"session/customizationRemoved",id:n.topLevelId});return}let r=this._options.resolveChildId(e);r!==void 0&&this._options.emit({type:"session/mcpServerStateChanged",id:r,state:{kind:"stopped"}})}_mintTopLevelId(e){return`mcp-top-level:${this._options.providerId}:${this._options.sessionId}:${e}`}_buildChannel(e,n){if(n.kind==="ready")return`mcp://${this._options.providerId}/${encodeURIComponent(this._options.sessionId)}/${encodeURIComponent(e)}`}_buildTopLevel(e,n,r){let o=this._buildChannel(n,r),s=this._options.capabilities?{capabilities:this._options.capabilities}:ap;return{type:"mcpServer",id:e,uri:this._mintTopLevelId(n),name:n,enabled:!0,state:r,channel:o,mcpApp:s}}};function QC(i,t){for(let e of i){if(e.type==="mcpServer"){if(e.name===t)return e.id;continue}let n=e.children;if(n){for(let r of n)if(r.type==="mcpServer"&&r.name===t)return r.id}}}function XC(i){let t="mcp://";if(!i.startsWith(t))return;let e=i.slice(t.length),n=e.indexOf("/");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1),s=o.indexOf("/");if(s<=0||s===o.length-1)return;let a,l;try{a=decodeURIComponent(o.slice(0,s)),l=decodeURIComponent(o.slice(s+1))}catch{return}if(!(!r||!a||!l))return{providerId:r,sessionId:a,serverName:l}}var Fh="vscode-agent-client";function ks(i,t){let e=i.authority||"-",n=i.path.length>0&&!i.path.startsWith("/"),r=n?`${i.scheme}!`:i.scheme,o=n?`/${i.path}`:i.path;return y.from({scheme:Fh,authority:t,path:`/${r}/${e}${o}`,query:i.query||void 0,fragment:i.fragment||void 0})}function ZC(i){let t=i.path,e=i.query||void 0,n=i.fragment||void 0,r=t.indexOf("/",1);if(r===-1)return y.from({scheme:"file",path:t,query:e,fragment:n});let o=t.substring(1,r),s=o.endsWith("!");s&&(o=o.substring(0,o.length-1));let a=t.indexOf("/",r+1);if(a===-1){let c=t.substring(r+1);return y.from({scheme:o,authority:c==="-"?"":c,path:"/",query:e,fragment:n})}let l=t.substring(r+1,a);l==="-"&&(l="");let d=t.substring(a);return s&&(d=d.substring(1)),y.from({scheme:o,authority:l||void 0,path:d,query:e,fragment:n})}var dp=class extends T{constructor(e,n){super();this._stateManager=e;this._sessionGitStateService=n;this._handlerRegistrations=this._register(new ve);this._changesetOperationHandlers=new Map;this._inFlightOperations=new Map;this._registry={registerChangesetOperationHandler:(r,o)=>this._registerChangesetOperationHandler(r,o),onDidChangeOperations:r=>this.refreshOperationsFromCurrentState(r),refreshSessionGitState:r=>this._refreshSessionGitStateAndOperations(r)}}registerContribution(e){if(this._handlerRegistrations.has(e))throw new Error("Changeset operation contribution already registered");return this._handlerRegistrations.set(e,e.registerHandlers(this._registry)),k(()=>{this._handlerRegistrations.deleteAndDispose(e),e.dispose()})}getOperations(e){let n=[];for(let r of this._handlerRegistrations.keys()){let o=r.getOperations(e);o&&n.push(...o)}return n.length>0?n:void 0}refreshOperationsFromCurrentState(e){let n=hn(this._stateManager.getSessionState(e)?._meta);n&&this.updateOperations(e,n)}updateOperations(e,n){this._updateOperationsForChangeset(e,Bt(e),"session",n),this._updateOperationsForChangeset(e,xn(e),"uncommitted",n)}_updateOperationsForChangeset(e,n,r,o){let s=this.getOperations({sessionKey:e,changesetUri:n,changesetKind:r,gitState:o});this._stateManager.dispatchServerAction(n,{type:"changeset/operationsChanged",operations:s?[...s]:void 0})}async _refreshSessionGitStateAndOperations(e){let n=await this._sessionGitStateService.refreshSessionGitState(e);n&&this.updateOperations(e,n)}async invokeChangesetOperation(e){let n=this._stateManager.getChangesetState(e.channel);if(!n)throw new D(At,`Changeset not found: ${e.channel}`);let r=n.operations?.find(c=>c.id===e.operationId);if(!r)throw new D(fe.InvalidParams,`Unknown operation '${e.operationId}' on changeset ${e.channel}`);let o=e.target?.kind==="resource"?"resource":e.target?.kind==="range"?"range":"changeset";if(!r.scopes.includes(o))throw new D(fe.InvalidParams,`Operation '${e.operationId}' does not support scope '${o}' (allowed: ${r.scopes.join(", ")})`);let s=this._changesetOperationHandlers.get(e.operationId);if(!s)throw new D(fe.InternalError,`No operation handler registered for '${e.operationId}' on changeset ${e.channel}`);let a=`${e.channel}\0${e.operationId}\0${JSON.stringify(e.target??null)}`,l=this._inFlightOperations.get(a);if(l)return l;let d=s.invoke(e,Ee.None).finally(()=>{this._inFlightOperations.get(a)===d&&this._inFlightOperations.delete(a)});return this._inFlightOperations.set(a,d),d}_registerChangesetOperationHandler(e,n){if(this._changesetOperationHandlers.has(e))throw new Error(`Changeset operation handler already registered for '${e}'`);return this._changesetOperationHandlers.set(e,n),k(()=>{this._changesetOperationHandlers.get(e)===n&&this._changesetOperationHandlers.delete(e)})}};var jk=2e4,hi=class{constructor(t,e,n,r,o,s,a){this._getSessionState=t;this._onCommitted=e;this._agentService=n;this._gitService=r;this._copilotApiService=o;this._changesets=s;this._logService=a}static{this.OPERATION_COMMIT="commit"}async invoke(t,e){let n=new AbortController;e.isCancellationRequested&&n.abort();let r=e.onCancellationRequested(()=>n.abort());try{return await this._invoke(t,e,n.signal)}finally{r.dispose()}}async _invoke(t,e,n){let r=Vt(t.channel);if(!r||r.kind!=="uncommitted")throw new D(fe.InvalidParams,`Not an uncommitted changeset URI: ${t.channel}`);this._throwIfCancelled(e);let o=r.sessionUri,s=this._getSessionState(o);if(!s)throw new D(At,`Session not found: ${o}`);let a=s.summary.workingDirectory;if(!a)throw new D(fe.InternalError,`Session has no working directory: ${o}`);let l=y.parse(a),d=hn(s._meta);if(!d)throw new D(fe.InternalError,`Session's working directory is not a git repo: ${o}`);if(!await this._gitService.hasUncommittedChanges(l))return{message:{markdown:g(1922,null)}};this._throwIfCancelled(e);let u=this._agentService.getAuthToken({resource:St.resource,scopes:St.scopes_supported});if(!u)throw new D(on,g(1917,null),[St]);let p=await this._gitService.computeSessionFileDiffs(l,{sessionUri:o});if(!p||p.length===0)throw new D(fe.InternalError,g(1920,null));this._throwIfCancelled(e);let m;try{m=this._cleanCommitMessage(await this._copilotApiService.utilityChatCompletion(u,{messages:this._buildCommitMessagePrompt(l,d.branchName,p)},{signal:n}))}catch(h){throw this._throwIfCancelled(e),this._isAuthFailure(h)?new D(on,g(1916,null),[St]):h}if(!m)throw new D(fe.InternalError,g(1921,null));this._throwIfCancelled(e),this._logService.info(`[AgentHostCommitOperationHandler] Committing uncommitted changes for session ${o}`);try{await this._gitService.commitAll(l,m)}catch(h){throw this._throwIfCancelled(e),new D(fe.InternalError,`Failed to commit changes: ${h instanceof Error?h.message:String(h)}`)}try{await this._onCommitted(o)}catch(h){this._logService.warn(`[AgentHostCommitOperationHandler] Post-commit refresh failed for session ${o}: ${h instanceof Error?h.message:String(h)}`)}return this._changesets.refreshBranchChangeset(o),this._changesets.refreshSessionChangeset(o),this._changesets.computeUncommittedChangeset(o),{message:{markdown:g(1919,null,m.split(`
`)[0])}}}_buildCommitMessagePrompt(t,e,n){let r=this._summarizeDiffsForPrompt(n);return[{role:"system",content:["You generate concise Git commit messages.","Return only the commit message text, with no markdown or code fences.","Use imperative mood. Keep the subject line under 72 characters.","Add a body only when it helps explain multiple related changes."].join(" ")},{role:"user",content:[`Repository: ${pe(t)}`,`Branch: ${e??"unknown"}`,"Changed files:",r].join(`
`)}]}_summarizeDiffsForPrompt(t){let e=[];for(let n of t){let r=n.before?.uri,o=n.after?.uri,s=o??r??"(unknown)",a="Edit";if(!r&&o?a="Create":r&&!o?a="Delete":r&&o&&r!==o&&(a="Rename"),e.push(`- ${a}: ${this._displayUri(s)} (+${n.diff?.added??0} -${n.diff?.removed??0})`),e.join(`
`).length>jk){e.push("[file list truncated]");break}}return e.join(`
`)}_displayUri(t){try{let e=y.parse(t);return e.scheme==="file"?e.fsPath:e.path||t}catch{return t}}_cleanCommitMessage(t){let e=t.trim().replace(/\r\n/g,`
`),n=/^```(?:text|gitcommit)?\s*([\s\S]*?)\s*```$/i.exec(e);return n&&(e=n[1].trim()),e}_isAuthFailure(t){if(t instanceof Pn)return t.status===401||t.status===403;let e=t instanceof Error?t.message:String(t);return/\b(401|403)\b/.test(e)&&/\b(auth|authorization|unauthorized|forbidden|token|copilot endpoint discovery|copilot session token mint)\b/i.test(e)}_throwIfCancelled(t){if(t.isCancellationRequested)throw new D(fe.InternalError,g(1918,null))}};hi=x([C(2,ti),C(3,tt),C(4,Kt),C(5,ui),C(6,O)],hi);var Ds=class extends T{constructor(e,n){super();this._stateManager=e;this._instantiationService=n}registerHandlers(e){this._registry=e;let n=new z,r=s=>this._stateManager.getSessionState(s),o=this._instantiationService.createInstance(hi,r,s=>this._onCommitted(s));return n.add(e.registerChangesetOperationHandler(hi.OPERATION_COMMIT,o)),n.add({dispose:()=>{this._registry=void 0}}),n}getOperations({changesetKind:e,gitState:n}){if(!(e!=="uncommitted"||(n.uncommittedChanges??0)<=0))return[{id:hi.OPERATION_COMMIT,label:g(1923,null),scopes:["changeset"],icon:"git-commit",status:"idle"}]}async _onCommitted(e){this._registry?.onDidChangeOperations(e),await this._registry?.refreshSessionGitState(e)}};Ds=x([C(1,ke)],Ds);var cp=$("agentHostOctoKitService"),Kk="https://api.github.com",Gk="2022-11-28",eT=500,Os=class{constructor(t,e){this._logService=e;this._fetch=t??globalThis.fetch}async createPullRequest(t,e,n,r,o,s,a,l,d){let c=await this._makeGHAPIRequest(`repos/${t}/${e}/pulls`,"POST",l,d,{title:n,body:r,head:o,base:s,draft:a}),u=c?.html_url,p=c?.number;if(typeof u!="string"||typeof p!="number")throw new Error(`Failed to create pull request for ${t}/${e}`);return{url:u,number:p}}async findPullRequestByHeadBranch(t,e,n,r,o){let s=await this._makeGHAPIRequest(`repos/${t}/${e}/pulls?head=${encodeURIComponent(`${t}:${n}`)}&state=all&sort=updated&direction=desc&per_page=1`,"GET",r,o);if(!Array.isArray(s)||s.length===0)return;let a=s[0],l=a?.html_url,d=a?.number;return typeof l=="string"&&typeof d=="number"?{url:l,number:d}:void 0}async _makeGHAPIRequest(t,e,n,r,o){let s=`${Kk}/${t}`,a={Accept:"application/vnd.github+json",Authorization:`Bearer ${n}`,"X-GitHub-Api-Version":Gk};o&&(a["Content-Type"]="application/json");let l;try{l=await this._fetch(s,{method:e,headers:a,body:o?JSON.stringify(o):void 0,signal:r})}catch(d){throw r.aborted||this._logService.error(`[AgentHostOctoKit] ${e} ${s} - Network error`,d),d}if(!l.ok){let d=await l.text().catch(()=>{}),c=this._formatErrorResponseBody(d);throw this._logService.error(`[AgentHostOctoKit] ${e} ${s} - Status: ${l.status}${c?` - ${c}`:""}`),new Error(`GitHub API request failed: ${e} ${t} - ${l.status} ${l.statusText}${c?` - ${c}`:""}`)}try{return await l.json()}catch(d){throw this._logService.error(`[AgentHostOctoKit] ${e} ${s} - Failed to parse JSON`,d),d}}_formatErrorResponseBody(t){let e=t?.replace(/\s+/g," ").trim();if(e)return e.length>eT?`${e.substring(0,eT)}...`:e}};Os=x([C(1,O)],Os);var kr=class{constructor(t,e,n,r,o,s,a){this._draft=t;this._getSessionState=e;this._onPullRequestCreated=n;this._agentService=r;this._gitService=o;this._octoKitService=s;this._logService=a}static{this.OPERATION_CREATE_PR="create-pr"}static{this.OPERATION_CREATE_DRAFT_PR="create-draft-pr"}async invoke(t,e){let n=new AbortController;e.isCancellationRequested&&n.abort();let r=e.onCancellationRequested(()=>n.abort());try{return await this._invoke(t,e,n.signal)}finally{r.dispose()}}async _invoke(t,e,n){let r=Vt(t.channel);if(!r)throw new D(fe.InvalidParams,`Not a changeset URI: ${t.channel}`);this._throwIfCancelled(e);let o=r.sessionUri,s=this._getSessionState(o);if(!s)throw new D(At,`Session not found: ${o}`);let a=s.summary.workingDirectory;if(!a)throw new D(fe.InternalError,`Session has no working directory: ${o}`);let l=y.parse(a),d=hn(s._meta);if(!d?.hasGitHubRemote||!d.githubOwner||!d.githubRepo)throw new D(fe.InternalError,`Session's working directory is not a GitHub-backed git repo: ${o}`);let c=d.branchName??await this._gitService.getCurrentBranch(l);if(!c)throw new D(fe.InternalError,`Could not determine current branch for ${l}`);let u=d.baseBranchName??await this._gitService.getDefaultBranch(l);if(!u)throw new D(fe.InternalError,`Could not determine base branch for ${l}`);let p=u.startsWith("origin/")?u.substring(7):u,m=this._agentService.getAuthToken(Hg);if(!m)throw new D(on,g(1925,null),[Hg]);if(await this._gitService.hasUncommittedChanges(l)){this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Committing uncommitted changes for session ${o}`);try{await this._gitService.commitAll(l,this._formatCommitMessage(c))}catch(q){throw this._throwIfCancelled(e),new D(fe.InternalError,`Failed to commit changes before creating a pull request: ${q instanceof Error?q.message:String(q)}`)}}this._throwIfCancelled(e);let v=await this._gitService.computeSessionFileDiffs(l,{sessionUri:o,baseBranch:p});if(v===void 0)throw new D(fe.InternalError,g(1929,null));if(v!==void 0&&v.length===0)throw new D(fe.InternalError,g(1933,null));this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Pushing branch ${c} for session ${o}`);let I=await this._gitService.hasUpstream(l,c);this._throwIfCancelled(e);try{await this._gitService.pushBranch(l,c,!I)}catch(q){throw this._throwIfCancelled(e),new D(fe.InternalError,`Failed to push branch '${c}': ${q instanceof Error?q.message:String(q)}`)}this._throwIfCancelled(e);let b=this._formatTitle(c),S=this._formatBody(c,p),_=await this._octoKitService.findPullRequestByHeadBranch(d.githubOwner,d.githubRepo,c,m,n);if(_)return this._throwIfCancelled(e),this._onPullRequestCreated({sessionKey:o,branchName:c}),this._createResult(_,g(1932,null,_.number,_.url));this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Creating ${this._draft?"draft ":""}PR ${d.githubOwner}/${d.githubRepo} ${c} -> ${p}`);let R;try{R=await this._octoKitService.createPullRequest(d.githubOwner,d.githubRepo,b,S,c,p,this._draft,m,n)}catch(q){this._throwIfCancelled(e);let E;try{E=await this._octoKitService.findPullRequestByHeadBranch(d.githubOwner,d.githubRepo,c,m,n)}catch{throw this._throwIfCancelled(e),q}if(E)return this._throwIfCancelled(e),this._onPullRequestCreated({sessionKey:o,branchName:c}),this._createResult(E,g(1932,null,E.number,E.url));throw q}this._throwIfCancelled(e);let P=this._draft?g(1931,null,R.number,R.url):g(1930,null,R.number,R.url);return this._onPullRequestCreated({sessionKey:o,branchName:c}),this._createResult(R,P)}_throwIfCancelled(t){if(t.isCancellationRequested)throw new D(fe.InternalError,g(1927,null))}_formatTitle(t){let e=t.indexOf("/");if(e>0&&e<t.length-1){let n=t.substring(0,e),r=t.substring(e+1).replace(/[-_]+/g," ");return`${n}: ${r}`}return t.replace(/[-_]+/g," ")}_formatCommitMessage(t){return g(1928,null,t)}_formatBody(t,e){return g(1926,null,t,e)}_createResult(t,e){let n={content:{uri:t.url,contentType:"text/html"},external:!0};return{message:{markdown:e},followUp:n}}};kr=x([C(3,ti),C(4,tt),C(5,cp),C(6,O)],kr);var Jk=3e4,Ms=class extends T{constructor(e,n){super();this._stateManager=e;this._instantiationService=n;this._optimisticCreatedPullRequests=this._register(new ve);this.onPullRequestCreated=e=>{let n=this._key(e.sessionKey,e.branchName);this._optimisticCreatedPullRequests.set(n,$t(()=>{this._optimisticCreatedPullRequests.deleteAndDispose(n),this._registry?.onDidChangeOperations(e.sessionKey)},Jk)),this._registry?.onDidChangeOperations(e.sessionKey),this._registry?.refreshSessionGitState(e.sessionKey).finally(()=>{this._optimisticCreatedPullRequests.has(n)&&(this._optimisticCreatedPullRequests.deleteAndDispose(n),this._registry?.onDidChangeOperations(e.sessionKey))})}}registerHandlers(e){this._registry=e;let n=new z,r=a=>this._stateManager.getSessionState(a),o=this._instantiationService.createInstance(kr,!1,r,this.onPullRequestCreated.bind(this)),s=this._instantiationService.createInstance(kr,!0,r,this.onPullRequestCreated.bind(this));return n.add(e.registerChangesetOperationHandler(kr.OPERATION_CREATE_PR,o)),n.add(e.registerChangesetOperationHandler(kr.OPERATION_CREATE_DRAFT_PR,s)),n.add({dispose:()=>{this._registry=void 0}}),n}getOperations({sessionKey:e,gitState:n}){if(n.branchName&&this._optimisticCreatedPullRequests.has(this._key(e,n.branchName)))return;let r=(n.outgoingChanges??0)>0||(n.uncommittedChanges??0)>0;if(!(!n.hasGitHubRemote||!r))return[{id:"create-pr",label:g(1935,null),scopes:["changeset"],icon:"git-pull-request",status:"idle"},{id:"create-draft-pr",label:g(1934,null),scopes:["changeset"],icon:"git-pull-request-draft",status:"idle"}]}_key(e,n){return`${e}
${n}`}};Ms=x([C(1,ke)],Ms);function tT(i,t,e){let n=new z;return n.add(i.registerContribution(t.createInstance(Ms,e))),n.add(i.registerContribution(t.createInstance(Ds,e))),n}var Ls=class extends T{constructor(e,n,r){super();this._stateManager=e;this._gitService=n;this._logService=r}async attachGitState(e,n){if(!n)return;let r=e.toString();try{let o=await this._gitService.getSessionGitState(n);if(!o){this._stripGitOnlyChangesetEntries(r);return}let s=this._stateManager.getSessionState(r)?._meta;return We(hn(s),o)?void 0:(this._setSessionGitState(r,o),o)}catch(o){this._logService.warn(`[AgentHostSessionGitStateService] Failed to compute git state for ${e}`,o);return}}async refreshSessionGitState(e){let n=this._stateManager.getSessionState(e)?.summary.workingDirectory;if(!n)return;let r=await this._gitService.getSessionGitState(y.parse(n));if(!r){this._stripGitOnlyChangesetEntries(e);return}return this._setSessionGitState(e,r),r}_setSessionGitState(e,n){let r=this._stateManager.getSessionState(e)?._meta;this._stateManager.setSessionMeta(e,AI(r,n)),this._updateBranchChangesetDescription(e,n)}_stripGitOnlyChangesetEntries(e){let r=this._stateManager.getSessionState(e)?.changesets;if(!r||r.length===0)return;let o=Bt(e),s=xn(e),a=r.filter(l=>l.uriTemplate!==o&&l.uriTemplate!==s);a.length!==r.length&&this._stateManager.setSessionChangesets(e,a)}_updateBranchChangesetDescription(e,n){let r=oI(n),s=this._stateManager.getSessionState(e)?.changesets;if(!s||s.length===0)return;let a=oi(e),l=!1,d=s.map(c=>{if(c.uriTemplate!==a||c.description===r)return c;if(l=!0,r===void 0){let{description:u,...p}=c;return p}return{...c,description:r}});l&&this._stateManager.setSessionChangesets(e,d)}};Ls=x([C(1,tt),C(2,O)],Ls);var up=class{constructor(t){this._logService=t;this._tokens=new Map}async authenticate(t,e){this._logService.trace(`[AgentHostAuthenticationService] authenticate called: resource=${t.resource}`);let n=[...e].filter(s=>s.getProtectedResources().some(a=>a.resource===t.resource)),r=await Promise.allSettled(n.map(s=>s.authenticate(t.resource,t.token))),o=!1;for(let s=0;s<r.length;s++){let a=r[s];a.status==="fulfilled"?o||=a.value:this._logService.error(a.reason,`[AgentHostAuthenticationService] Provider '${n[s].id}' authenticate threw for resource=${t.resource}`)}if(o){let s=this._normalizeScopes(t.scopes);this._tokens.set(this._key(t.resource,s),{resource:t.resource,scopes:s,token:t.token})}return{authenticated:o}}getAuthToken(t){let e=this._normalizeScopes(t.scopes),n=this._tokens.get(this._key(t.resource,e));if(n)return n.token;if(e.length===0)return;let r=new Set(e),o;for(let s of this._tokens.values())s.resource!==t.resource||s.scopes.length===0||this._containsAll(s.scopes,r)&&(!o||s.scopes.length<o.scopes.length)&&(o=s);return o?o.token:this._tokens.get(this._key(t.resource,[]))?.token}_containsAll(t,e){for(let n of e)if(!t.includes(n))return!1;return!0}_key(t,e){return`${t}\0${e.join("\0")}`}_normalizeScopes(t){return t?[...new Set(t)].sort():[]}};var Yk=3e4,Qk=3e4,pp=class extends T{constructor(e,n,r,o,s,a=h_,l,d=Nu,c,u){super();this._logService=e;this._fileService=n;this._sessionDataService=r;this._productService=o;this._gitService=s;this._checkpointService=a;this._rootConfigResource=l;this._telemetryService=d;this._onDidAction=this._register(new w);this.onDidAction=this._onDidAction.event;this._onDidNotification=this._register(new w);this.onDidNotification=this._onDidNotification.event;this._onMcpNotification=this._register(new w);this.onMcpNotification=this._onMcpNotification.event;this._providers=new Map;this._sessionToProvider=new Map;this._providerSubscriptions=this._register(new z);this._agents=pn("agents",[]);this._skillCompletionProviderRegistered=!1;this._resourceSubscribers=new Oe;this._pendingSessionGc=this._register(new hd);this._resourceWatches=this._register(new ve);this._clientDispatchQueues=new Map;this._logService.info("AgentService initialized"),this._authService=new up(e),this._stateManager=this._register(new as(e,{hostBuildInfo:kI(this._productService),changesetStateRetention:{canEvict:_=>this._changesets?this._isChangesetEvictable(_):!1}})),this._register(this._stateManager.onDidEmitEnvelope(_=>this._onDidAction.fire(_))),this._register(this._stateManager.onDidEmitNotification(_=>this._onDidNotification.fire(_)));let p=this._register(new es(this._stateManager,this._logService,this._rootConfigResource));this._configurationService=p;let m=c??this._register(new qn(this._fileService,this._logService));qu(this._telemetryService,this._stateManager.rootState.config?.values);let h=new ri([O,this._logService],[ti,this],[gt,this._productService],[$e,p],[ws,m],[tt,this._gitService],[ai,this._telemetryService],[ft,this._sessionDataService]),v=this._register(new Ko(h,!0)),I=v.createInstance(Os,void 0);h.set(cp,I);let b=u??v.createInstance(pi,void 0);h.set(Kt,b),this._sessionGitStateService=this._register(v.createInstance(Ls,this._stateManager)),this._changesetOperationContributionService=this._register(v.createInstance(dp,this._stateManager,this._sessionGitStateService)),h.set(Wn,this._checkpointService),this._changesets=this._register(v.createInstance(Er,this._stateManager)),h.set(ui,this._changesets),this._register(tT(this._changesetOperationContributionService,v,this._stateManager)),this._changesetCoordinator=this._register(v.createInstance(Rs,this._stateManager)),this._register(this._stateManager.onDidChangeSessionActiveTurn(_=>this._changesetCoordinator.onSessionTurnActiveChanged(_.session,_.active))),this._completions=this._register(v.createInstance(cs));let S=this._register(v.createInstance(As));this._register(this._completions.registerProvider(new op(this._stateManager,S))),this._register(this._completions.registerProvider(new ru(_=>(this._stateManager.getSessionState(_)?.turns.length??0)>0))),this._sideEffects=this._register(v.createInstance(xs,this._stateManager,{getAgent:_=>this._findProviderForSession(_),sessionDataService:this._sessionDataService,agents:this._agents,copilotApiService:b,getGitHubCopilotToken:()=>this.getAuthToken({resource:St.resource,scopes:St.scopes_supported}),onTurnComplete:_=>{let R=this._stateManager.getSessionState(_)?.summary.workingDirectory;this._attachGitState(y.parse(_),R?y.parse(R):void 0)}})),this._terminalManager=this._register(v.createInstance(rs,this._stateManager)),this._serverToolHost=new zu(this._stateManager,[wC])}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),e.setServerToolHost?.(this._serverToolHost),this._providerSubscriptions.add(this._sideEffects.registerProgressListener(e)),e.onDidMaterializeSession&&this._providerSubscriptions.add(e.onDidMaterializeSession(n=>this._onDidMaterializeSession(n))),e.onMcpNotification&&this._providerSubscriptions.add(e.onMcpNotification(n=>this._onMcpNotification.fire(n))),this._registerSkillCompletionProvider(),this._defaultProvider||(this._defaultProvider=e.id),this._updateAgents()}_registerSkillCompletionProvider(){if(this._skillCompletionProviderRegistered)return;this._skillCompletionProviderRegistered=!0;let e=this._register(new sp(n=>this._findProviderForSession(n)));this._register(this._completions.registerProvider(e))}async authenticate(e){return this._authService.authenticate(e,this._providers.values())}getAuthToken(e){return this._authService.getAuthToken(e)}async invokeChangesetOperation(e){return this._changesetOperationContributionService.invokeChangesetOperation(e)}async handleMcpRequest(e,n,r){let o=XC(e);if(!o)throw new Error(`Method not found: invalid mcp:// channel ${e}`);let s=this._providers.get(o.providerId);if(!s||!s.handleMcpRequest)throw new Error(`Method not found: no provider for mcp:// channel ${e}`);let a=F.uri(o.providerId,o.sessionId);return s.handleMcpRequest(a,o.serverName,n,r)}async listSessions(){this._logService.trace("[AgentService] listSessions called");let n=(await Promise.all([...this._providers.values()].map(d=>d.listSessions()))).flat(),o=(await Promise.all(n.map(async d=>{try{let c=await this._sessionDataService.tryOpenDatabase(d.session);if(!c)return d;try{let u=d.session.toString(),p=this._changesetCoordinator.getListMetadataKeys(u),m=p?{customTitle:!0,isRead:!0,isArchived:!0,isDone:!0,...p}:{customTitle:!0,isRead:!0,isArchived:!0,isDone:!0},h=await c.object.getMetadataObject(m),v=d;return h.customTitle&&(v={...v,summary:h.customTitle}),h.isRead!==void 0&&(v={...v,isRead:h.isRead==="true"}),h.isArchived!==void 0?v={...v,isArchived:h.isArchived==="true"}:h.isDone!==void 0&&(v={...v,isArchived:h.isDone==="true"}),this._changesetCoordinator.decorateListEntry(v,h)}finally{c.dispose()}}catch(c){this._logService.warn(`[AgentService] Failed to read session metadata overlay for ${d.session}`,c)}return d}))).map(d=>{let c=this._stateManager.getSessionState(d.session.toString());return c?{...d,summary:c.summary.title||d.summary,status:c.summary.status,activity:c.summary.activity,model:c.summary.model??d.model,agent:c.summary.agent??d.agent,changes:c.summary.changes??d.changes,changesets:c.changesets??d.changesets}:d}),s=new Set(o.map(d=>d.session.toString())),a=[];for(let d of this._stateManager.getOverlaySessionSummaries())s.has(d.resource)||Xo(d.resource)||a.push({session:y.parse(d.resource),startTime:d.createdAt,modifiedTime:d.modifiedAt,summary:d.title,status:d.status,activity:d.activity,model:d.model,agent:d.agent,workingDirectory:typeof d.workingDirectory=="string"?y.parse(d.workingDirectory):void 0,...d.project?{project:{uri:y.parse(d.project.uri),displayName:d.project.displayName}}:{},changes:d.changes});let l=a.length>0?[...o,...a]:o;return this._logService.trace(`[AgentService] listSessions returned ${l.length} sessions (${a.length} state-manager fallback)`),l}async createSession(e){let n=e?.provider??this._defaultProvider,r=n?this._providers.get(n):void 0;if(!r)throw new Error(`No agent provider registered for: ${n??"(none)"}`);if(e?.fork){let 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 p=new Map;for(let m of u)p.set(m.id,N());e={...e,fork:{...e.fork,turnIdMapping:p}}}}this._logService.trace("[AgentService] createSession: initializing auto-approver and creating session...");let[,o]=await Promise.all([this._sideEffects.initialize(),r.createSession(e)]),s=o.session;this._logService.trace("[AgentService] createSession: initialization complete"),this._cancelPendingSessionGc(s),this._logService.trace(`[AgentService] createSession: provider=${r.id} model=${e?.model?.id??"(default)"}`),this._sessionToProvider.set(s.toString(),r.id),this._logService.trace(`[AgentService] createSession returned: ${s.toString()}`);let[a,l]=await Promise.all([this._resolveCreatedSessionConfig(r,e),r.getSessionCustomizations?r.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(b=>({...b,id:e.fork.turnIdMapping.get(b.id)??N()})));let p=g(1938,null),m=c?.summary.title,h=m?m.startsWith(p)?m:`${p}${m}`:g(1937,null),v=this._buildInitialSummary(r,s,e,o,h),I=this._stateManager.createSession(v);I.config=a,I.turns=u,I.activeClient=e.activeClient,l&&l.length>0&&(I.customizations=[...l])}else{let c=this._buildInitialSummary(r,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])}a?.values&&Object.keys(a.values).length>0&&!o.provisional&&this._persistConfigValues(s,a.values);let d=bc(s.toString());return this._stateManager.setSessionChangesets(s.toString(),d),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,r,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:r?.model,agent:r?.agent,workingDirectory:(o.workingDirectory??r?.workingDirectory)?.toString()}}_onDidMaterializeSession(e){let n=e.session.toString(),r=this._stateManager.getSessionState(n);if(!r){this._logService.warn(`[AgentService] onDidMaterializeSession for unknown session: ${n}`);return}let o={...r.summary,...e.project?{project:{uri:e.project.uri.toString(),displayName:e.project.displayName}}:{},workingDirectory:e.workingDirectory?.toString()??r.summary.workingDirectory,modifiedAt:Date.now()},s=r.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);let a=bc(n);this._stateManager.setSessionChangesets(n,a),this._changesetCoordinator.onSessionMaterialized(n)}_attachGitState(e,n){let r=e.toString();this._sessionGitStateService.attachGitState(e,n).then(o=>{o&&(this._changesetCoordinator.onSessionGitStateChanged(r),this._changesetOperationContributionService.updateOperations(r,o))},o=>{this._logService.warn(`[AgentService] Failed to compute git state for ${e}`,o)})}_persistConfigValues(e,n){let r;try{r=this._sessionDataService.openDatabase(e)}catch(o){this._logService.warn(`[AgentService] Failed to open session database to persist configValues for ${e.toString()}: ${xt(o)}`);return}r.object.setMetadata("configValues",JSON.stringify(n)).catch(o=>{this._logService.warn(`[AgentService] Failed to persist configValues for ${e.toString()}: ${xt(o)}`)}).finally(()=>{r.dispose()})}async _resolveCreatedSessionConfig(e,n){if(!(!n?.config&&!n?.workingDirectory))try{let r=await e.resolveSessionConfig({provider:e.id,workingDirectory:n.workingDirectory,config:n.config});return{schema:r.schema,values:r.values}}catch(r){return this._logService.error(`[AgentService] Failed to resolve created session config for provider ${e.id}`,r),n.config?{schema:{type:"object",properties:{}},values:n.config}:void 0}}async resolveSessionConfig(e){let n=e.provider??this._defaultProvider,r=n?this._providers.get(n):void 0;if(!r)throw new Error(`No agent provider registered for: ${n??"(none)"}`);return r.resolveSessionConfig(e)}async sessionConfigCompletions(e){let n=e.provider??this._defaultProvider,r=n?this._providers.get(n):void 0;if(!r)throw new Error(`No agent provider registered for: ${n??"(none)"}`);return r.sessionConfigCompletions(e)}async 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.cancelSessionTitleGeneration(e.toString()),this._sideEffects.removeSubagentSessions(e.toString()),this._stateManager.deleteSession(e.toString()),await this._sessionDataService.deleteSessionData(e)}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 r=e.toString();this.addSubscriber(e,n);try{let o=this._terminalManager.getTerminalState(r);if(o)return{resource:r,state:o,fromSeq:this._stateManager.serverSeq};let s=this._stateManager.getSnapshot(r),a=Vt(r);if(s&&a&&!this._stateManager.getSessionState(a.sessionUri)&&(await this._changesetCoordinator.restoreSessionIfChangesetSubscription(e,d=>this.restoreSession(d)),s=this._stateManager.getSnapshot(r)),!s)if(await this._changesetCoordinator.tryHandleSubscribe(e,c=>this.restoreSession(c)))s=this._stateManager.getSnapshot(r);else{let c=Xe(e);c?await this._restoreSubagentSession(r,c.parentSession):await this.restoreSession(e),s=this._stateManager.getSnapshot(r)}if(!s)throw new Error(`Cannot subscribe to unknown resource: ${r}`);let l=this._stateManager.getSessionState(r);if(l&&hn(l._meta)===void 0){let d=l.summary?.workingDirectory;this._attachGitState(e,d?y.parse(d):void 0)}return s}catch(o){throw this.unsubscribe(e,n),o}}addSubscriber(e,n){let r=this._resourceSubscribers.get(e),o=!r||r.size===0;r||(r=new Set,this._resourceSubscribers.set(e,r)),r.add(n),this._cancelPendingSessionGc(e),o&&this._changesetCoordinator.onFirstSubscriber(e)}unsubscribe(e,n){let r=this._resourceSubscribers.get(e);r&&(r.delete(n),!(r.size>0)&&(this._resourceSubscribers.delete(e),this._changesetCoordinator.onLastSubscriber(e),this._stateManager.onChangesetLivenessChanged(),!this._maybeScheduleSessionGc(e)&&this._maybeEvictIdleSession(e)))}_maybeScheduleSessionGc(e){if(Xe(e))return!1;let n=e.toString(),r=this._stateManager.getSessionState(n);return!r||r.turns.length>0||r.activeTurn!==void 0?!1:(this._pendingSessionGc.set(e,$t(()=>{this._pendingSessionGc.deleteAndDispose(e),this._runSessionGc(e).catch(o=>{this._logService.error(o,`[AgentService] GC failed for ${n}`)})},Yk)),!0)}_cancelPendingSessionGc(e){this._pendingSessionGc.deleteAndDispose(e)}async _runSessionGc(e){let n=e.toString();if(this._resourceSubscribers.has(e))return;let r=this._stateManager.getSessionState(n);r&&(r.turns.length>0||r.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 r=e;{let l;for(;l=Xe(r);)r=l.parentSession}if(this._resourceSubscribers.has(r))return;for(let l of this._resourceSubscribers.keys())if(this._isSubagentDescendantOf(l,r))return;let o=r.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=EI(r);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 r=Vt(e);if(!r)return!1;let o=y.parse(r.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 r=Xe(e);for(;r;){if(Eo(r.parentSession,n))return!0;r=Xe(r.parentSession)}return!1}dispatchAction(e,n,r,o){this._logService.trace(`[AgentService] dispatchAction: type=${n.type}, clientId=${r}, clientSeq=${o}`,n);let s=this._clientDispatchQueues.get(r);if(!s&&!this._needsAsyncRewrite(e,n)){this._dispatchActionNow(e,n,r,o);return}let a=(s??Promise.resolve()).then(async()=>{let l=this._needsAsyncRewrite(e,n)?await this._rewriteUserMessageAttachments(e,n,r):n;this._dispatchActionNow(e,l,r,o)}).catch(l=>{this._logService.error(`[AgentService] async dispatchAction failed: ${xt(l)}`)});this._clientDispatchQueues.set(r,a.finally(()=>{this._clientDispatchQueues.get(r)===a&&this._clientDispatchQueues.delete(r)}))}_dispatchActionNow(e,n,r,o){let s={clientId:r,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 r=this._attachmentsRoot(e).toString();return!!n.message.attachments?.some(o=>this._isRewritableAttachment(o,r))}_isRewritableAttachment(e,n){return e.type==="embeddedResource"?!0:e.type==="resource"?!(e.displayKind==="directory"||e.uri.startsWith(n)):!1}_attachmentsRoot(e){return X(this._sessionDataService.getSessionDataDir(y.parse(e)),yc)}async _rewriteUserMessageAttachments(e,n,r){let o=n.message.attachments;if(!o?.length)return n;let s=this._attachmentsRoot(e),a=s.toString(),l=await Promise.all(o.map(d=>this._rewriteSingleAttachment(d,s,a,r)));return{...n,message:{...n.message,attachments:l}}}async _rewriteSingleAttachment(e,n,r,o){try{if(e.type==="embeddedResource"){let s=Ln(e.data).buffer,a=this._attachmentBasename(e.label,e.contentType);return this._writeAndRewrite(e,s,a,n)}if(e.type==="resource"&&this._isRewritableAttachment(e,r)){let s=y.parse(e.uri);if(s.scheme===ie.file&&await this._fileExistsSafe(s))return e;let a=await this._readClientResource(s,o),l=this._attachmentBasename(e.label,Kd(s.path));return this._writeAndRewrite(e,a,l,n)}}catch(s){this._logService.warn(`[AgentService] Failed to rewrite attachment '${e.label}': ${xt(s)}`)}return e}async _fileExistsSafe(e){try{return await this._fileService.exists(e)}catch{return!1}}async _readClientResource(e,n){let r=n?ks(e,n):e;try{return(await this._fileService.readFile(r)).value.buffer}catch(o){if(r!==e)try{return(await this._fileService.readFile(e)).value.buffer}catch{}throw o}}async _writeAndRewrite(e,n,r,o){let s=N(),a=X(o,s,r);await this._fileService.writeFile(a,A.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 r=(e||"attachment").replace(/[\\/:*?"<>|\u0000-\u001f]/g,"_");if(Ma(y.file(r)))return r;let o=n?mb(n):void 0;return o?`${r}${o}`:r}async resourceList(e){let n;try{n=await this._fileService.resolve(e)}catch{throw new D(ue.NotFound,`Directory not found: ${e.toString()}`)}if(!n.isDirectory)throw new D(ue.NotFound,`Not a directory: ${e.toString()}`);return{entries:(n.children??[]).map(o=>({name:o.name,type:o.isDirectory?"directory":"file"}))}}async restoreSession(e){let n=e.toString();if(this._stateManager.getSessionState(n))return;let r=this._findProviderForSession(e);if(!r)throw new D(At,`No agent for session: ${n}`);let o=await this._getSessionMetadataForRestore(r,e);if(!o)throw new D(At,`Session not found on backend: ${n}`);let s;try{s=await r.getSessionMessages(e)}catch(S){if(S instanceof D)throw S;let _=S instanceof Error?S.message:String(S);throw new D(Jo,`Failed to restore session ${n}: ${_}`)}let a=o.summary??"Session",l,d,c,u,p,m=this._sessionDataService.tryOpenDatabase?.(e);if(m)try{let S=await m;if(S)try{let _=await S.object.getMetadataObject({customTitle:!0,isRead:!0,isArchived:!0,isDone:!0,configValues:!0,...Eh});if(_.customTitle&&(a=_.customTitle),_.isRead!==void 0&&(l=_.isRead==="true"),_.isArchived!==void 0?d=_.isArchived==="true":_.isDone!==void 0&&(d=_.isDone==="true"),p=_,p[no])try{u=JSON.parse(p[no])}catch(R){this._logService.warn(`[AgentService] Failed to parse changes summary for ${n}: ${xt(R)}`)}if(_.configValues)try{c=JSON.parse(_.configValues)}catch(R){this._logService.warn(`[AgentService] Failed to parse persisted configValues for ${n}: ${xt(R)}`)}}finally{S.dispose()}}catch{}let h=1;l&&(h|=32),d&&(h|=64);let v={resource:n,provider:r.id,title:a,status:h,createdAt:o.startTime,modifiedAt:o.modifiedTime,...o.project?{project:{uri:o.project.uri.toString(),displayName:o.project.displayName}}:{},model:o.model,agent:o.agent,changes:o.changes??u,workingDirectory:o.workingDirectory?.toString()};this._stateManager.restoreSession(v,[...s]);let I=bc(n);this._stateManager.setSessionChangesets(n,I),this._changesetCoordinator.onSessionRestored(n,p??{}),o._meta&&this._stateManager.setSessionMeta(n,o._meta);let b=await this._resolveCreatedSessionConfig(r,{workingDirectory:o.workingDirectory,config:c});if(b){let S=this._stateManager.getSessionState(n);S&&(S.config=b)}this._logService.info(`[AgentService] Restored session ${n} with ${s.length} turns`),this._attachGitState(e,o.workingDirectory)}async _getSessionMetadataForRestore(e,n){let r=n.toString();if(e.getSessionMetadata)try{return await e.getSessionMetadata(n)}catch(o){if(o instanceof D)throw o;try{return await this._getSessionMetadataFromCatalog(e,n)}catch(s){if(s instanceof D){let a=o instanceof Error?o.message:String(o);throw new D(s.code,`Failed to get session metadata for ${r}: ${a}; ${s.message}`,s.data)}throw s}}return this._getSessionMetadataFromCatalog(e,n)}async _getSessionMetadataFromCatalog(e,n){let r=n.toString(),o;try{o=await e.listSessions()}catch(s){if(s instanceof D)throw s;let a=s instanceof Error?s.message:String(s);throw new D(Jo,`Failed to list sessions for ${r}: ${a}`)}return o.find(s=>s.session.toString()===r)}async resourceRead(e){let n=l_(e.toString());if(n)return this._fetchSessionDbContent(n);let r=c_(e.toString());if(r)return this._fetchGitBlobContent(r);try{return{data:(await this._fileService.readFile(e)).value.toString(),encoding:"utf-8",contentType:"text/plain"}}catch{throw new D(ue.NotFound,`Content not found: ${e.toString()}`)}}async resourceWrite(e){let n=typeof e.uri=="string"?y.parse(e.uri):y.revive(e.uri),r;e.encoding==="base64"?r=Ln(e.data):r=A.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,r,o,s,e):e.createOnly?await this._fileService.createFile(n,r,{overwrite:!1}):await this._fileService.writeFile(n,r),{}}catch(a){if(a instanceof D)throw a;if(a instanceof Ke&&a.fileOperationResult===3)throw new D(ue.Conflict,`ifMatch precondition failed for: ${n.toString()}`);let l=qt(a);throw l==="EntryExists"?new D(ue.AlreadyExists,`File already exists: ${n.toString()}`):l==="NoPermissions"?new D(ue.PermissionDenied,`Permission denied: ${n.toString()}`):new D(ue.NotFound,`Failed to write file: ${n.toString()}`)}}async _resourceWriteWithMode(e,n,r,o,s){let a,l;try{let u=await this._fileService.readFile(e);a=u.value,l=u.etag}catch(u){if(qt(u)!=="EntryNotFound")throw u}if(s.ifMatch!==void 0&&(a===void 0||l!==s.ifMatch))throw new D(ue.Conflict,`ifMatch precondition failed for: ${e.toString()}`);let d=a??A.alloc(0),c;switch(r){case"append":{let u=d.byteLength,p=Math.max(0,u-o);c=A.concat([d.slice(0,p),n,d.slice(p,u)]);break}case"insert":{let u=Math.min(o,d.byteLength);c=A.concat([d.slice(0,u),n,d.slice(u,d.byteLength)]);break}case"truncate":default:{let u=Math.min(o,d.byteLength);c=A.concat([d.slice(0,u),n]);break}}await this._fileService.writeFile(e,c,{etag:l})}async resourceCopy(e){let n=y.parse(e.source),r=y.parse(e.destination);try{return await this._fileService.copy(n,r,!e.failIfExists),{}}catch(o){let s=qt(o);throw s==="EntryExists"?new D(ue.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new D(ue.PermissionDenied,`Permission denied: ${n.toString()}`):new D(ue.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(r){throw qt(r)==="NoPermissions"?new D(ue.PermissionDenied,`Permission denied: ${n.toString()}`):new D(ue.NotFound,`Resource not found: ${n.toString()}`)}}async resourceMove(e){let n=y.parse(e.source),r=y.parse(e.destination);try{return await this._fileService.move(n,r,!e.failIfExists),{}}catch(o){let s=qt(o);throw s==="EntryExists"?new D(ue.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new D(ue.PermissionDenied,`Permission denied: ${n.toString()}`):new D(ue.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 r=await this._fileService.stat(n),o;return r.isSymbolicLink&&e.followSymlinks===!1?o="symlink":r.isDirectory?o="directory":o="file",{uri:n.toString(),type:o,...r.size!==void 0?{size:r.size}:{},...r.mtime!==void 0?{mtime:new Date(r.mtime).toISOString()}:{},...r.ctime!==void 0?{ctime:new Date(r.ctime).toISOString()}:{},...r.etag?{etag:r.etag}:{}}}catch(r){throw qt(r)==="NoPermissions"?new D(ue.PermissionDenied,`Permission denied: ${n.toString()}`):new D(ue.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 r=await this._fileService.stat(n).catch(()=>{});if(r&&!r.isDirectory)throw new D(ue.AlreadyExists,`Path exists and is not a directory: ${n.toString()}`);return await this._fileService.createFolder(n),{}}catch(r){throw r instanceof D?r:qt(r)==="NoPermissions"?new D(ue.PermissionDenied,`Permission denied: ${n.toString()}`):new D(ue.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 qt(o)==="NoPermissions"?new D(ue.PermissionDenied,`Permission denied: ${n.toString()}`):new D(ue.NotFound,`Resource not found: ${n.toString()}`)}return{channel:_I({root:n.toString(),recursive:e.recursive===!0,excludes:e.excludes,includes:e.includes})}}onResourceWatchSubscribed(e){let n=CI(e);if(!n)return;let r=this._resourceWatches.get(e);if(r)return r.subscribers++,r.pendingGc&&r.pendingGc.clear(),r.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 d=Zk(l,s);d.length>0&&this._dispatchResourceWatchChanges(e,d)}));else{let l=this._fileService.createWatcher(s,{...a,recursive:!1});o.add(l),o.add(l.onDidChange(d=>{this._dispatchResourceWatchChanges(e,Xk(d))}))}}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 vt),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=$t(()=>{let r=this._resourceWatches.get(e);!r||r.subscribers>0||this._resourceWatches.deleteAndDispose(e)},Qk)),!0):!1}_dispatchResourceWatchChanges(e,n){if(n.length===0)return;let r=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:r}})}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),r=this._sessionDataService.openDatabase(n);try{let o=await r.object.readFileEditContent(e.toolCallId,e.filePath);if(!o)throw new D(ue.NotFound,`File edit not found: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);let s=e.part==="before"?o.beforeContent:o.afterContent;if(!s)throw new D(ue.NotFound,`No ${e.part} content for: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);return{data:new TextDecoder().decode(s),encoding:"utf-8",contentType:"text/plain"}}finally{r.dispose()}}async _fetchGitBlobContent(e){if(!this._gitService)throw new D(ue.NotFound,`git service unavailable for: ${e.repoRelativePath}`);let n=this._stateManager.getSessionState(e.sessionUri)?.summary.workingDirectory;if(!n)throw new D(ue.NotFound,`Session has no working directory for git-blob URI: ${e.sessionUri}`);let r=await this._gitService.showBlob(y.parse(n),e.sha,e.repoRelativePath);if(!r)throw new D(ue.NotFound,`git blob not found: ${e.sha}:${e.repoRelativePath}`);return{data:r.toString(),encoding:"utf-8",contentType:"text/plain"}}async _restoreSubagentSession(e,n){let r=n.toString();if(!this._stateManager.getSessionState(r))try{await this.restoreSession(n)}catch{this._logService.warn(`[AgentService] Cannot restore parent session for subagent: ${r}`);return}let o=this._stateManager.getSessionState(r);if(!o)return;let s=[...o.turns];o.activeTurn&&s.push(o.activeTurn);let a;for(let u of s){for(let p of u.responseParts)if(p.kind==="toolCall"){let m=p.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=[],d=this._findProviderForSession(n);if(d)try{l=await d.getSessionMessages(y.parse(e))}catch(u){this._logService.warn(`[AgentService] Failed to load subagent turns for ${e}`,u)}let c=a?.title??"Subagent";this._stateManager.restoreSession({resource:e,provider:"subagent",title:c,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(),r=this._sessionToProvider.get(n);if(r)return this._providers.get(r);let o=F.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 Xk(i){let t=[];for(let e of i.rawAdded)t.push({resource:e,type:1});for(let e of i.rawUpdated)t.push({resource:e,type:0});for(let e of i.rawDeleted)t.push({resource:e,type:2});return t}function Zk(i,t){let e=[],n=(r,o)=>{Oa(r,t)&&e.push({resource:r,type:o})};for(let r of i.rawAdded)n(r,1);for(let r of i.rawUpdated)n(r,0);for(let r of i.rawDeleted)n(r,2);return e}import{CopilotClient as s2,RuntimeConnection as a2}from"@github/copilot-sdk";import*as ao from"fs/promises";var nT=Object.create(null);function f(i,t){if(Ne(t)){let e=nT[t];if(e===void 0)throw new Error(`${i} references an unknown codicon: ${t}`);t=e}return nT[i]=t,{id:i}}var rT={add:f("add",6e4),plus:f("plus",6e4),gistNew:f("gist-new",6e4),repoCreate:f("repo-create",6e4),lightbulb:f("lightbulb",60001),lightBulb:f("light-bulb",60001),repo:f("repo",60002),repoDelete:f("repo-delete",60002),gistFork:f("gist-fork",60003),repoForked:f("repo-forked",60003),gitPullRequest:f("git-pull-request",60004),gitPullRequestAbandoned:f("git-pull-request-abandoned",60004),recordKeys:f("record-keys",60005),keyboard:f("keyboard",60005),tag:f("tag",60006),gitPullRequestLabel:f("git-pull-request-label",60006),tagAdd:f("tag-add",60006),tagRemove:f("tag-remove",60006),person:f("person",60007),personFollow:f("person-follow",60007),personOutline:f("person-outline",60007),personFilled:f("person-filled",60007),sourceControl:f("source-control",60008),mirror:f("mirror",60009),mirrorPublic:f("mirror-public",60009),star:f("star",60010),starAdd:f("star-add",60010),starDelete:f("star-delete",60010),starEmpty:f("star-empty",60010),comment:f("comment",60011),commentAdd:f("comment-add",60011),alert:f("alert",60012),warning:f("warning",60012),search:f("search",60013),searchSave:f("search-save",60013),logOut:f("log-out",60014),signOut:f("sign-out",60014),logIn:f("log-in",60015),signIn:f("sign-in",60015),eye:f("eye",60016),eyeUnwatch:f("eye-unwatch",60016),eyeWatch:f("eye-watch",60016),circleFilled:f("circle-filled",60017),primitiveDot:f("primitive-dot",60017),closeDirty:f("close-dirty",60017),debugBreakpoint:f("debug-breakpoint",60017),debugBreakpointDisabled:f("debug-breakpoint-disabled",60017),debugHint:f("debug-hint",60017),terminalDecorationSuccess:f("terminal-decoration-success",60017),primitiveSquare:f("primitive-square",60018),edit:f("edit",60019),pencil:f("pencil",60019),info:f("info",60020),issueOpened:f("issue-opened",60020),gistPrivate:f("gist-private",60021),gitForkPrivate:f("git-fork-private",60021),lock:f("lock",60021),mirrorPrivate:f("mirror-private",60021),close:f("close",60022),removeClose:f("remove-close",60022),x:f("x",60022),repoSync:f("repo-sync",60023),sync:f("sync",60023),clone:f("clone",60024),desktopDownload:f("desktop-download",60024),beaker:f("beaker",60025),microscope:f("microscope",60025),vm:f("vm",60026),deviceDesktop:f("device-desktop",60026),file:f("file",60027),more:f("more",60028),ellipsis:f("ellipsis",60028),kebabHorizontal:f("kebab-horizontal",60028),mailReply:f("mail-reply",60029),reply:f("reply",60029),organization:f("organization",60030),organizationFilled:f("organization-filled",60030),organizationOutline:f("organization-outline",60030),newFile:f("new-file",60031),fileAdd:f("file-add",60031),newFolder:f("new-folder",60032),fileDirectoryCreate:f("file-directory-create",60032),trash:f("trash",60033),trashcan:f("trashcan",60033),history:f("history",60034),clock:f("clock",60034),folder:f("folder",60035),fileDirectory:f("file-directory",60035),symbolFolder:f("symbol-folder",60035),logoGithub:f("logo-github",60036),markGithub:f("mark-github",60036),github:f("github",60036),terminal:f("terminal",60037),console:f("console",60037),repl:f("repl",60037),zap:f("zap",60038),symbolEvent:f("symbol-event",60038),error:f("error",60039),stop:f("stop",60039),variable:f("variable",60040),symbolVariable:f("symbol-variable",60040),array:f("array",60042),symbolArray:f("symbol-array",60042),symbolModule:f("symbol-module",60043),symbolPackage:f("symbol-package",60043),symbolNamespace:f("symbol-namespace",60043),symbolObject:f("symbol-object",60043),symbolMethod:f("symbol-method",60044),symbolFunction:f("symbol-function",60044),symbolConstructor:f("symbol-constructor",60044),symbolBoolean:f("symbol-boolean",60047),symbolNull:f("symbol-null",60047),symbolNumeric:f("symbol-numeric",60048),symbolNumber:f("symbol-number",60048),symbolStructure:f("symbol-structure",60049),symbolStruct:f("symbol-struct",60049),symbolParameter:f("symbol-parameter",60050),symbolTypeParameter:f("symbol-type-parameter",60050),symbolKey:f("symbol-key",60051),symbolText:f("symbol-text",60051),symbolReference:f("symbol-reference",60052),goToFile:f("go-to-file",60052),symbolEnum:f("symbol-enum",60053),symbolValue:f("symbol-value",60053),symbolRuler:f("symbol-ruler",60054),symbolUnit:f("symbol-unit",60054),activateBreakpoints:f("activate-breakpoints",60055),archive:f("archive",60056),arrowBoth:f("arrow-both",60057),arrowDown:f("arrow-down",60058),arrowLeft:f("arrow-left",60059),arrowRight:f("arrow-right",60060),arrowSmallDown:f("arrow-small-down",60061),arrowSmallLeft:f("arrow-small-left",60062),arrowSmallRight:f("arrow-small-right",60063),arrowSmallUp:f("arrow-small-up",60064),arrowUp:f("arrow-up",60065),bell:f("bell",60066),bold:f("bold",60067),book:f("book",60068),bookmark:f("bookmark",60069),debugBreakpointConditionalUnverified:f("debug-breakpoint-conditional-unverified",60070),debugBreakpointConditional:f("debug-breakpoint-conditional",60071),debugBreakpointConditionalDisabled:f("debug-breakpoint-conditional-disabled",60071),debugBreakpointDataUnverified:f("debug-breakpoint-data-unverified",60072),debugBreakpointData:f("debug-breakpoint-data",60073),debugBreakpointDataDisabled:f("debug-breakpoint-data-disabled",60073),debugBreakpointLogUnverified:f("debug-breakpoint-log-unverified",60074),debugBreakpointLog:f("debug-breakpoint-log",60075),debugBreakpointLogDisabled:f("debug-breakpoint-log-disabled",60075),briefcase:f("briefcase",60076),broadcast:f("broadcast",60077),browser:f("browser",60078),bug:f("bug",60079),calendar:f("calendar",60080),caseSensitive:f("case-sensitive",60081),check:f("check",60082),checklist:f("checklist",60083),chevronDown:f("chevron-down",60084),chevronLeft:f("chevron-left",60085),chevronRight:f("chevron-right",60086),chevronUp:f("chevron-up",60087),chromeClose:f("chrome-close",60088),chromeMaximize:f("chrome-maximize",60089),chromeMinimize:f("chrome-minimize",60090),chromeRestore:f("chrome-restore",60091),circleOutline:f("circle-outline",60092),circle:f("circle",60092),debugBreakpointUnverified:f("debug-breakpoint-unverified",60092),terminalDecorationIncomplete:f("terminal-decoration-incomplete",60092),circleSlash:f("circle-slash",60093),circuitBoard:f("circuit-board",60094),clearAll:f("clear-all",60095),clippy:f("clippy",60096),closeAll:f("close-all",60097),cloudDownload:f("cloud-download",60098),cloudUpload:f("cloud-upload",60099),code:f("code",60100),collapseAll:f("collapse-all",60101),colorMode:f("color-mode",60102),commentDiscussion:f("comment-discussion",60103),creditCard:f("credit-card",60105),dash:f("dash",60108),dashboard:f("dashboard",60109),database:f("database",60110),debugContinue:f("debug-continue",60111),debugDisconnect:f("debug-disconnect",60112),debugPause:f("debug-pause",60113),debugRestart:f("debug-restart",60114),debugStart:f("debug-start",60115),debugStepInto:f("debug-step-into",60116),debugStepOut:f("debug-step-out",60117),debugStepOver:f("debug-step-over",60118),debugStop:f("debug-stop",60119),debug:f("debug",60120),deviceCameraVideo:f("device-camera-video",60121),deviceCamera:f("device-camera",60122),deviceMobile:f("device-mobile",60123),diffAdded:f("diff-added",60124),diffIgnored:f("diff-ignored",60125),diffModified:f("diff-modified",60126),diffRemoved:f("diff-removed",60127),diffRenamed:f("diff-renamed",60128),diff:f("diff",60129),diffSidebyside:f("diff-sidebyside",60129),discard:f("discard",60130),editorLayout:f("editor-layout",60131),emptyWindow:f("empty-window",60132),exclude:f("exclude",60133),extensions:f("extensions",60134),eyeClosed:f("eye-closed",60135),fileBinary:f("file-binary",60136),fileCode:f("file-code",60137),fileMedia:f("file-media",60138),filePdf:f("file-pdf",60139),fileSubmodule:f("file-submodule",60140),fileSymlinkDirectory:f("file-symlink-directory",60141),fileSymlinkFile:f("file-symlink-file",60142),fileZip:f("file-zip",60143),files:f("files",60144),filter:f("filter",60145),flame:f("flame",60146),foldDown:f("fold-down",60147),foldUp:f("fold-up",60148),fold:f("fold",60149),folderActive:f("folder-active",60150),folderOpened:f("folder-opened",60151),gear:f("gear",60152),gift:f("gift",60153),gistSecret:f("gist-secret",60154),gist:f("gist",60155),gitCommit:f("git-commit",60156),gitCompare:f("git-compare",60157),compareChanges:f("compare-changes",60157),gitMerge:f("git-merge",60158),githubAction:f("github-action",60159),githubAlt:f("github-alt",60160),globe:f("globe",60161),grabber:f("grabber",60162),graph:f("graph",60163),gripper:f("gripper",60164),heart:f("heart",60165),home:f("home",60166),horizontalRule:f("horizontal-rule",60167),hubot:f("hubot",60168),inbox:f("inbox",60169),issueReopened:f("issue-reopened",60171),issues:f("issues",60172),italic:f("italic",60173),jersey:f("jersey",60174),json:f("json",60175),bracket:f("bracket",60175),kebabVertical:f("kebab-vertical",60176),key:f("key",60177),law:f("law",60178),lightbulbAutofix:f("lightbulb-autofix",60179),linkExternal:f("link-external",60180),link:f("link",60181),listOrdered:f("list-ordered",60182),listUnordered:f("list-unordered",60183),liveShare:f("live-share",60184),loading:f("loading",60185),location:f("location",60186),mailRead:f("mail-read",60187),mail:f("mail",60188),markdown:f("markdown",60189),megaphone:f("megaphone",60190),mention:f("mention",60191),milestone:f("milestone",60192),gitPullRequestMilestone:f("git-pull-request-milestone",60192),mortarBoard:f("mortar-board",60193),move:f("move",60194),multipleWindows:f("multiple-windows",60195),mute:f("mute",60196),noNewline:f("no-newline",60197),note:f("note",60198),octoface:f("octoface",60199),openPreview:f("open-preview",60200),package:f("package",60201),paintcan:f("paintcan",60202),pin:f("pin",60203),play:f("play",60204),run:f("run",60204),plug:f("plug",60205),preserveCase:f("preserve-case",60206),preview:f("preview",60207),project:f("project",60208),pulse:f("pulse",60209),question:f("question",60210),quote:f("quote",60211),radioTower:f("radio-tower",60212),reactions:f("reactions",60213),references:f("references",60214),refresh:f("refresh",60215),regex:f("regex",60216),remoteExplorer:f("remote-explorer",60217),remote:f("remote",60218),remove:f("remove",60219),replaceAll:f("replace-all",60220),replace:f("replace",60221),repoClone:f("repo-clone",60222),repoForcePush:f("repo-force-push",60223),repoPull:f("repo-pull",60224),repoPush:f("repo-push",60225),report:f("report",60226),requestChanges:f("request-changes",60227),rocket:f("rocket",60228),rootFolderOpened:f("root-folder-opened",60229),rootFolder:f("root-folder",60230),rss:f("rss",60231),ruby:f("ruby",60232),saveAll:f("save-all",60233),saveAs:f("save-as",60234),save:f("save",60235),screenFull:f("screen-full",60236),screenNormal:f("screen-normal",60237),searchStop:f("search-stop",60238),server:f("server",60240),settingsGear:f("settings-gear",60241),settings:f("settings",60242),shield:f("shield",60243),smiley:f("smiley",60244),sortPrecedence:f("sort-precedence",60245),splitHorizontal:f("split-horizontal",60246),splitVertical:f("split-vertical",60247),squirrel:f("squirrel",60248),starFull:f("star-full",60249),starHalf:f("star-half",60250),symbolClass:f("symbol-class",60251),symbolColor:f("symbol-color",60252),symbolConstant:f("symbol-constant",60253),symbolEnumMember:f("symbol-enum-member",60254),symbolField:f("symbol-field",60255),symbolFile:f("symbol-file",60256),symbolInterface:f("symbol-interface",60257),symbolKeyword:f("symbol-keyword",60258),symbolMisc:f("symbol-misc",60259),symbolOperator:f("symbol-operator",60260),symbolProperty:f("symbol-property",60261),wrench:f("wrench",60261),wrenchSubaction:f("wrench-subaction",60261),symbolSnippet:f("symbol-snippet",60262),tasklist:f("tasklist",60263),telescope:f("telescope",60264),textSize:f("text-size",60265),threeBars:f("three-bars",60266),thumbsdown:f("thumbsdown",60267),thumbsup:f("thumbsup",60268),tools:f("tools",60269),triangleDown:f("triangle-down",60270),triangleLeft:f("triangle-left",60271),triangleRight:f("triangle-right",60272),triangleUp:f("triangle-up",60273),twitter:f("twitter",60274),unfold:f("unfold",60275),unlock:f("unlock",60276),unmute:f("unmute",60277),unverified:f("unverified",60278),verified:f("verified",60279),versions:f("versions",60280),vmActive:f("vm-active",60281),vmOutline:f("vm-outline",60282),vmRunning:f("vm-running",60283),watch:f("watch",60284),whitespace:f("whitespace",60285),wholeWord:f("whole-word",60286),window:f("window",60287),wordWrap:f("word-wrap",60288),zoomIn:f("zoom-in",60289),zoomOut:f("zoom-out",60290),listFilter:f("list-filter",60291),listFlat:f("list-flat",60292),listSelection:f("list-selection",60293),selection:f("selection",60293),listTree:f("list-tree",60294),debugBreakpointFunctionUnverified:f("debug-breakpoint-function-unverified",60295),debugBreakpointFunction:f("debug-breakpoint-function",60296),debugBreakpointFunctionDisabled:f("debug-breakpoint-function-disabled",60296),debugStackframeActive:f("debug-stackframe-active",60297),circleSmallFilled:f("circle-small-filled",60298),debugStackframeDot:f("debug-stackframe-dot",60298),terminalDecorationMark:f("terminal-decoration-mark",60298),debugStackframe:f("debug-stackframe",60299),debugStackframeFocused:f("debug-stackframe-focused",60299),debugBreakpointUnsupported:f("debug-breakpoint-unsupported",60300),symbolString:f("symbol-string",60301),debugReverseContinue:f("debug-reverse-continue",60302),debugStepBack:f("debug-step-back",60303),debugRestartFrame:f("debug-restart-frame",60304),debugAlt:f("debug-alt",60305),callIncoming:f("call-incoming",60306),callOutgoing:f("call-outgoing",60307),menu:f("menu",60308),expandAll:f("expand-all",60309),feedback:f("feedback",60310),gitPullRequestReviewer:f("git-pull-request-reviewer",60310),groupByRefType:f("group-by-ref-type",60311),ungroupByRefType:f("ungroup-by-ref-type",60312),account:f("account",60313),gitPullRequestAssignee:f("git-pull-request-assignee",60313),bellDot:f("bell-dot",60314),debugConsole:f("debug-console",60315),library:f("library",60316),output:f("output",60317),runAll:f("run-all",60318),syncIgnored:f("sync-ignored",60319),pinned:f("pinned",60320),githubInverted:f("github-inverted",60321),serverProcess:f("server-process",60322),serverEnvironment:f("server-environment",60323),pass:f("pass",60324),issueClosed:f("issue-closed",60324),stopCircle:f("stop-circle",60325),playCircle:f("play-circle",60326),record:f("record",60327),debugAltSmall:f("debug-alt-small",60328),vmConnect:f("vm-connect",60329),cloud:f("cloud",60330),merge:f("merge",60331),export:f("export",60332),graphLeft:f("graph-left",60333),magnet:f("magnet",60334),notebook:f("notebook",60335),redo:f("redo",60336),checkAll:f("check-all",60337),pinnedDirty:f("pinned-dirty",60338),passFilled:f("pass-filled",60339),circleLargeFilled:f("circle-large-filled",60340),circleLarge:f("circle-large",60341),circleLargeOutline:f("circle-large-outline",60341),combine:f("combine",60342),gather:f("gather",60342),table:f("table",60343),variableGroup:f("variable-group",60344),typeHierarchy:f("type-hierarchy",60345),typeHierarchySub:f("type-hierarchy-sub",60346),typeHierarchySuper:f("type-hierarchy-super",60347),gitPullRequestCreate:f("git-pull-request-create",60348),runAbove:f("run-above",60349),runBelow:f("run-below",60350),notebookTemplate:f("notebook-template",60351),debugRerun:f("debug-rerun",60352),workspaceTrusted:f("workspace-trusted",60353),workspaceUntrusted:f("workspace-untrusted",60354),workspaceUnknown:f("workspace-unknown",60355),terminalCmd:f("terminal-cmd",60356),terminalDebian:f("terminal-debian",60357),terminalLinux:f("terminal-linux",60358),terminalPowershell:f("terminal-powershell",60359),terminalTmux:f("terminal-tmux",60360),terminalUbuntu:f("terminal-ubuntu",60361),terminalBash:f("terminal-bash",60362),arrowSwap:f("arrow-swap",60363),copy:f("copy",60364),personAdd:f("person-add",60365),filterFilled:f("filter-filled",60366),wand:f("wand",60367),debugLineByLine:f("debug-line-by-line",60368),inspect:f("inspect",60369),layers:f("layers",60370),layersDot:f("layers-dot",60371),layersActive:f("layers-active",60372),compass:f("compass",60373),compassDot:f("compass-dot",60374),compassActive:f("compass-active",60375),azure:f("azure",60376),issueDraft:f("issue-draft",60377),gitPullRequestClosed:f("git-pull-request-closed",60378),gitPullRequestDraft:f("git-pull-request-draft",60379),debugAll:f("debug-all",60380),debugCoverage:f("debug-coverage",60381),runErrors:f("run-errors",60382),folderLibrary:f("folder-library",60383),debugContinueSmall:f("debug-continue-small",60384),beakerStop:f("beaker-stop",60385),graphLine:f("graph-line",60386),graphScatter:f("graph-scatter",60387),pieChart:f("pie-chart",60388),bracketDot:f("bracket-dot",60389),bracketError:f("bracket-error",60390),lockSmall:f("lock-small",60391),azureDevops:f("azure-devops",60392),verifiedFilled:f("verified-filled",60393),newline:f("newline",60394),layout:f("layout",60395),layoutActivitybarLeft:f("layout-activitybar-left",60396),layoutActivitybarRight:f("layout-activitybar-right",60397),layoutPanelLeft:f("layout-panel-left",60398),layoutPanelCenter:f("layout-panel-center",60399),layoutPanelJustify:f("layout-panel-justify",60400),layoutPanelRight:f("layout-panel-right",60401),layoutPanel:f("layout-panel",60402),layoutSidebarLeft:f("layout-sidebar-left",60403),layoutSidebarRight:f("layout-sidebar-right",60404),layoutStatusbar:f("layout-statusbar",60405),layoutMenubar:f("layout-menubar",60406),layoutCentered:f("layout-centered",60407),target:f("target",60408),indent:f("indent",60409),recordSmall:f("record-small",60410),errorSmall:f("error-small",60411),terminalDecorationError:f("terminal-decoration-error",60411),arrowCircleDown:f("arrow-circle-down",60412),arrowCircleLeft:f("arrow-circle-left",60413),arrowCircleRight:f("arrow-circle-right",60414),arrowCircleUp:f("arrow-circle-up",60415),layoutSidebarRightOff:f("layout-sidebar-right-off",60416),layoutPanelOff:f("layout-panel-off",60417),layoutSidebarLeftOff:f("layout-sidebar-left-off",60418),blank:f("blank",60419),heartFilled:f("heart-filled",60420),map:f("map",60421),mapHorizontal:f("map-horizontal",60421),foldHorizontal:f("fold-horizontal",60421),mapFilled:f("map-filled",60422),mapHorizontalFilled:f("map-horizontal-filled",60422),foldHorizontalFilled:f("fold-horizontal-filled",60422),circleSmall:f("circle-small",60423),bellSlash:f("bell-slash",60424),bellSlashDot:f("bell-slash-dot",60425),commentUnresolved:f("comment-unresolved",60426),gitPullRequestGoToChanges:f("git-pull-request-go-to-changes",60427),gitPullRequestNewChanges:f("git-pull-request-new-changes",60428),searchFuzzy:f("search-fuzzy",60429),commentDraft:f("comment-draft",60430),send:f("send",60431),sparkle:f("sparkle",60432),insert:f("insert",60433),mic:f("mic",60434),thumbsdownFilled:f("thumbsdown-filled",60435),thumbsupFilled:f("thumbsup-filled",60436),coffee:f("coffee",60437),snake:f("snake",60438),game:f("game",60439),vr:f("vr",60440),chip:f("chip",60441),piano:f("piano",60442),music:f("music",60443),micFilled:f("mic-filled",60444),repoFetch:f("repo-fetch",60445),copilot:f("copilot",60446),lightbulbSparkle:f("lightbulb-sparkle",60447),robot:f("robot",60448),sparkleFilled:f("sparkle-filled",60449),diffSingle:f("diff-single",60450),diffMultiple:f("diff-multiple",60451),surroundWith:f("surround-with",60452),share:f("share",60453),gitStash:f("git-stash",60454),gitStashApply:f("git-stash-apply",60455),gitStashPop:f("git-stash-pop",60456),vscode:f("vscode",60457),vscodeInsiders:f("vscode-insiders",60458),codeOss:f("code-oss",60459),runCoverage:f("run-coverage",60460),runAllCoverage:f("run-all-coverage",60461),coverage:f("coverage",60462),githubProject:f("github-project",60463),mapVertical:f("map-vertical",60464),foldVertical:f("fold-vertical",60464),mapVerticalFilled:f("map-vertical-filled",60465),foldVerticalFilled:f("fold-vertical-filled",60465),goToSearch:f("go-to-search",60466),percentage:f("percentage",60467),sortPercentage:f("sort-percentage",60467),attach:f("attach",60468),goToEditingSession:f("go-to-editing-session",60469),editSession:f("edit-session",60470),codeReview:f("code-review",60471),copilotWarning:f("copilot-warning",60472),python:f("python",60473),copilotLarge:f("copilot-large",60474),copilotWarningLarge:f("copilot-warning-large",60475),keyboardTab:f("keyboard-tab",60476),copilotBlocked:f("copilot-blocked",60477),copilotNotConnected:f("copilot-not-connected",60478),flag:f("flag",60479),lightbulbEmpty:f("lightbulb-empty",60480),symbolMethodArrow:f("symbol-method-arrow",60481),copilotUnavailable:f("copilot-unavailable",60482),repoPinned:f("repo-pinned",60483),keyboardTabAbove:f("keyboard-tab-above",60484),keyboardTabBelow:f("keyboard-tab-below",60485),gitPullRequestDone:f("git-pull-request-done",60486),mcp:f("mcp",60487),extensionsLarge:f("extensions-large",60488),layoutPanelDock:f("layout-panel-dock",60489),layoutSidebarLeftDock:f("layout-sidebar-left-dock",60490),layoutSidebarRightDock:f("layout-sidebar-right-dock",60491),copilotInProgress:f("copilot-in-progress",60492),copilotError:f("copilot-error",60493),copilotSuccess:f("copilot-success",60494),chatSparkle:f("chat-sparkle",60495),searchSparkle:f("search-sparkle",60496),editSparkle:f("edit-sparkle",60497),copilotSnooze:f("copilot-snooze",60498),sendToRemoteAgent:f("send-to-remote-agent",60499),commentDiscussionSparkle:f("comment-discussion-sparkle",60500),chatSparkleWarning:f("chat-sparkle-warning",60501),chatSparkleError:f("chat-sparkle-error",60502),collection:f("collection",60503),newCollection:f("new-collection",60504),thinking:f("thinking",60505),build:f("build",60506),commentDiscussionQuote:f("comment-discussion-quote",60507),cursor:f("cursor",60508),eraser:f("eraser",60509),fileText:f("file-text",60510),quotes:f("quotes",60512),rename:f("rename",60513),runWithDeps:f("run-with-deps",60514),debugConnected:f("debug-connected",60515),strikethrough:f("strikethrough",60516),openInProduct:f("open-in-product",60517),indexZero:f("index-zero",60518),agent:f("agent",60519),editCode:f("edit-code",60520),repoSelected:f("repo-selected",60521),skip:f("skip",60522),mergeInto:f("merge-into",60523),gitBranchChanges:f("git-branch-changes",60524),gitBranchStagedChanges:f("git-branch-staged-changes",60525),gitBranchConflicts:f("git-branch-conflicts",60526),gitBranch:f("git-branch",60527),gitBranchCreate:f("git-branch-create",60527),gitBranchDelete:f("git-branch-delete",60527),searchLarge:f("search-large",60528),terminalGitBash:f("terminal-git-bash",60529),windowActive:f("window-active",60530),forward:f("forward",60531),download:f("download",60532),clockface:f("clockface",60533),unarchive:f("unarchive",60534),sessionInProgress:f("session-in-progress",60535),collectionSmall:f("collection-small",60536),vmSmall:f("vm-small",60537),cloudSmall:f("cloud-small",60538),addSmall:f("add-small",60539),removeSmall:f("remove-small",60540),worktreeSmall:f("worktree-small",60541),worktree:f("worktree",60542),screenCut:f("screen-cut",60543),ask:f("ask",60544),openai:f("openai",60545),claude:f("claude",60546),openInWindow:f("open-in-window",60547),newSession:f("new-session",60548),terminalSecure:f("terminal-secure",60549),chatImport:f("chat-import",60550),chatExport:f("chat-export",60551),shareWindow:f("share-window",60552),circleSlashCompact:f("circle-slash-compact",60553),copilotCompact:f("copilot-compact",60554),folderOpenedCompact:f("folder-opened-compact",60555),folderCompact:f("folder-compact",60556),gearCompact:f("gear-compact",60557),gitBranchCompact:f("git-branch-compact",60558),libraryCompact:f("library-compact",60559),recordKeysCompact:f("record-keys-compact",60560),remoteCompact:f("remote-compact",60561),repoForkedCompact:f("repo-forked-compact",60562),repoCompact:f("repo-compact",60563),shieldCompact:f("shield-compact",60564),sparkleCompact:f("sparkle-compact",60565),symbolColorCompact:f("symbol-color-compact",60566),windowCompact:f("window-compact",60567),errorCompact:f("error-compact",60568),warningCompact:f("warning-compact",60569),passCompact:f("pass-compact",60570),important:f("important",60571),importantCompact:f("important-compact",60572),rocketCompact:f("rocket-compact",60573),unpin:f("unpin",60574),addCompact:f("add-compact",60575),attachCompact:f("attach-compact",60576),beakerCompact:f("beaker-compact",60577),checkCompact:f("check-compact",60578),checklistCompact:f("checklist-compact",60579),chevronDownCompact:f("chevron-down-compact",60580),chevronLeftCompact:f("chevron-left-compact",60581),chevronRightCompact:f("chevron-right-compact",60582),chevronUpCompact:f("chevron-up-compact",60583),circleFilledCompact:f("circle-filled-compact",60584),circleSmallFilledCompact:f("circle-small-filled-compact",60585),closeCompact:f("close-compact",60586),collapseAllCompact:f("collapse-all-compact",60587),commentCompact:f("comment-compact",60588),commentUnresolvedCompact:f("comment-unresolved-compact",60589),debugConnectedCompact:f("debug-connected-compact",60590),debugDisconnectCompact:f("debug-disconnect-compact",60591),editCompact:f("edit-compact",60592),fileMediaCompact:f("file-media-compact",60593),gitFetch:f("git-fetch",60594),lightbulbCompact:f("lightbulb-compact",60595),loadingCompact:f("loading-compact",60596),passFilledCompact:f("pass-filled-compact",60597),projectCompact:f("project-compact",60598),refreshCompact:f("refresh-compact",60599),searchCompact:f("search-compact",60600),sessionInProgressCompact:f("session-in-progress-compact",60601),syncCompact:f("sync-compact",60602),terminalCompact:f("terminal-compact",60603),vmPending:f("vm-pending",60604),worktreeCompact:f("worktree-compact",60605),developerTools:f("developer-tools",60606),cloudCompact:f("cloud-compact",60607),agentCompact:f("agent-compact",60608),askCompact:f("ask-compact",60609),settingsCompact:f("settings-compact",60610),vmCompact:f("vm-compact",60611),runCompact:f("run-compact",60612)};var eD={dialogError:f("dialog-error","error"),dialogWarning:f("dialog-warning","warning"),dialogInfo:f("dialog-info","info"),dialogClose:f("dialog-close","close"),treeItemExpanded:f("tree-item-expanded","chevron-down"),treeFilterOnTypeOn:f("tree-filter-on-type-on","list-filter"),treeFilterOnTypeOff:f("tree-filter-on-type-off","list-selection"),treeFilterClear:f("tree-filter-clear","close"),treeItemLoading:f("tree-item-loading","loading"),menuSelection:f("menu-selection","check"),menuSubmenu:f("menu-submenu","chevron-right"),menuBarMore:f("menubar-more","more"),scrollbarButtonLeft:f("scrollbar-button-left","triangle-left"),scrollbarButtonRight:f("scrollbar-button-right","triangle-right"),scrollbarButtonUp:f("scrollbar-button-up","triangle-up"),scrollbarButtonDown:f("scrollbar-button-down","triangle-down"),toolBarMore:f("toolbar-more","more"),quickInputBack:f("quick-input-back","arrow-left"),dropDownButton:f("drop-down-button",60084),symbolCustomColor:f("symbol-customcolor",60252),exportIcon:f("export",60332),workspaceUnspecified:f("workspace-unspecified",60355),newLine:f("newline",60394),thumbsDownFilled:f("thumbsdown-filled",60435),thumbsUpFilled:f("thumbsup-filled",60436),gitFetch:f("git-fetch",60445),lightbulbSparkleAutofix:f("lightbulb-sparkle-autofix",60447),debugBreakpointPending:f("debug-breakpoint-pending",60377),chatImport:f("chat-import",60550),chatExport:f("chat-export",60551)},fp={...rT,...eD};var iT;(t=>{function i(e){return!!e&&typeof e=="object"&&typeof e.id=="string"}t.isThemeColor=i})(iT||={});var Ml;(b=>{b.iconNameSegment="[A-Za-z0-9]+",b.iconNameExpression="[A-Za-z0-9-]+",b.iconModifierExpression="~[A-Za-z]+",b.iconNameCharacter="[A-Za-z0-9~-]";let r=new RegExp(`^(${b.iconNameExpression})(${b.iconModifierExpression})?$`);function o(S){let _=r.exec(S.id);if(!_)return o(fp.error);let[,R,P]=_,q=["codicon","codicon-"+R];return P&&q.push("codicon-modifier-"+P.substring(1)),q}b.asClassNameArray=o;function s(S){return o(S).join(" ")}b.asClassName=s;function a(S){return"."+o(S).join(".")}b.asCSSSelector=a;function l(S){return!!S&&typeof S=="object"&&typeof S.id=="string"&&(typeof S.color>"u"||iT.isThemeColor(S.color))}b.isThemeIcon=l;let d=new RegExp(`^\\$\\((${b.iconNameExpression}(?:${b.iconModifierExpression})?)\\)$`);function c(S){let _=d.exec(S);if(!_)return;let[,R]=_;return{id:R}}b.fromString=c;function u(S){return{id:S}}b.fromId=u;function p(S,_){let R=S.id,P=R.lastIndexOf("~");return P!==-1&&(R=R.substring(0,P)),_&&(R=`${R}~${_}`),{id:R}}b.modify=p;function m(S){let _=S.id.lastIndexOf("~");if(_!==-1)return S.id.substring(_+1)}b.getModifier=m;function h(S,_){return S.id===_.id&&S.color?.id===_.color?.id}b.isEqual=h;function v(S){return S?.id===fp.file.id}b.isFile=v;function I(S){return S?.id===fp.folder.id}b.isFolder=I})(Ml||={});var Wh=new RegExp(`\\$\\(${Ml.iconNameExpression}(?:${Ml.iconModifierExpression})?\\)`,"g"),tD=new RegExp(`(\\\\)?${Wh.source}`,"g");function oT(i){return i.replace(tD,(t,e)=>e?t:`\\${t}`)}var Zne=new RegExp(`\\\\${Wh.source}`,"g");var ere=new RegExp(`(\\s)?(\\\\)?${Wh.source}(\\s)?`,"g");var tre=new RegExp(`\\$\\(${Ml.iconNameCharacter}+\\)`,"g");var gp=class i{static lift(t){let e=new i(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 Kf("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+=nD(this.supportThemeIcons?oT(t):t).replace(/([ \t]+)/g,(n,r)=>"&nbsp;".repeat(r.length)).replace(/\>/gm,"\\>").replace(/\n/g,e===1?`\\
`:`

`),this}appendMarkdown(t){return this.value+=t,this}appendCodeblock(t,e){return this.value+=`
${rD(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(Zt(e),"g");return t.replace(n,(r,o)=>t.charAt(o-1)!=="\\"?`\\${r}`:r)}};function nD(i){return i.replace(/[\\`*_{}[\]()#+!~]/g,"\\$&").replace(/^([ \t]*)-/gm,"$1\\-")}function Ns(i){return i.replace(/[\\\]]/g,"\\$&")}function rD(i,t){let e=i.match(/^`+/gm)?.reduce((r,o)=>r.length>o.length?r:o).length??0,n=e>=3?e+1:3;return[`${"`".repeat(n)}${t}`,i,`${"`".repeat(n)}`].join(`
`)}function Ye(i){let t=Math.max(0,...(i.match(/`+/g)??[]).map(o=>o.length)),e="`".repeat(t+1),r=i.startsWith("`")||i.endsWith("`")?` ${i} `:i;return`${e}${r}${e}`}function sT(i,t,e){return Math.min(Math.max(i,t),e)}function $h(i){if(i>=1e6){let t=i/1e6,e=Math.floor(t*10)/10;return e%1===0?`${e.toFixed(0)}M`:`${e.toFixed(1)}M`}else{if(i>9e5)return"1M";if(i>=1e3)return`${Math.round(i/1e3)}K`}return i.toString()}function iD(i,t=[],e={}){let r=new mp(i).scan();return new hp(r,i,t,e).parse()}function Us(i,t=[],e={}){let n=new mp(i).scan();if(n.length===0||n[0].type!==11)return new Ll(void 0,i);if(!n.slice(1).some(l=>l.type===11))return new Ll(void 0,i);let o=new hp(n,i,t,e).parse(),s=n[n.length-1],a=s.type===13?i.substring(s.startOffset):"";return new Ll(o,a)}var Ll=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 oD(e.value.value,0).map(n=>n.value)}}getBooleanValue(t){let e=this.getStringValue(t);if(e==="true")return!0;if(e==="false")return!1}};function oD(i,t=0){let e=iD(`[${i}]`),n=t-1,r=[];if(e&&e.type==="sequence")for(let o of e.items)o.type==="scalar"&&r.push({...o,startOffset:o.startOffset+n,endOffset:o.endOffset+n});else r.push({type:"scalar",value:i,rawValue:i,startOffset:t,endOffset:i.length+t,format:"none"});return r}function Ze(i,t,e,n){return{type:i,startOffset:t,endOffset:e,rawValue:n?.rawValue??"",value:n?.value??"",format:n?.format??"none",indent:n?.indent??0}}var mp=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(Ze(13,this.pos,this.pos)),this.tokens}scanLine(){if(this.seenBlockColon=!1,this.peekChar()===`
`){this.tokens.push(Ze(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(Ze(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(Ze(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,r=this.peekChar()==="\r"&&this.input[this.pos+1]===`
`?this.pos+2:this.pos+1;this.tokens.push(Ze(8,n,r)),this.pos=r}return}if(e===0&&this.input.length-this.pos>=3){let n=this.input[this.pos],r=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==="-"&&r==="-"&&o==="-"&&a){this.tokens.push(Ze(11,this.pos,this.pos+3)),this.pos+=3,this.scanLineContent(),this.scanNewline(),this.seenDocumentStart++;return}if(n==="."&&r==="."&&o==="."&&a){this.tokens.push(Ze(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(Ze(4,this.pos,this.pos+1)),this.pos++;else if(t==="}"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Ze(5,this.pos,this.pos+1)),this.pos++;else if(t==="[")this.flowDepth++,this.tokens.push(Ze(6,this.pos,this.pos+1)),this.pos++;else if(t==="]"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Ze(7,this.pos,this.pos+1)),this.pos++;else if(t===","&&this.flowDepth>0)this.tokens.push(Ze(3,this.pos,this.pos+1)),this.pos++;else if(t==="-"&&this.isBlockDash())this.tokens.push(Ze(2,this.pos,this.pos+1)),this.pos++;else if(t===":"&&this.isBlockColon())this.tokens.push(Ze(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(Ze(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="",r=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,r=0;continue}this.pos++;let a=this.input.substring(e,this.pos);this.tokens.push(Ze(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(),r=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),d=parseInt(l,16);l.length===2&&!isNaN(d)?(n+=String.fromCharCode(d),this.pos+=4):(n+="\\x",this.pos+=2),r=0;continue}case"u":{let l=this.input.substring(this.pos+2,this.pos+6),d=parseInt(l,16);l.length===4&&!isNaN(d)?(n+=String.fromCodePoint(d),this.pos+=6):(n+="\\u",this.pos+=2),r=0;continue}case"U":{let l=this.input.substring(this.pos+2,this.pos+10),d=parseInt(l,16);l.length===8&&!isNaN(d)?(n+=String.fromCodePoint(d),this.pos+=10):(n+="\\U",this.pos+=2),r=0;continue}default:n+="\\"+(a??"");break}this.pos+=2,r=0;continue}if(s===`
`||s==="\r"){r>0&&(n=n.substring(0,n.length-r)),r=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==="	"?r++:r=0,n+=s,this.pos++}let o=this.input.substring(e,this.pos);this.tokens.push(Ze(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 r=this.input[this.pos];if(r===`
`||r==="\r"||this.flowDepth>0&&(r===","||r==="}"||r==="]")||this.flowDepth>0&&(r==="{"||r==="[")||r===":"&&this.isBlockColon()||r==="#"&&this.pos>t&&(this.input[this.pos-1]===" "||this.input[this.pos-1]==="	"))break;this.pos++,r!==" "&&r!=="	"&&(e=this.pos)}let n=this.input.substring(t,e);this.tokens.push(Ze(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,r="clip";for(let p=0;p<2;p++)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==="-"&&r==="clip"?(r="strip",this.pos++):m==="+"&&r==="clip"&&(r="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 p=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 I=this.input.substring(p+s,this.pos);a.push(I),I===""?l++:l=0}else a.push(""),l++;this.consumeNewline();continue}if(m===0&&this.input.length-this.pos>=3){let I=this.input[this.pos],b=this.input[this.pos+1],S=this.input[this.pos+2],_=this.input[this.pos+3],R=_===void 0||_===" "||_==="	"||_===`
`||_==="\r";if(I==="-"&&b==="-"&&S==="-"&&R||I==="."&&b==="."&&S==="."&&R){this.pos=p;break}}if(s===0){if(m<=o){this.pos=p;break}s=m}if(m<s){this.pos=p;break}let h=p+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 d;if(t==="|")d=a.join(`
`);else{d="";let p=!1,m=!1,h=!1;for(let v=0;v<a.length;v++){let I=a[v],b=I.length>0&&(I[0]===" "||I[0]==="	");I===""?(d+=`
`,m=!0):v===0?(d=I,p=b,h=!0):m?((p||b)&&h?d+=`
`+I:d+=I,p=b,m=!1,h=!0):b||p?(d+=`
`+I,p=b,h=!0):(d+=" "+I,p=!1,h=!0)}}if(l>0){let p=d.length;for(;p>0&&d[p-1]===`
`;)p--;d=d.substring(0,p)}let c=a.some(p=>p!=="");switch(r){case"clip":c&&(d+=`
`);break;case"keep":c?d+=`
`.repeat(l+1):d=`
`.repeat(l);break;case"strip":break}let u=this.input.substring(e,this.pos);this.tokens.push(Ze(0,e,this.pos,{rawValue:u,value:d,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 r=e-1;r>=0;r--){let o=this.tokens[r];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(Ze(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(Ze(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]}},hp=class{constructor(t,e,n,r){this.tokens=t;this.input=e;this.errors=n;this.options=r;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,r){this.errors.push({message:t,startOffset:e,endOffset:n,code:r})}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 r=this.currentIndent();if(this.peekPastIndent().type===2)return this.parseBlockSequence(r);if(this.looksLikeMapping())return this.parseBlockMapping(r);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,r=t.endOffset;for(;;){let o=this.pos,s=0,a=!1;for(;this.pos<this.tokens.length;){let d=this.currentToken();if(d.type===10)break;if(d.type===8){this.advance();let c=this.currentToken();if(c.type===8){s++;continue}if(c.type===9){let u=this.peek(1);if(u.type===8||u.type===13){s++,this.advance();continue}if(u.type===10)break;if(c.indent>e){a=!0;break}else break}if(c.type===13||c.type===11||c.type===12)break;if(e<0){a=!0;break}break}if(d.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 d=this.advance(),c="-";if(this.currentToken().type===0){let u=this.advance();c="- "+u.value,r=u.endOffset}else r=d.endOffset;s>0?n+=`
`.repeat(s):n+=" ",n+=c;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,r=l.endOffset}return{type:"scalar",value:n,rawValue:this.input.substring(t.startOffset,r),startOffset:t.startOffset,endOffset:r,format:"none"}}parseBlockMapping(t,e=!1){let n=this.currentToken().startOffset,r=[],o=new Set;if(e){let a=this.parseMappingEntry(t);a&&(o.add(a.key.value),r.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),r.push(l)}let s=r.length>0?r[r.length-1].value.endOffset:n;return{type:"map",properties:r,style:"block",startOffset:n,endOffset:s}}parseMappingEntry(t){this.currentToken().type===9&&this.advance();let e=this.expect(0),n=this.scalarFromToken(e),r=this.expect(1);if(r.type!==1){this.emitError(g(144,null),r.startOffset,r.endOffset,"expected-colon");return}let o=this.parseMappingValue(t,r);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,r=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(),d=this.parseSequenceItemValue(t,l);e.push(d),r=d.endOffset}return{type:"sequence",items:e,style:"block",startOffset:n,endOffset:r}}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 r;if(this.currentToken().type===0)r=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(r.endOffset),e.push({key:r,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 r;if(this.currentToken().type===4)r=this.parseFlowMap();else if(this.currentToken().type===6)r=this.parseFlowSeq();else if(this.currentToken().type===0)r=this.parseFlowScalar();else{this.emitError(g(151,null),this.currentToken().startOffset,this.currentToken().endOffset,"unexpected-token"),this.advance();continue}e.push(r),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 r=!1,o=this.pos;for(;o<this.tokens.length;){let a=this.tokens[o];if(a.type===8)r=!0,o++;else if(a.type===9||a.type===10)o++;else break}if(!r||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 aD;(t=>{function i(e,n){return e===n?!0:!e||!n?!1:e.command===n.command&&e.windows===n.windows&&e.linux===n.linux&&e.osx===n.osx&&Eo(e.cwd,n.cwd)&&We(e.env,n.env)&&e.timeout===n.timeout&&Eo(e.sourceUri,n.sourceUri)}t.isEquals=i})(aD||={});var lD={format:0,manifestPath:"plugin.json",hookConfigPath:"hooks.json",pluginRootToken:void 0,pluginRootEnvVar:void 0,parseHooks(i,t,e,n,r){return uT(i,t,n,r)}},dD={format:1,manifestPath:".claude-plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${CLAUDE_PLUGIN_ROOT}",pluginRootEnvVar:"CLAUDE_PLUGIN_ROOT",parseHooks(i,t,e,n,r){return pT(i,t,e,n,r,"${CLAUDE_PLUGIN_ROOT}","CLAUDE_PLUGIN_ROOT")}},cD={format:2,manifestPath:".plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${PLUGIN_ROOT}",pluginRootEnvVar:"PLUGIN_ROOT",parseHooks(i,t,e,n,r){return pT(i,t,e,n,r,"${PLUGIN_ROOT}","PLUGIN_ROOT")}};async function uD(i,t){return await Fl(X(i,".plugin","plugin.json"),t)?cD:i.path.split("/").includes(".claude")||await Fl(X(i,".claude-plugin","plugin.json"),t)?dD:lD}function Wl(i,t){let e=Rn(i.toString());return t?`${e.replace(/#/g,"%23")}#${t}`:e}function pD(i){let t=i.uri.toString();return{type:"agent",id:Wl(i.uri),uri:t,name:i.name,...i.description?{description:i.description}:{}}}function fD(i){let t=i.uri.toString();return{type:"skill",id:Wl(i.uri),uri:t,name:i.name,...i.description?{description:i.description}:{}}}function gD(i){let t=i.uri.toString();return{type:"rule",id:Wl(i.uri),uri:t,name:i.name,...i.description?{description:i.description}:{}}}function mD(i){return{type:"hook",id:Wl(i),uri:i.toString(),name:pe(i)}}function hD(i,t){return{type:"mcpServer",id:Wl(i,`mcp=${encodeURIComponent(t)}`),uri:i.toString(),name:t,enabled:!0,state:{kind:"starting"},mcpApp:ap}}var Hh={paths:[],exclusive:!1};function Nl(i){if(i==null)return Hh;if(typeof i=="string"){let t=i.trim();return t?{paths:[t],exclusive:!1}:Hh}if(Array.isArray(i))return{paths:i.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0),exclusive:!1};if(typeof i=="object"){let t=i;if(Array.isArray(t.paths)){let e=t.paths.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0),n=t.exclusive===!0;return{paths:e,exclusive:n}}}return Hh}function Ul(i,t,e,n){let r=n&&Oa(i,n)?n:i,o=[];e.exclusive||o.push(X(i,t));for(let s of e.paths){let a=en(X(i,s));Oa(a,r)&&o.push(a)}return o}function yD(i){if(!i||typeof i!="object"||Array.isArray(i))return;let t=i;return Object.hasOwn(t,"mcpServers")?t.mcpServers:t}function vD(i){if(!i||typeof i!="object")return;let t=i,e=typeof t.type=="string"?t.type:void 0,n=typeof t.command=="string"?t.command:void 0,r=typeof t.url=="string"?t.url:void 0,o=Array.isArray(t.args)?t.args.filter(u=>typeof u=="string"):void 0,s=t.env&&typeof t.env=="object"?Object.fromEntries(Object.entries(t.env).filter(([,u])=>typeof u=="string"||typeof u=="number"||u===null).map(([u,p])=>[u,p])):void 0,a=typeof t.envFile=="string"?t.envFile:void 0,l=typeof t.cwd=="string"?t.cwd:void 0,d=t.headers&&typeof t.headers=="object"?Object.fromEntries(Object.entries(t.headers).filter(([,u])=>typeof u=="string").map(([u,p])=>[u,p])):void 0,c=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:c}:void 0;if(e==="http"||e==="sse"||!e&&r)return r?{type:"http",url:r,headers:d,dev:c}:void 0}}var SD=/[\s&|<>()^;!`"']/;function bD(i,t,e){if(!i.includes(e))return i;if(!SD.test(t))return i.replaceAll(e,t);let n=Zt(e),r=new RegExp(`(["']?)`+n+"([\\w./\\\\~:-]*)","g");return i.replace(r,(o,s,a)=>{let l=t+a;return s?s+l:'"'+l.replace(/"/g,'\\"')+'"'})}function ID(i,t,e,n){let r=a=>a.replaceAll(e,t),o=i.configuration,s;if(o.type==="stdio"){let a={...o};a.command=r(a.command),a.args&&(a.args=a.args.map(r)),a.cwd&&(a.cwd=r(a.cwd)),a.env={...a.env};for(let[l,d]of Object.entries(a.env))typeof d=="string"&&(a.env[l]=r(d));a.env[n]=t,a.envFile&&(a.envFile=r(a.envFile)),s=a}else{let a={...o};a.url=r(a.url),a.headers&&(a.headers=Object.fromEntries(Object.entries(a.headers).map(([l,d])=>[l,r(d)]))),s=a}return{name:i.name,configuration:s,uri:i.uri,customization:i.customization}}var _D=/\$\{(?![A-Za-z]+:)([A-Z_][A-Z0-9_]*)\}/g;function CD(i){return Ha(i,t=>{if(y.isUri(t))return t;if(typeof t=="string"){let e=t.replace(_D,"${env:$1}");return e!==t?e:void 0}})}var TD={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 xD(i){if(i.type!==void 0&&i.type!=="command")return;let t=typeof i.command=="string"&&i.command.length>0,e=typeof i.bash=="string"&&i.bash.length>0,n=typeof i.powershell=="string"&&i.powershell.length>0,r=typeof i.windows=="string"&&i.windows.length>0,o=typeof i.linux=="string"&&i.linux.length>0,s=typeof i.osx=="string"&&i.osx.length>0;if(!t&&!e&&!n&&!r&&!o&&!s)return;let a=r?i.windows:n?i.powershell:void 0,l=o?i.linux:e?i.bash:void 0,d=s?i.osx:e?i.bash:void 0,c=typeof i.timeout=="number"?i.timeout:typeof i.timeoutSec=="number"?i.timeoutSec:void 0;return{...t&&{command:i.command},...a&&{windows:a},...l&&{linux:l},...d&&{osx:d},...typeof i.env=="object"&&i.env!==null&&{env:i.env},...c!==void 0&&{timeout:c}}}function aT(i,t,e){let n=xD(i);if(!n)return;let r,o=typeof i.cwd=="string"?i.cwd:void 0;if(o){let s=su(o,e);Wt(s)?r=y.file(s):t&&(r=X(t,s))}else r=t;return{...n,cwd:r}}function wD(i,t,e){if(!i||typeof i!="object")return[];let n=i,r=[],o=n.hooks;if(o!==void 0&&Array.isArray(o))for(let s of o){if(!s||typeof s!="object")continue;let a=aT(s,t,e);a&&r.push(a)}else{let s=aT(n,t,e);s&&r.push(s)}return r}function uT(i,t,e,n){if(!t||typeof t!="object")return[];let r=t;if(r.disableAllHooks===!0)return[];let o=r.hooks;if(!o||typeof o!="object")return[];let s=o,a=[],l=mD(i);for(let d of Object.keys(s)){let c=TD[d];if(!c)continue;let u=s[d];if(!Array.isArray(u))continue;let p=[];for(let m of u)p.push(...wD(m,e,n));p.length>0&&a.push({type:c,commands:p,uri:i,originalId:d,customization:l})}return a}function pT(i,t,e,n,r,o,s){let a=e.fsPath,l=t,d=u=>{for(let p of["command","windows","linux","osx"])typeof u[p]=="string"&&(u[p]=bD(u[p],a,o));(!u.env||typeof u.env!="object")&&(u.env={}),u.env[s]=a};for(let u of Object.values(l.hooks??{}))if(Array.isArray(u))for(let p of u){if(!p||typeof p!="object")continue;let m=p;if(Array.isArray(m.hooks))for(let h of m.hooks)d(h);else d(m)}return uT(i,Ha(t,u=>typeof u=="string"?u.replaceAll(o,e.fsPath):void 0),n,r)}async function qh(i,t){try{let e=await t.readFile(i);return yu(e.value.toString())}catch{return}}async function Fl(i,t){try{return await t.resolve(i),!0}catch{return!1}}var yp=".md",lT=".mdc",dT=".instructions.md";async function RD(i,t,e){let n=new Set,r=[],o=async(s,a)=>{if(n.has(s))return;n.add(s);let l;try{l=(await Vh(a,e)).description}catch{}r.push({uri:a,name:s,...l?{description:l}:{}})};if(await Promise.all(t.map(async s=>{let a=y.joinPath(s,"SKILL.md");if(await Fl(a,e)){await o(pe(s),a);return}let l;try{l=await e.resolve(s)}catch{return}!l.isDirectory||!l.children||await Promise.all(l.children.map(async d=>{let c=y.joinPath(d.resource,"SKILL.md");await Fl(c,e)&&await o(pe(d.resource),c)}))})),r.length===0){let s=y.joinPath(i,"SKILL.md");await Fl(s,e)&&await o(pe(i),s)}return r.sort((s,a)=>s.name.localeCompare(a.name)),r}async function ED(i,t){let e=new Set,n=[],r=(o,s)=>{e.has(o)||(e.add(o),n.push({uri:s,name:o}))};for(let o of i){let s;try{s=await t.resolve(o)}catch{continue}if(s.isFile&&Ma(o).toLowerCase()===yp){r(pe(o).slice(0,-yp.length),o);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children)!a.isFile||Ma(a.resource).toLowerCase()!==yp||r(pe(a.resource).slice(0,-yp.length),a.resource)}return n.sort((o,s)=>o.name.localeCompare(s.name)),n}function cT(i){let t=pe(i),e=t.toLowerCase();if(e.endsWith(lT))return t.slice(0,-lT.length);if(e.endsWith(dT))return t.slice(0,-dT.length)}async function PD(i,t){let e=new Set,n=[],r=(o,s)=>{e.has(o)||(e.add(o),n.push({uri:s,name:o}))};for(let o of i){let s;try{s=await t.resolve(o)}catch{continue}if(s.isFile){let a=cT(o);a&&r(a,o);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children){if(!a.isFile)continue;let l=cT(a.resource);l&&r(l,a.resource)}}return n.sort((o,s)=>o.name.localeCompare(s.name)),n}async function AD(i,t){let e=await ED(i,t);if(e.length===0)return e;let n=await Promise.all(e.map(async s=>{try{let{name:a,description:l}=await Bh(s.uri,t);return{uri:s.uri,name:a||s.name,...l?{description:l}:{}}}catch{return s}})),r=new Set,o=[];for(let s of n)r.has(s.name)||(r.add(s.name),o.push(s));return o.sort((s,a)=>s.name.localeCompare(a.name)),o}async function Bh(i,t){let e=pe(i).replace(/(\.agent)?\.md$/i,"");try{let n=await t.readFile(i),r=Us(n.value.toString()),o=r?.getStringValue("name")?.trim()||e,s=r?.getStringValue("description")?.trim(),a=r?.getBooleanValue("user-invocable");return{name:o,description:s,userInvocable:a}}catch{return{name:e}}}async function Vh(i,t){try{let e=await t.readFile(i),n=Us(e.value.toString()),r=n?.getStringValue("name")?.trim()||pe(pr(i)),o=n?.getStringValue("description")?.trim(),s=n?.getBooleanValue("user-invocable");return{name:r,description:o,userInvokable:s}}catch{return{name:pe(pr(i))}}}async function fT(i,t){let e=pe(i).replace(/(\.instructions)?\.md$/i,"");try{let n=await t.readFile(i),r=Us(n.value.toString()),o=r?.getStringValue("name")?.trim()||e,s=r?.getStringValue("description")?.trim(),a=r?.getStringArrayValue("globs")??r?.getStringArrayValue("applyTo")??r?.getStringArrayValue("paths")??void 0,l=r?.getBooleanValue("alwaysApply");return{name:o,description:s,globs:a,alwaysApply:l}}catch{return{name:e}}}async function kD(i,t,e,n,r,o){for(let s of t){let a=await qh(s,n);if(a)return e.parseHooks(s,a,i,r,o)}return[]}async function DD(i,t,e,n){let r=new Map;for(let o of i){let s=await qh(o,n);for(let a of gT(o,s,t,e))r.has(a.name)||r.set(a.name,a)}return[...r.values()].sort((o,s)=>o.name.localeCompare(s.name))}function gT(i,t,e,n){let r=yD(t);if(!r)return[];let o=[];for(let[s,a]of Object.entries(r)){let l=vD(a);if(!l)continue;let d={name:s,configuration:l,uri:i,customization:hD(i,s)};n.pluginRootToken&&n.pluginRootEnvVar&&(d=ID(d,e,n.pluginRootToken,n.pluginRootEnvVar)),d=CD(d),o.push(d)}return o}async function mT(i,t,e,n,r){let o=await uD(i,t),s=await qh(X(i,o.manifestPath),t),a=s&&typeof s=="object"?s:void 0,l=Ul(i,o.hookConfigPath,Nl(a?.hooks),r),d=Ul(i,".mcp.json",Nl(a?.mcpServers),r),c=Ul(i,"skills",Nl(a?.skills),r),u=Ul(i,"agents",Nl(a?.agents),r),p=Ul(i,"rules",Nl(a?.rules),r),m=[],h=a?.mcpServers;h&&typeof h=="object"&&!Array.isArray(h)&&!ye(h,{paths:!0})&&(m=gT(X(i,o.manifestPath),{mcpServers:h},i.fsPath,o));let v=[],I=a?.hooks;if(I&&typeof I=="object"&&!Array.isArray(I)&&!ye(I,{paths:!0})){let q=X(i,o.manifestPath);v=o.parseHooks(q,{hooks:I},i,e,n)}let[b,S,_,R,P]=await Promise.all([v.length>0?Promise.resolve(v):kD(i,l,o,t,e,n),m.length>0?Promise.resolve(m):DD(d,i.fsPath,o,t),RD(i,c,t),AD(u,t),PD(p,t)]);return{hooks:b,mcpServers:S,skills:_.map(MD),agents:R.map(OD),instructions:P.map(LD)}}function OD(i){return{...i,customization:pD(i)}}function MD(i){return{...i,customization:fD(i)}}function LD(i){return{...i,customization:gD(i)}}var yi=$("agentPluginManager");function hT(i){let t=new Map;if(i){for(let n of i)if(n.type!=="mcpServer"&&!(n.enabled===!1||!n.children))for(let r of n.children){if(r.type!=="agent")continue;let o=r.uri.toString();t.has(o)||t.set(o,r)}}let e=[...t.values()];return e.sort((n,r)=>n.name.localeCompare(r.name)||n.uri.toString().localeCompare(r.uri.toString())),e}var vp=$("agentHostOTelService");function Sp(i,t){let e=i??[],n=t??[];if(e.length!==n.length)return!1;let r=new Map;for(let o of e)r.set(o.name,o);for(let o of n){let s=r.get(o.name);if(!s||s.description!==o.description||!We(s.inputSchema,o.inputSchema))return!1}return!0}var Fs=class{constructor(){this._clientId=void 0;this._tools=[]}get clientId(){return this._clientId}get tools(){return this._tools}update(t,e){this._clientId=t,this._tools=e}structuralEquals(t){return Sp(this._tools,t.tools)}};function ND(i,t){let e=i.match(t?/^(?:cd(?: \/d)?|Set-Location(?: -Path)?) (?<dir>"[^"]*"|[^\s]+) *(?:&&|;|\r?\n)\s*(?<suffix>[\s\S]+)$/i:/^cd (?<dir>"[^"]*"|[^\s]+) *(?:&&|\r?\n)\s*(?<suffix>[\s\S]+)$/),n=e?.groups?.dir,r=e?.groups?.suffix;if(n&&r){let o=n;return o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1)),{directory:o,command:r}}}function io(i,t,e){if(!e||!t)return!1;let n=i==="bash",r=i==="powershell";if(!n&&!r)return!1;let o=t.command;if(typeof o!="string")return!1;let s=ND(o,r);return!s||!UD(s.directory,e)?!1:(t.command=s.command,!0)}function UD(i,t){if(!i)return!1;let e=a=>a.replace(/[\\/]+$/,""),n=e(i),r=e(t.fsPath);if(!n||!r)return!1;let o,s;try{o=y.file(n),s=y.file(r)}catch{return!1}return Je.isEqual(o,s)}var yT="ahp-otlp://logs/{level}",vT="ahp-otlp",FD=["trace","debug","info","warn","error","fatal"];function ST(i){switch(i){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 WD(i){let t=i.toLowerCase();return FD.includes(t)?t:void 0}function $D(i){switch(i){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 Ws=class{constructor(t){this.attributes=t}toJSON(){return this.attributes}},bp=class extends T{constructor(){super(...arguments);this._onDidLog=this._register(new w);this.onDidLog=this._onDidLog.event}emit(e){this._onDidLog.fire(e)}},Ip=class extends Gi{constructor(e,n=1){super();this._emitter=e;this.setLevel(n)}trace(e,...n){this.canLog(1)&&this._emit(1,e,n,!0)}debug(e,...n){this.canLog(2)&&this._emit(2,e,n)}info(e,...n){this.canLog(3)&&this._emit(3,e,n)}warn(e,...n){this.canLog(4)&&this._emit(4,e,n)}error(e,...n){if(this.canLog(5)){let r=e instanceof Error?e.stack??e.message:e;this._emit(5,r,n)}}log(e,n){e!==0&&this._emit(e,n,[])}_emit(e,n,r,o=!1){let s,a=r.findIndex(c=>c instanceof Ws);a!==-1&&(s=r[a].attributes,r=r.slice(0,a).concat(r.slice(a+1)));let{severityNumber:l,severityText:d}=$D(e);this._emitter.emit({timeUnixNano:VD(Date.now()),severityNumber:l,severityText:d,body:Cr([n,...r],o),...s?{attributes:s}:void 0})}};function bT(i){return HD([i])}function HD(i){return{resourceLogs:[{resource:{attributes:[]},scopeLogs:[{scope:{name:"vscode.agentHost"},logRecords:i.map(t=>({timeUnixNano:t.timeUnixNano,observedTimeUnixNano:t.timeUnixNano,severityNumber:t.severityNumber,severityText:t.severityText,body:{stringValue:t.body},...t.attributes?{attributes:qD(t.attributes)}:void 0}))}]}]}}function qD(i){return Object.entries(i).map(([t,e])=>({key:t,value:BD(e)}))}function BD(i){switch(typeof i){case"boolean":return{boolValue:i};case"number":return Number.isInteger(i)?{intValue:String(i)}:{doubleValue:i};default:return{stringValue:i}}}function VD(i){return`${i}000000`}function IT(i){let t=/^ahp-otlp:\/\/logs\/([^/?#]+)/i.exec(i);if(t)return WD(t[1])}function _T(i){return`ahp-otlp://logs/${i}`}var sn=class{constructor(){this._entries=new Map;this._earlyResults=new Map}registerAndFire(t,e){if(this._earlyResults.has(t)){let r=this._earlyResults.get(t);return this._earlyResults.delete(t),Promise.resolve(r)}let n=new Ie;return this._entries.set(t,n),e(),n.p}register(t){if(this._earlyResults.has(t)){let r=this._earlyResults.get(t);return this._earlyResults.delete(t),Promise.resolve(r)}let e=this._entries.get(t);e&&!e.isSettled&&e.error(new K);let n=new Ie;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}respondOrBuffer(t,e){this.respond(t,e)||this._earlyResults.set(t,e)}denyAll(t){for(let[,e]of this._entries)e.isSettled||e.complete(t);this._entries.clear(),this._earlyResults.clear()}rejectAll(t){for(let[,e]of this._entries)e.isSettled||e.error(t);this._entries.clear(),this._earlyResults.clear()}};function CT(i){let t=i.data,e=t.kind,n=zD(t.content);if(n)switch(e.type){case"shell_completed":case"shell_detached_completed":{let r=e.description,o=e.shellId;return{content:n,messageText:r?g(2107,null,r):o?g(2108,null,o):g(2106,null)}}case"agent_completed":return{content:n,messageText:g(2105,null)};default:return}}function zD(i){let t=i.trim();return(/^<system_notification>\s*([\s\S]*?)\s*<\/system_notification>$/.exec(t)?.[1]??t).trim()}var jD=["plan","compact","research","rubber-duck"];function KD(i){switch(i){case"plan":return g(2102,null);case"compact":return g(2101,null);case"research":return g(2103,null);case"rubber-duck":return g(2104,null)}}function TT(i){let t=/^\/(plan|compact|research|rubber-duck)(?:$|\s+([\s\S]*))/.exec(i);if(t)return{command:t[1],rest:(t[2]??"").trim()}}var Cp=class{constructor(t,e){this.copilotcliId=t;this._sessionInfo=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(t,e){if(F.provider(t.channel)!==this.copilotcliId)return[];let n=tu(t.text,t.offset);if(!n)return[];let r=F.id(t.channel),o=this._sessionInfo?.hasHistory(r)??!0,s=n.typed,a=this._sessionInfo?.isRubberDuckEnabled?.()??!1,l=[];for(let d of jD)s.length>0&&!d.startsWith(s)||d==="compact"&&!o||d==="rubber-duck"&&!a||l.push({insertText:d==="compact"?"/"+d:"/"+d+" ",rangeStart:0,rangeEnd:n.rangeEnd,attachment:{type:"simple",label:"/"+d,_meta:{command:d,description:KD(d)}}});return l}};function Tp(i,t){if(!t)return;let e=i==="win32"&&t["enabled.windows"]!==void 0?t["enabled.windows"]:t.enabled;if(e!=="on"&&e!=="allowNetwork")return;let n=i==="win32"?t["fileSystem.windows"]:i==="darwin"?t["fileSystem.mac"]:t["fileSystem.linux"],r=n&&typeof n=="object"?n:{},o=new Set(r.denyRead??[]),s=new Set,a=new Set;for(let v of r.denyWrite??[])o.has(v)||s.add(v);for(let v of r.allowWrite??[])!o.has(v)&&!s.has(v)&&a.add(v);for(let v of r.allowRead??[])!o.has(v)&&!s.has(v)&&!a.has(v)&&s.add(v);let l=e==="allowNetwork",d=i!=="darwin",c=t.allowedNetworkDomains,u=t.deniedNetworkDomains,p=!l&&d&&c?.length?[...c]:void 0,m=!l&&d&&u?.length?[...u]:void 0,h=l||!!p||!!m;return{enabled:!0,userPolicy:{filesystem:{...a.size?{readwritePaths:[...a]}:{},...s.size?{readonlyPaths:[...s]}:{},...o.size?{deniedPaths:[...o]}:{}},network:{allowOutbound:h,...h&&p?{allowedHosts:p}:{},...h&&m?{blockedHosts:m}:{}}}}}function xT(i){if(!Array.isArray(i)||i.length!==2)return;let[t,e]=i;if(!(!Number.isInteger(t)||!Number.isInteger(e))&&!(t<0)&&!(e!==-1&&e<t))return{startLine:t,endLine:e}}var GD=[/^\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 zh(i){let t=typeof i=="string"?i:i?.input??i?.patch;if(typeof t!="string"||t.length===0)return[];let e=new Set,n=[];for(let r of t.split(`
`))for(let o of GD){let s=o.exec(r);if(s){let a=s[1];a&&!e.has(a)&&(e.add(a),n.push(a));break}}return n}var JD=new Set(["edit","str_replace","insert","create","apply_patch","git_apply_patch"]),YD=new Set(["edit","str_replace","insert","create"]);function $s(i,t){return JD.has(i)?!0:i==="str_replace_editor"?t!==void 0&&YD.has(t):!1}function xp(i){if(typeof i=="string"){try{i=JSON.parse(i)}catch{return zh(i)}if(typeof i=="string")return zh(i)}if(!i||typeof i!="object")return[];let t=i;if(typeof t.input=="string"||typeof t.patch=="string")return zh(t);let e=i;return typeof e.path=="string"?[e.path]:[]}var $l=new Set(["bash","powershell"]),jh=new Set(["write_bash","write_powershell"]),wT=new Set(["read_bash","read_powershell"]),QD=new Set(["task"]),XD=new Set(["grep","rg","glob"]),ZD=new Set(["report_intent","skill"]);function wp(i){return ZD.has(i)}function Hl(i){return i==="task_complete"}function Rp(i,t){if(t&&t.trim().length>0)return t;let e=i?.summary;return typeof e=="string"&&e.trim().length>0?e:void 0}function Ep(i){return $l.has(i)}function An(i,t){return i.length>t?i.substring(0,t-3)+"...":i}function Bn(i){let t=y.file(i);return`[${pe(t)}](${t})`}function RT(i){return new gp().appendLink(i,An(i,80)).value}function ge(i){return{markdown:i}}function Vn(i){switch(i){case"str_replace_editor":case"edit":case"str_replace":case"insert":return g(2181,null);case"create":return g(2179,null);case"view":return g(2195,null);case"bash":case"powershell":return g(2203,null);case"read_bash":case"read_powershell":return g(2197,null);case"write_bash":return g(2216,null);case"write_powershell":return g(2217,null);case"stop_bash":case"stop_powershell":case"bash_shutdown":case"powershell_shutdown":return g(2207,null);case"list_bash":case"list_powershell":return g(2188,null);case"grep":case"rg":case"glob":return g(2201,null);case"search_code_subagent":return g(2202,null);case"apply_patch":return g(2175,null);case"git_apply_patch":return g(2193,null);case"codeql_checker":return g(2177,null);case"code_review":return g(2178,null);case"reply_to_comment":return g(2198,null);case"think":return g(2211,null);case"report_intent":return g(2199,null);case"report_progress":return g(2200,null);case"web_search":return g(2214,null);case"web_fetch":return g(2184,null);case"update_todo":return g(2213,null);case"show_file":return g(2204,null);case"fetch_copilot_cli_documentation":return g(2183,null);case"propose_work":return g(2194,null);case"task_complete":return g(2210,null);case"ask_user":return g(2176,null);case"skill":return g(2186,null);case"task":return g(2209,null);case"list_agents":return g(2187,null);case"read_agent":return g(2196,null);case"exit_plan_mode":return g(2182,null);case"sql":return g(2206,null);case"lsp":return g(2189,null);case"create_pull_request":return g(2180,null);case"gh-advisory-database":return g(2185,null);case"store_memory":return g(2208,null);case"parallel_validation":return g(2192,null);case"write_agent":return g(2215,null);case"mcp_reload":return g(2190,null);case"mcp_validate":return g(2191,null);case"tool_search_tool_regex":return g(2212,null);default:return i}}function Or(i,t,e){if($l.has(i)){let n=e;if(n?.command){let r=n.command.split(`
`)[0];return ge(g(2162,null,Ye(An(r,80))))}return g(2161,null,t)}if(jh.has(i)){let n=e;if(n?.command){let r=n.command.split(`
`)[0];return ge(g(2174,null,Ye(An(r,80))))}return g(2173,null)}if(wT.has(i))return g(2160,null);switch(i){case"view":{let n=e;if(n?.path){let r=Bn(n.path),o=xT(n.view_range);return o?o.endLine===-1?ge(g(2168,null,r,o.startLine)):o.endLine!==o.startLine?ge(g(2170,null,r,o.startLine,o.endLine)):ge(g(2169,null,r,o.startLine)):ge(g(2167,null,r))}return g(2166,null)}case"edit":{let n=e;return n?.path?ge(g(2150,null,Bn(n.path))):g(2149,null)}case"create":{let n=e;return n?.path?ge(g(2148,null,Bn(n.path))):g(2147,null)}case"grep":{let n=e;return n?.pattern?ge(g(2156,null,Ye(An(n.pattern,80)))):g(2155,null)}case"rg":{let n=e;return n?.pattern?ge(g(2156,null,Ye(An(n.pattern,80)))):g(2155,null)}case"glob":{let n=e;return n?.pattern?ge(g(2154,null,Ye(An(n.pattern,80)))):g(2153,null)}case"apply_patch":case"git_apply_patch":{let n=xp(e);return n.length===1?ge(g(2158,null,Bn(n[0]))):n.length>1?ge(g(2159,null,n.map(Bn).join(", "))):g(2157,null)}case"sql":return e?.description||g(2165,null);case"web_fetch":{let n=e;return n?.url?ge(g(2171,null,RT(n.url))):g(2172,null)}case"exit_plan_mode":return g(2151,null);default:return g(2152,null,t)}}function Pp(i,t,e,n){if(!n)return g(2123,null,t);if($l.has(i)){let r=e;if(r?.command){let o=r.command.split(`
`)[0];return ge(g(2134,null,Ye(An(o,80))))}return g(2133,null,t)}if(jh.has(i)){let r=e;if(r?.command){let o=r.command.split(`
`)[0];return ge(g(2146,null,Ye(An(o,80))))}return g(2145,null)}if(wT.has(i))return g(2132,null);switch(i){case"view":{let r=e;if(r?.path){let o=Bn(r.path),s=xT(r.view_range);return s?s.endLine===-1?ge(g(2140,null,o,s.startLine)):s.endLine!==s.startLine?ge(g(2142,null,o,s.startLine,s.endLine)):ge(g(2141,null,o,s.startLine)):ge(g(2139,null,o))}return g(2138,null)}case"edit":{let r=e;return r?.path?ge(g(2121,null,Bn(r.path))):g(2120,null)}case"create":{let r=e;return r?.path?ge(g(2119,null,Bn(r.path))):g(2118,null)}case"grep":{let r=e;return r?.pattern?ge(g(2128,null,Ye(An(r.pattern,80)))):g(2127,null)}case"rg":{let r=e;return r?.pattern?ge(g(2128,null,Ye(An(r.pattern,80)))):g(2127,null)}case"glob":{let r=e;return r?.pattern?ge(g(2126,null,Ye(An(r.pattern,80)))):g(2125,null)}case"apply_patch":case"git_apply_patch":{let r=xp(e);return r.length===1?ge(g(2130,null,Bn(r[0]))):r.length>1?ge(g(2131,null,r.map(Bn).join(", "))):g(2129,null)}case"sql":return e?.description||g(2137,null);case"web_fetch":{let r=e;return r?.url?ge(g(2143,null,RT(r.url))):g(2144,null)}case"exit_plan_mode":return g(2122,null);default:return g(2124,null,t)}}function eO(i,t){if(i)return`synth-skill-${i}`;let e=t.path??t.name;return`synth-skill-${rn(e).toString(16)}`}function Ap(i,t){let e=eO(t,i),n=g(2205,null),r=Ns(i.name),o=i.path?`[${r}](${y.file(i.path)})`:void 0,s=o?ge(g(2163,null,o)):g(2164,null,i.name),a=o?ge(g(2135,null,o)):g(2136,null,i.name);return{toolCallId:e,toolName:"skill",displayName:n,invocationMessage:s,pastTenseMessage:a}}function ql(i,t,e){if(!(!t&&!e)){if($l.has(i)||jh.has(i)){let n=t,r=n?.command??n?.args;return typeof r=="string"?r:typeof r=="object"&&r!==null&&ye(r,{command:!0})?r.command:e}switch(i){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 kp(i){if($l.has(i))return"terminal";if(QD.has(i))return"subagent";if(XD.has(i))return"search"}function Dp(i){if(!i)return{};let t=typeof i.agent_type=="string"&&i.agent_type.length>0?i.agent_type:void 0,e=typeof i.description=="string"&&i.description.length>0?i.description:void 0;return{agentName:t,description:e}}function Op(i){switch(i){case"powershell":case"write_powershell":case"read_powershell":return"powershell";default:return"shellscript"}}function Dr(i){try{return JSON.stringify(i)}catch{return}}function vi(i){return typeof i=="string"?i:void 0}function ET(i,t){let e=vi(i.path)??vi(i.fileName),n=vi(i.fullCommandText),r=vi(i.intention),o=vi(i.serverName),s=vi(i.toolName);switch(i.kind){case"shell":{let a=n?{command:n}:void 0;io("bash",a,t);let l=typeof a?.command=="string"?a.command:n;return{confirmationTitle:g(2114,null),invocationMessage:r??Or("bash",Vn("bash"),l?{command:l}:void 0),toolInput:l,permissionKind:"shell",permissionPath:e}}case"custom-tool":{let a=typeof i.args=="object"&&i.args!==null?i.args:void 0,l=vi(i.toolName);if(a&&l&&Ep(l)&&typeof a.command=="string"){io(l,a,t);let d=a.command;return{confirmationTitle:g(2114,null),invocationMessage:Or(l,Vn(l),{command:d}),toolInput:d,permissionKind:"shell",permissionPath:e}}return{confirmationTitle:g(2110,null),invocationMessage:ge(g(2109,null,Ye(s??i.kind))),toolInput:Dr(a||i),permissionKind:i.kind,permissionPath:e}}case"write":return{confirmationTitle:g(2117,null),invocationMessage:Or("edit",Vn("edit"),e?{path:e}:void 0),toolInput:Dr(e?{path:e}:i)??void 0,permissionKind:"write",permissionPath:e};case"mcp":{let a=s??g(2111,null);return{confirmationTitle:o?g(2112,null,o):g(2110,null),invocationMessage:o?`${o}: ${a}`:a,toolInput:Dr({serverName:o,toolName:s})??void 0,permissionKind:"mcp",permissionPath:e}}case"read":return{confirmationTitle:g(2113,null),invocationMessage:r??Or("view",Vn("view"),e?{path:e}:void 0),toolInput:Dr(e?{path:e,intention:r}:i)??void 0,permissionKind:"read",permissionPath:e};case"url":{let a=vi(i.url),l=a?URL.canParse(a)?new URL(a).href:a:void 0;return{confirmationTitle:g(2116,null),invocationMessage:ge(g(2115,null)),toolInput:l?JSON.stringify({url:l}):void 0,permissionKind:"url"}}default:return{confirmationTitle:g(2110,null),invocationMessage:ge(g(2109,null,Ye(s??i.kind))),toolInput:Dr(i)??void 0,permissionKind:i.kind,permissionPath:e}}}function PT(i){try{return JSON.stringify(i)}catch{return}}function tO(i){if(i.type!=="user.message")return!1;let t=i.data?.source;return!!t&&t.toLowerCase()!=="user"}function Mp(i,t,e){let n=e?.length?{text:t,origin:{kind:"user"},attachments:e}:{text:t,origin:{kind:"user"}};return{id:i,message:n,responseParts:[],pendingTools:new Map}}function AT(i,t,e,n){if(wp(i))return;let r=t!==void 0?PT(t):void 0,o;if(r)try{o=JSON.parse(r)}catch{}let a=(io(i,o,n)?PT(o):void 0)??r,l=kp(i),d=l==="subagent"?Dp(o):void 0,c=Vn(i);return{toolName:i,displayName:c,invocationMessage:Or(i,c,o),toolInput:ql(i,o,a),toolKind:l,language:l==="terminal"?Op(i):void 0,subagentAgentName:d?.agentName,subagentDescription:d?.description,parameters:o,parentToolCallId:e}}function Bl(i,t){return{id:i.id,message:i.message,responseParts:i.responseParts,usage:void 0,state:t}}async function Kh(i,t,e,n){let r=new Map,o=[],s=new Map;for(let S of e){if(S.type==="tool.execution_complete"){let _=S.data;s.set(_.toolCallId,_)}if(S.type==="tool.execution_start"){let _=S.data,R=AT(_.toolName,_.arguments,_.parentToolCallId,n);if(!R)continue;r.set(_.toolCallId,R);let P=Ne(R.parameters?.command)?R.parameters.command:void 0;$s(_.toolName,P)&&o.push(_.toolCallId)}}let a;if(t&&o.length>0)try{let S=await t.getFileEdits(o);if(S.length>0){a=new Map;for(let _ of S){let R=a.get(_.toolCallId);R||(R=[],a.set(_.toolCallId,R)),R.push(_)}}}catch{}let l=i.toString(),d=[],c=new Map,u=new Map,p=new Map,m,h=S=>{let _=c.get(S);if(!_||(c.delete(S),_.responseParts.length===0))return;let R=u.get(S)??[];R.push(Bl(_,"complete")),u.set(S,R)},v=S=>{let _=c.get(S);return _||(_=Mp(N(),""),c.set(S,_)),_},I=S=>S?v(S):m;for(let S of e)switch(S.type){case"user.message":{if(tO(S))continue;let _=S.data,R=_?.messageId??_?.interactionId??"",P=_?.content??"",q=nO(_?.attachments);if(_?.parentToolCallId){let E=v(_.parentToolCallId);P&&E.responseParts.push({kind:"markdown",id:N(),content:P}),q?.length&&(E.message={...E.message,attachments:q})}else{m&&d.push(Bl(m,"cancelled"));let E=S.id??R;m=Mp(E,P,q)}break}case"assistant.message":{let _=S.data,R=_?.messageId??_?.interactionId??"",P=_?.content??"",q=_?.reasoningText,E=!!_?.toolRequests&&_.toolRequests.length>0,L=S.id??R,U=I(_?.parentToolCallId)??(m=Mp(L,""));q&&U.responseParts.push({kind:"reasoning",id:N(),content:q}),P&&U.responseParts.push({kind:"markdown",id:N(),content:P}),_?.toolRequests?.length&&b(U,_.toolRequests,_.parentToolCallId),!_?.parentToolCallId&&!E&&U===m&&(d.push(Bl(m,"complete")),m=void 0);break}case"subagent.started":{let _=S.data;p.set(_.toolCallId,{agentName:_.agentName,agentDisplayName:_.agentDisplayName,agentDescription:_.agentDescription});break}case"tool.execution_start":break;case"tool.execution_complete":{let _=S.data,R=r.get(_.toolCallId);if(!R)continue;if(r.delete(_.toolCallId),Hl(R.toolName)){let E=I(_.parentToolCallId);if(!E)continue;let L=Rp(R.parameters,_.error?.message??_.result?.content);L&&E.responseParts.push({kind:"markdown",id:N(),content:L}),!_.parentToolCallId&&_.success&&E===m&&(d.push(Bl(m,"complete")),m=void 0);continue}let P=I(_.parentToolCallId);if(!P)continue;let q=kT(_,R,l,a,p.get(_.toolCallId));P.responseParts.push(q),!_.parentToolCallId&&p.has(_.toolCallId)&&h(_.toolCallId);break}case"skill.invoked":{let _=S,R=Ap(_.data,_.id);(m??(m=Mp(N(),""))).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&&(d.push(Bl(m,"cancelled")),m=void 0);for(let S of[...c.keys()])h(S);return{turns:d,subagentTurnsByToolCallId:u};function b(S,_,R){for(let P of _){let q=s.get(P.toolCallId);if(q&&r.has(P.toolCallId))continue;let E=r.get(P.toolCallId)??AT(P.name,P.arguments,R,n);E&&S.responseParts.push(kT(q??{toolCallId:P.toolCallId,success:!0},E,l,a,p.get(P.toolCallId)))}}}function nO(i){if(!i?.length)return;let t=[];for(let e of i){let n=rO(e);n&&t.push(n)}return t.length>0?t:void 0}function rO(i){switch(i.type){case"file":return{type:"resource",uri:y.file(i.path).toString(),label:i.displayName||Ce(i.path),displayKind:Kd(i.path)?.startsWith("image/")?"image":"document"};case"directory":return{type:"resource",uri:y.file(i.path).toString(),label:i.displayName||Ce(i.path),displayKind:"directory"};case"selection":return{type:"resource",uri:y.file(i.filePath).toString(),label:i.displayName,displayKind:"selection",selection:{range:i.selection}};case"blob":{if(i.mimeType.startsWith("text/plain"))return{type:"simple",label:i.displayName??"attachment",modelRepresentation:Ln(i.data).toString()};let t=i.mimeType.startsWith("image/")?"image":void 0;return{type:"embeddedResource",label:i.displayName??"attachment",data:i.data,contentType:i.mimeType,displayKind:t}}default:return}}function kT(i,t,e,n,r){let o=i.error?.message??i.result?.content,s=[];o!==void 0&&s.push({type:"text",text:o});let a=n?.get(i.toolCallId);if(a)for(let d of a){let c=d.kind==="rename"&&d.originalPath?y.file(d.originalPath).toString():y.file(d.filePath).toString(),u=y.file(d.filePath).toString(),p=d.kind!=="create",m=d.kind!=="delete";s.push({type:"fileEdit",before:p?{uri:c,content:{uri:di(e,d.toolCallId,d.filePath,"before")}}:void 0,after:m?{uri:u,content:{uri:di(e,d.toolCallId,d.filePath,"after")}}:void 0,diff:d.addedLines!==void 0||d.removedLines!==void 0?{added:d.addedLines,removed:d.removedLines}:void 0})}r&&s.push({type:"subagent",resource:Qo(e,i.toolCallId),title:r.agentDisplayName,agentName:r.agentName,description:r.agentDescription});let l={status:"completed",toolCallId:i.toolCallId,toolName:t.toolName,displayName:t.displayName,invocationMessage:t.invocationMessage,toolInput:t.toolInput,success:i.success,pastTenseMessage:Pp(t.toolName,t.displayName,t.parameters,i.success),content:s.length>0?s:void 0,error:i.error,confirmed:"not-needed",_meta:{toolKind:t.toolKind,language:t.language,subagentDescription:t.subagentDescription,subagentAgentName:t.subagentAgentName}};return{kind:"toolCall",toolCall:l}}var Vl=class{constructor(t){this.type=1,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=t}},Si=class{constructor(t){this.type=2,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=t,this.entries=new Map}},Lp=class extends T{constructor(){super(...arguments);this.memoryFdCounter=0;this.fdMemory=new Map;this._onDidChangeCapabilities=this._register(new w);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._capabilities=525318;this.root=new Si("");this._onDidChangeFile=this._register(new w);this.onDidChangeFile=this._onDidChangeFile.event;this._bufferedChanges=[]}get capabilities(){return this._capabilities}setReadOnly(e){let n=!!(this._capabilities&2048);e!==n&&(this._capabilities=525314|(e?2048:0),this._onDidChangeCapabilities.fire())}async stat(e){return this._lookup(e,!1)}async readdir(e){let n=this._lookupAsDirectory(e,!1),r=[];return n.entries.forEach((o,s)=>r.push([s,o.type])),r}async readFile(e){let n=this._lookupAsFile(e,!1).data;if(n)return n;throw he("file not found","EntryNotFound")}readFileStream(e){let n=this._lookupAsFile(e,!1).data,r=fr(o=>A.concat(o.map(s=>A.wrap(s))).buffer);return r.end(n),r}async writeFile(e,n,r){let o=pe(e),s=this._lookupParentDirectory(e),a=s.entries.get(o);if(a instanceof Si)throw he("file is directory","EntryIsADirectory");if(!a&&!r.create)throw he("file not found","EntryNotFound");if(a&&r.create&&!r.overwrite)throw he("file exists already","EntryExists");if(a||(a=new Vl(o),s.entries.set(o,a),this._fireSoon({type:1,resource:e})),a.mtime=Date.now(),r.append){a.size+=n.byteLength;let l=a.data??new Uint8Array(0),d=new Uint8Array(l.byteLength+n.byteLength);d.set(l,0),d.set(n,l.byteLength),a.data=d}else a.size=n.byteLength,a.data=n;this._fireSoon({type:0,resource:e})}open(e,n){let r=this._lookup(e,!0),o=vr(n),s=o&&!!n.append;if(r){if(r instanceof Si)throw he("file is directory","EntryIsADirectory")}else{if(!o)throw he("file not found","EntryNotFound");let l=pe(e),d=this._lookupParentDirectory(e);r=new Vl(l),r.data=new Uint8Array(0),d.entries.set(l,r),this._fireSoon({type:1,resource:e})}r.data||(r.data=new Uint8Array(0));let a=this.memoryFdCounter++;return this.fdMemory.set(a,{file:r,resource:e,write:o,append:s}),Promise.resolve(a)}close(e){let n=this.fdMemory.get(e);return n?.write&&(n.file.mtime=Date.now(),n.file.size=n.file.data?.byteLength??0,this._fireSoon({type:0,resource:n.resource})),this.fdMemory.delete(e),Promise.resolve()}read(e,n,r,o,s){let a=this.fdMemory.get(e);if(!a)throw he("No file with that descriptor open","Unavailable");if(!a.file.data)return Promise.resolve(0);let l=A.wrap(a.file.data).slice(n,n+s);return r.set(l.buffer,o),Promise.resolve(l.byteLength)}write(e,n,r,o,s){let a=this.fdMemory.get(e);if(!a)throw he("No file with that descriptor open","Unavailable");let l=A.wrap(r).slice(o,o+s);a.file.data??=new Uint8Array(0);let d=a.append?a.file.data.byteLength:n,c=d+l.byteLength;if(c>a.file.data.byteLength){let u=new Uint8Array(c);u.set(a.file.data,0),a.file.data=u}return a.file.data.set(l.buffer,d),Promise.resolve(l.byteLength)}async rename(e,n,r){if(!r.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 r=pr(e),o=pe(e),s=this._lookupAsDirectory(r,!1);s.entries.delete(o)&&(s.mtime=Date.now(),s.size-=1,this._fireSoon({type:0,resource:r},{resource:e,type:2}))}async mkdir(e){if(this._lookup(e,!0))throw he("file exists already","EntryExists");let n=pe(e),r=pr(e),o=this._lookupAsDirectory(r,!1),s=new Si(n);o.entries.set(s.name,s),o.mtime=Date.now(),o.size+=1,this._fireSoon({type:0,resource:r},{type:1,resource:e})}_lookup(e,n){let r=e.path.split("/"),o=this.root;for(let s of r){if(!s)continue;let a;if(o instanceof Si&&(a=o.entries.get(s)),!a){if(n)return;throw he("file not found","EntryNotFound")}o=a}return o}_lookupAsDirectory(e,n){let r=this._lookup(e,n);if(r instanceof Si)return r;throw he("file not a directory","EntryNotADirectory")}_lookupAsFile(e,n){let r=this._lookup(e,n);if(r instanceof Vl)return r;throw he("file is a directory","EntryIsADirectory")}_lookupParentDirectory(e){let n=pr(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 DT="pending-edit-content";function OT(i,t,e){return y.from({scheme:DT,authority:Zr(A.fromString(i)).toString(),path:`/${encodeURIComponent(t)}/${Zr(A.fromString(e))}`})}function MT(i){let t=new Lp,e=i.registerProvider(DT,t);return{dispose(){e.dispose(),t.dispose()}}}var iO=".copilot",LT=W(iO,"session-state"),oO="<empty />";function sO(i){if(!i?.length)return oO;let t=i.some(n=>n.type==="image"),e=i.some(n=>n.type==="resource");return t&&e?"Tool produced the attached image and file":t?"Tool produced the attached image":"Tool produced the attached file"}function aO(i){switch(i){case"autopilot":return{label:g(2085,null),description:g(2084,null)};case"autopilot_fleet":return{label:g(2087,null),description:g(2086,null)};case"interactive":return{label:g(2092,null),description:g(2091,null)};case"exit_only":return{label:g(2089,null),description:g(2088,null)};default:return}}function NT(i){let t=Ue(i.toolArgs)?Reflect.get(i.toolArgs,"command"):void 0;return Ne(t)?t:void 0}function lO(i,t,e){let n={id:i,title:t.title??i,message:t.description??t.title??i,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 r=ye(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:r,min:t.minItems,max:t.maxItems}}case"string":{if(ye(t,{enum:!0})){let r=t.enumNames,o=t.enum.map((s,a)=>({id:s,label:r?.[a]??s}));return{...n,kind:"single-select",options:o}}if(ye(t,{oneOf:!0})){let r=t.oneOf.map(o=>({id:o.const,label:o.title}));return{...n,kind:"single-select",options:r}}return{...n,kind:"text",format:t.format,min:t.minLength,max:t.maxLength,defaultValue:t.default}}}}function dO(i,t){if(!t||t.state==="skipped")return;let e=t.value;if(i.type==="boolean")return e.kind==="boolean"?e.value:e.kind==="text"?e.value==="true"?!0:e.value==="false"?!1:void 0:void 0;if(i.type==="number"||i.type==="integer"){if(e.kind==="number")return i.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)?i.type==="integer"?Math.trunc(n):n:void 0}return}if(i.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 cO(i){let t=process.env.XDG_STATE_HOME;return t?W(t,LT):W(i,LT)}var uO=/^(?:\d{10,}-copilot-tool-output-[a-z0-9]{6}|copilot-tool-output-\d{10,}-[a-z0-9]{6})\.txt$/i;function pO(i,t){let e=en(y.file(i)),n=en(y.file(t)),r=en(y.joinPath(e,".."));if(!Je.isEqual(r,n))return!1;let o=Math.max(i.lastIndexOf("/"),i.lastIndexOf("\\")),s=o>=0?i.substring(o+1):i;return uO.test(s)}var Hs=class extends T{constructor(e,n,r,o,s,a,l,d){super();this._instantiationService=n;this._logService=r;this._fileService=s;this._environmentService=a;this._configurationService=l;this._telemetryService=d;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._turnCopilotUsageTotalNanoAiu=0;this._steeringMessagesInFlight=new Set;this._pendingSteeringFlips=new Map;this._pendingClientToolCalls=new sn;this._pendingEditContentUris=new Map;this._onMcpNotification=this._register(new w);this.onMcpNotification=this._onMcpNotification.event;this._pendingMcpSamplings=new Set;this._currentMarkdownPartIds=new Map;this._currentReasoningPartIds=new Map;this._hasReportedActivity=!1;this.sessionId=e.rawSessionId,this.sessionUri=e.sessionUri,this._onDidSessionProgress=e.onDidSessionProgress,this._sessionLauncher=e.sessionLauncher,this._launchPlan=e.launchPlan,this._shellManager=e.shellManager,this._workingDirectory=e.workingDirectory,this._customizationDirectory=e.customizationDirectory,this._serverToolHost=e.serverToolHost,this._appliedSnapshot=e.clientSnapshot??{tools:[],plugins:[]},this._clientToolNames=new Set(this._appliedSnapshot.tools.map(c=>c.name)),e.activeClientState?this._activeClientState=e.activeClientState:(this._activeClientState=new Fs,this._activeClientState.update(void 0,this._appliedSnapshot.tools)),this._databaseRef=o.openDatabase(e.sessionUri),this._register(k(()=>this._databaseRef.dispose())),this._sessionDataDir=o.getSessionDataDir(e.sessionUri),this._editTracker=this._instantiationService.createInstance(li,e.sessionUri.toString(),this._databaseRef.object),this._mcpCustomizations=this._register(new lp({providerId:this.sessionUri.scheme,sessionId:this.sessionId,resolveChildId:e.resolveMcpChildId,emit:c=>this._emitAction(c)})),this._register(k(()=>this._denyPendingPermissions())),this._register(k(()=>this._shellManager?.dispose())),this._register(k(()=>this._cancelPendingUserInputs())),this._register(k(()=>this._cancelPendingElicitations())),this._register(k(()=>this._cancelPendingPlanReviews())),this._register(k(()=>this._drainPendingSteeringFlips())),this._register(k(()=>this._cancelPendingMcpSamplings())),this._shellManager&&this._register(this._shellManager.onDidAssociateTerminal(({toolCallId:c,terminalUri:u,displayName:p})=>{let m=this._activeToolCalls.get(c);m&&(m.content.push({type:"terminal",resource:u,title:p}),this._emitAction({type:"session/toolCallContentChanged",turnId:this._turnId,toolCallId:c,content:m.content}))})),this._register(k(()=>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 r=N();return this._emitAction({type:"session/turnStarted",turnId:r,message:e.message,queuedMessageId:e.id}),this.resetTurnState(r),r}_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,r]of this._pendingSteeringFlips)if(r.message.text===e)return this._pendingSteeringFlips.delete(n),r}}_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._turnCopilotUsageTotalNanoAiu=0,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 xp(e).map(n=>this._resolveEditFilePath(n))}_resolveEditFilePath(e){return Wt(e)||!this._workingDirectory||this._workingDirectory.scheme!==ie.file?e:W(this._workingDirectory.fsPath,e)}_sendToolInvokedTelemetry(e,n,r){let o;e?o="success":n==="rejected"||n==="denied"||n==="cancelled"?o="userCancelled":o="error";let s=this._clientToolNames.has(r.toolName),a=r.mcpServerName?"mcp":s?"client":"agentHost",l=Date.now()-r.startTimeMs;this._telemetryService.publicLog2("languageModelToolInvoked",{result:o,chatSessionId:this.sessionUri.toString(),toolId:r.toolName,toolExtensionId:void 0,toolSourceKind:a,invocationTimeMs:l})}emitInitialMarkdown(e){this._emitMarkdownDelta(e)}_emitMarkdownDelta(e,n){let r=n??"",o=this._currentMarkdownPartIds.get(r);if(!o){o=N(),this._currentMarkdownPartIds.set(r,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 r=n??"",o=this._currentReasoningPartIds.get(r);if(!o){o=N(),this._currentReasoningPartIds.set(r,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(r,{toolCallId:o})=>{try{return await this._pendingClientToolCalls.register(o)}catch(s){throw this._logService.error(s,`[Copilot:${this.sessionId}] Failed in client tool handler: tool=${n.name}, toolCallId=${o}`),s}}}))}_createServerSdkTools(){let e=this._serverToolHost;if(!e)return[];let n=this.sessionUri.toString();return e.definitions.map(r=>({name:r.name,description:r.description??"",parameters:r.inputSchema??{type:"object",properties:{}},handler:async o=>{try{return{textResultForLlm:e.executeTool(n,r.name,o),resultType:"success"}}catch(s){let a=s instanceof Error?s.message:String(s);return this._logService.error(s,`[Copilot:${this.sessionId}] Failed in server tool handler: tool=${r.name}`),{textResultForLlm:a,resultType:"failure",error:a}}}}))}handleClientToolCallComplete(e,n){let r=n.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
`)??"",o=n.content?.filter(a=>a.type==="embeddedResource").map(a=>({data:a.data,mimeType:a.contentType,type:/^image(\/|$)/.test(a.contentType)?"image":"resource"})),s=r.trim()?r:sO(o);n.success?this._pendingClientToolCalls.respondOrBuffer(e,{textResultForLlm:s,resultType:"success",binaryResultsForLlm:o?.length?o:void 0}):this._pendingClientToolCalls.respondOrBuffer(e,{textResultForLlm:r.trim()?r:n.error?.message||"Tool call failed",resultType:"failure",error:n.error?.message,binaryResultsForLlm:o?.length?o:void 0})}async initializeSession(){let e=await this._sessionLauncher.launch(this._launchPlan,this._createRuntimeAdapter());if(this._store.isDisposed)throw e.dispose(),new K;this._wrapper=this._register(e),this._subscribeToEvents(),this._subscribeForLogging(),this._serverToolHost?.advertise(this.sessionUri.toString())}_createRuntimeAdapter(){return{handlePermissionRequest:e=>this._handlePermissionRequest(e),handleExitPlanModeRequest:(e,n)=>this._handleExitPlanModeRequest(e,n),handleUserInputRequest:(e,n)=>this._handleUserInputRequest(e,n),handleElicitationRequest:e=>this._handleElicitationRequest(e),requestUnsandboxedCommandConfirmation:e=>this._requestUnsandboxedCommandConfirmation(e),createClientSdkTools:()=>this._createClientSdkTools(),createServerSdkTools:()=>this._createServerSdkTools(),handlePreToolUse:e=>this._handlePreToolUse(e),handlePostToolUse:e=>this._handlePostToolUse(e)}}async send(e,n,r,o){r&&(this._turnId=r,this._turnCopilotUsageTotalNanoAiu=0),this._logService.info(`[Copilot:${this.sessionId}] sendMessage called: "${e.substring(0,100)}${e.length>100?"...":""}" (${n?.length??0} attachments)`);let s=TT(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}this._completeActiveTurn();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(this._configurationService.getRootValue(jt,"rubberDuck")!==!0)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(tr):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:Fi(A.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),r=n.scheme==="file"?n.fsPath:n.toString(),o=e.label??r;if(e.selection)try{let a=await this._readSelectedText(n,e.selection.range);return{type:"selection",filePath:r,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:r,displayName:o}}return e.displayKind==="selection"?{type:"file",path:r,displayName:o}:{type:e.displayKind==="directory"?"directory":"file",path:r,displayName:o}}async _readSelectedText(e,n){let o=(await this._fileService.readFile(e)).value.toString(),s=iS(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 r=Math.max(0,Math.min(n.line,e.length-1)),o=0;for(let a=0;a<r;a++)o+=e[a].length;let s=e[r].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 Kh(this.sessionUri,n,e,this._workingDirectory)).turns}async getSubagentMessages(e){let n=await this._wrapper.session.getEvents(),r;try{r=this._databaseRef.object}catch{}return(await Kh(this.sessionUri,r,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,r){this._logService.info(`[Copilot:${this.sessionId}] Changing model to: ${e}`),await this._wrapper.session.setModel(e,{reasoningEffort:n,contextTier:r})}async handleMcpRequest(e,n,r){let o=this._wrapper.session.rpc.mcp.apps;switch(n){case"tools/list":return o.listTools({serverName:e,originServerName:e});case"tools/call":{let s=r&&typeof r.name=="string"?r.name:void 0;if(!s)throw new Error("tools/call missing 'name' parameter");let a=r?r.arguments:void 0,l=Ue(a)?a:void 0;return o.callTool({serverName:e,toolName:s,arguments:l,originServerName:e})}case"resources/read":{let s=r&&typeof r.uri=="string"?r.uri:void 0;if(!s)throw new Error("resources/read missing 'uri' parameter");return o.readResource({serverName:e,uri:s})}case"resources/list":return{resources:[]};case"resources/templates/list":return{resourceTemplates:[]};case"sampling/createMessage":return this._handleSamplingCreateMessage(e,r);default:throw new Error(`Method not found: ${n}`)}}async _handleSamplingCreateMessage(e,n){if(!n)throw new Error("sampling/createMessage missing params");let r=N(),o=N();this._pendingMcpSamplings.add(r);try{let s=await this._wrapper.session.rpc.mcp.executeSampling({requestId:r,serverName:e,mcpRequestId:o,request:n});if(s.action==="success")return s.result??null;throw new Error(`sampling/createMessage ${s.action}${s.error?`: ${s.error}`:""}`)}finally{this._pendingMcpSamplings.delete(r)}}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(r){throw this._logService.error(r,`[Copilot:${this.sessionId}] rpc.agent.select failed: name=${n}`),r}}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 r=this._getInternalSessionResourcePath(e);if(r)return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving internal session resource ${r}`),{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"&&pO(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"};if(e.kind==="custom-tool"&&typeof e.toolName=="string"&&this._serverToolHost?.toolNames.includes(e.toolName))return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving server tool ${e.toolName}`),{kind:"approve-once"};let o=e.kind==="shell"||e.kind==="custom-tool"&&typeof e.toolName=="string"&&Ep(e.toolName);this._logService.info(`[Copilot:${this.sessionId}] Requesting confirmation for tool call: ${n}`);let s=new Ie;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:d,permissionKind:c,permissionPath:u}=ET(e,this._workingDirectory),p=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:Vn(m),invocationMessage:l,toolInput:d,confirmationTitle:a,edits:p},permissionKind:c,permissionPath:u,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 r=en(y.file(cO(this._environmentService.userHome.fsPath))),o=en(y.joinPath(r,this.sessionId));if(!Je.isEqualOrParent(o,r))return;let s=en(y.file(n));return Je.isEqualOrParent(s,o)?n:void 0}_isSessionAttachmentPath(e){let n=en(y.joinPath(this._sessionDataDir,yc)),r=en(y.file(e));return Je.isEqualOrParent(r,n)}async _isShellSandboxedByDefault(){if(this._configurationService.getRootValue(jt,"enableCustomTerminalTool")===!0)return this._shellManager?this._shellManager.getOrCreateSandboxEngine().isEnabled():!1;let n=this._configurationService.getRootValue(Rr,"sandbox");return Tp(process.platform,n)!==void 0}async _buildEditsForPermission(e,n){if(e.kind!=="write")return;let r=typeof e.fileName=="string"?e.fileName:void 0,o=typeof e.newFileContents=="string"?e.newFileContents:void 0;if(!r||o===void 0)return;let s=y.file(r),a=s.toString(),l=!1;try{l=await this._fileService.exists(s)}catch(p){this._logService.warn(`[Copilot:${this.sessionId}] Failed to check file for edit preview: ${r}`,p)}let d=OT(this.sessionUri.toString(),n,r);try{await this._fileService.writeFile(d,A.fromString(o))}catch(p){this._logService.warn(`[Copilot:${this.sessionId}] Failed to write pending edit content for ${r}`,p);return}if(!this._pendingPermissions.has(n)){this._fileService.del(d).catch(p=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to delete orphaned pending edit content: ${d.toString()}`,p)});return}this._pendingEditContentUris.set(n,d);let c=typeof e.diff=="string"?gO(e.diff):void 0;return{items:[{...l?{before:{uri:a,content:{uri:a}}}:{},after:{uri:a,content:{uri:d.toString()}},...c?{diff:c}:{}}]}}respondToPermissionRequest(e,n){let r=this._pendingPermissions.get(e);return r?(this._pendingPermissions.delete(e),this._deletePendingEditContent(e),r.complete(n),!0):!1}async _requestUnsandboxedCommandConfirmation(e){let n=new Ie;this._pendingPermissions.set(e.toolCallId,n);let r=Vn(e.toolName),o=e.blockedDomains?.length?e.blockedDomains.join(", "):void 0,s=o?g(2099,null,o):g(2100,null),a=e.reason?g(2098,null,e.reason):o?g(2096,null,o):g(2097,null);return this._onDidSessionProgress.fire({kind:"pending_confirmation",session:this.sessionUri,state:{status:"pending-confirmation",toolCallId:e.toolCallId,toolName:e.toolName,displayName:r,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(),It,"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=N(),a=N();this._logService.info(`[Copilot:${this.sessionId}] User input request: requestId=${s}, question="${o}"`);let l=new Ie;this._pendingUserInputs.set(s,{deferred:l,questionId:a});let d={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:d});let c=await l.p;if(this._logService.info(`[Copilot:${this.sessionId}] User input response: requestId=${s}, response=${c.response}`),c.response!=="accept"||!c.answers)return{answer:"",wasFreeform:!0};let u=c.answers[a];if(!u||u.state==="skipped")return{answer:"",wasFreeform:!0};let{value:p}=u;if(p.kind==="text")return{answer:p.value,wasFreeform:!0};if(p.kind==="selected"){let m=!e.choices?.includes(p.value);return{answer:p.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(),It,"autoApprove")==="autopilot")return{action:"cancel"};let r=e.message.substring(0,100);try{let o=N();this._logService.info(`[Copilot:${this.sessionId}] Elicitation request: requestId=${o}, mode=${e.mode??"form"}, source=${e.elicitationSource??"<unknown>"}, message="${r}"`);let s=e.mode==="url"?void 0:e.requestedSchema,a=new Set(s?.required??[]),l=s?Object.entries(s.properties).map(([h,v])=>lO(h,v,a.has(h))):void 0,d=new Ie;this._pendingElicitations.set(o,{deferred:d,schema:s});let c={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:c});let u=await d.p;if(this._logService.info(`[Copilot:${this.sessionId}] Elicitation response: requestId=${o}, response=${u.response}`),u.response==="decline")return{action:"decline"};if(u.response!=="accept")return{action:"cancel"};let p=u.answers??{};if(!s){let h=p.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 I=dO(v,p[h]);I!==void 0&&(m[h]=I)}return{action:"accept",content:m}}catch(o){throw this._logService.error(o,`[Copilot:${this.sessionId}] Failed to handle elicitation request: message="${r}"`),o}}respondToUserInputRequest(e,n,r){let o=this._pendingPlanReviews.get(e);if(o)return this._pendingPlanReviews.delete(e),o.deferred.complete(this._resolveExitPlanMode(o,n,r)),!0;let s=this._pendingElicitations.get(e);if(s)return this._pendingElicitations.delete(e),s.deferred.complete({response:n,answers:r}),!0;let a=this._pendingUserInputs.get(e);return a?(this._pendingUserInputs.delete(e),a.deferred.complete({response:n,answers:r}),!0):!1}_resolveExitPlanMode(e,n,r){if(n!=="accept")return{approved:!1};let o=r?.[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(p=>p.trim().length>0)?.trim();else if(s.kind==="text")l=s.value.trim()||void 0;else return{approved:!1};let d=a&&e.actions.includes(a)?a:e.actions.includes(e.recommendedAction)?e.recommendedAction:void 0;return l?{approved:!1,feedback:l,...d?{selectedAction:d}:{}}:d?{approved:!0,selectedAction:d,...d==="autopilot"||d==="autopilot_fleet"?{autoApproveEdits:!0}:{}}:{approved:!1}}async _handlePreToolUse(e){try{if($s(e.toolName,NT(e))){let n=this._getEditFilePaths(e.toolArgs);await Promise.all(n.map(r=>this._editTracker.trackEditStart(r)))}}catch(n){throw this._logService.error(n,`[Copilot:${this.sessionId}] Failed in onPreToolUse: tool=${e.toolName}`),n}}async _handlePostToolUse(e){try{if($s(e.toolName,NT(e))){let n=this._getEditFilePaths(e.toolArgs);await Promise.all(n.map(r=>this._editTracker.completeEdit(r)))}}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(r=>{let o=CT(r);if(!o){this._logService.trace(`[Copilot:${n}] Ignoring system.notification kind=${r.data.kind.type}`);return}if(this._logService.info(`[Copilot:${n}] System notification received: kind=${r.data.kind.type}`),this._turnId){this._emitAction({type:"session/responsePart",turnId:this._turnId,part:{kind:"systemNotification",content:o.content}});return}let s=N();this.resetTurnState(s),this._emitAction({type:"session/turnStarted",turnId:s,message:{text:o.messageText,origin:{kind:"systemNotification"}}})})),this._register(e.onUserMessage(r=>{if(r.data.source&&r.data.source.toLowerCase()!=="user")return;let o=this._takeMatchingPendingSteering(r.data.content);o&&this._beginSteeringTurn(o),this._turnId&&this._databaseRef.object.setTurnEventId(this._turnId,r.id)})),this._register(e.onMessageDelta(r=>{this._logService.trace(`[Copilot:${n}] delta: ${r.data.deltaContent}`),!this._shouldDropUnmappedSubagentEvent(r,"assistant.message_delta")&&this._emitMarkdownDelta(r.data.deltaContent,this._parentToolCallIdForSubagentEvent(r))})),this._register(e.onMessage(r=>{if(this._logService.info(`[Copilot:${n}] Full message received: ${r.data.content.length} chars`),!r.data.content||this._shouldDropUnmappedSubagentEvent(r,"assistant.message"))return;let o=this._parentToolCallIdForSubagentEvent(r),s=o??"";if(this._currentMarkdownPartIds.has(s))return;let a=N();this._currentMarkdownPartIds.set(s,a),this._emitAction({type:"session/responsePart",turnId:this._turnId,part:{kind:"markdown",id:a,content:r.data.content}},o)})),this._register(e.onToolStart(r=>{if(wp(r.data.toolName)){if(this._logService.trace(`[Copilot:${n}] Tool started (hidden): ${r.data.toolName}`),r.data.toolName==="report_intent"){let v=r.data.arguments?.intent;typeof v=="string"&&v.length>0&&(this._hasReportedActivity=!0,this._emitAction({type:"session/activityChanged",activity:v}))}return}this._logService.info(`[Copilot:${n}] Tool started: ${r.data.toolName}`);let o=r.data.arguments!==void 0?Dr(r.data.arguments):void 0,s;if(o)try{s=JSON.parse(o)}catch{}io(r.data.toolName,s,this._workingDirectory)&&(o=Dr(s));let a=Vn(r.data.toolName);if(this._shouldDropUnmappedSubagentEvent(r,"tool.execution_start"))return;let l=this._parentToolCallIdForSubagentEvent(r);if(this._activeToolCalls.set(r.data.toolCallId,{toolName:r.data.toolName,displayName:a,parameters:s,content:[],parentToolCallId:l,startTimeMs:Date.now(),mcpServerName:r.data.mcpServerName,meta:void 0}),Hl(r.data.toolName)){let v=l??"";this._currentMarkdownPartIds.delete(v),this._currentReasoningPartIds.delete(v);return}let d=kp(r.data.toolName),c=d==="subagent"?Dp(s):void 0,u,p=this._clientToolNames.has(r.data.toolName);if(p&&this._activeClientState.clientId)u={kind:"client",clientId:this._activeClientState.clientId};else if(r.data.mcpServerName){let v=this._mcpCustomizations.customizationIdForServer(r.data.mcpServerName);v!==void 0&&(u={kind:"mcp",customizationId:v})}this._currentMarkdownPartIds.delete(l??""),this._currentReasoningPartIds.delete(l??"");let m={toolKind:d,language:d==="terminal"?Op(r.data.toolName):void 0};c?.description&&(m.subagentDescription=c.description),c?.agentName&&(m.subagentAgentName=c.agentName),o!==void 0&&(m.toolArguments=o),r.data.mcpServerName&&(m.mcpServerName=r.data.mcpServerName),r.data.mcpToolName&&(m.mcpToolName=r.data.mcpToolName);let h=this._activeToolCalls.get(r.data.toolCallId);if(h&&(h.meta=m),this._emitAction({type:"session/toolCallStart",turnId:this._turnId,toolCallId:r.data.toolCallId,toolName:r.data.toolName,displayName:a,contributor:u,_meta:m},l),p&&!u){this._logService.warn(`[Copilot:${n}] Client tool '${r.data.toolName}' started with no connected client; failing it immediately.`),this._activeToolCalls.delete(r.data.toolCallId),this._emitAction({type:"session/toolCallReady",turnId:this._turnId,toolCallId:r.data.toolCallId,invocationMessage:Or(r.data.toolName,a,s),toolInput:ql(r.data.toolName,s,o),confirmed:"not-needed"},l),this._emitAction({type:"session/toolCallComplete",turnId:this._turnId,toolCallId:r.data.toolCallId,result:{success:!1,pastTenseMessage:`${a} failed`,error:{message:`No client was connected to run ${a}`}}},l),this._pendingClientToolCalls.respondOrBuffer(r.data.toolCallId,{textResultForLlm:`No client was connected to run ${a}.`,resultType:"failure",error:"No client connected"});return}u?.kind!=="client"&&this._emitAction({type:"session/toolCallReady",turnId:this._turnId,toolCallId:r.data.toolCallId,invocationMessage:Or(r.data.toolName,a,s),toolInput:ql(r.data.toolName,s,o),confirmed:"not-needed"},l)})),this._register(e.onToolComplete(async r=>{let o=this._activeToolCalls.get(r.data.toolCallId);if(!o)return;let s=o.parentToolCallId??this._parentToolCallIdForSubagentEvent(r);if(!s&&r.agentId){this._logService.warn(`[Copilot:${this.sessionId}] Dropping tool.execution_complete for unknown subagent agentId=${r.agentId}`);return}this._logService.info(`[Copilot:${n}] Tool completed: ${r.data.toolCallId}`),this._activeToolCalls.delete(r.data.toolCallId);let a=o.displayName,l=r.data.error?.message??r.data.result?.content;if(Hl(o.toolName)){this._sendToolInvokedTelemetry(r.data.success,r.data.error?.code,o);let h=Rp(o.parameters,l);h&&this._emitAction({type:"session/responsePart",turnId:this._turnId,part:{kind:"markdown",id:N(),content:h}});return}let d=[...o.content];l!==void 0&&d.push({type:"text",text:l});let c=Ne(o.parameters?.command)?o.parameters.command:void 0,u=$s(o.toolName,c)?this._getEditFilePaths(o.parameters):[];for(let h of u)try{let v=await this._editTracker.takeCompletedEdit(this._turnId,r.data.toolCallId,h);v&&d.push(v)}catch(v){this._logService.warn(`[Copilot:${n}] Failed to take completed edit`,v)}if(Ep(o.toolName)&&this._shellManager){let h=this._shellManager.getTerminalUriForToolCall(r.data.toolCallId);h&&!d.some(v=>v.type==="terminal"&&v.resource===h)&&d.push({type:"terminal",resource:h,title:o.displayName})}this._sendToolInvokedTelemetry(r.data.success,r.data.error?.code,o);let p=r.data.toolDescription?._meta?.ui?.resourceUri,m=o.meta;if(p){let h={resourceUri:p};if(o.mcpServerName){let v=this._mcpCustomizations.channelForServer(o.mcpServerName);v!==void 0&&(h.channel=v)}m={...o.meta??{},ui:h}}this._emitAction({type:"session/toolCallComplete",turnId:this._turnId,toolCallId:r.data.toolCallId,result:{success:r.data.success,pastTenseMessage:Pp(o.toolName,a,o.parameters,r.data.success),content:d.length>0?d:void 0,error:r.data.error},_meta:m},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(r=>{this._logService.info(`[Copilot:${n}] Skill invoked: ${r.data.name} (${r.data.path})`);let o=Ap(r.data,r.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(r=>{r.agentId&&this._parentToolCallIdsByAgentId.set(r.agentId,r.data.toolCallId),this._logService.info(`[Copilot:${n}] Subagent started: toolCallId=${r.data.toolCallId}, agent=${r.data.agentName}`),this._onDidSessionProgress.fire({kind:"subagent_started",session:this.sessionUri,toolCallId:r.data.toolCallId,agentName:r.data.agentName,agentDisplayName:r.data.agentDisplayName,agentDescription:r.data.agentDescription})})),this._register(e.onSessionError(r=>{this._logService.error(`[Copilot:${n}] Session error: ${r.data.errorType} - ${r.data.message}`);let o=q_(r.data)??H_(r.data.message);this._emitAction({type:"session/error",turnId:this._turnId,error:{errorType:r.data.errorType,message:xl(r.data.message),stack:r.data.stack,...o?{_meta:o}:{}}})})),this._register(e.onUsage(r=>{let o={};typeof r.data.cost=="number"&&(o.cost=r.data.cost);let s=r.data.copilotUsage;typeof s?.totalNanoAiu=="number"&&(this._turnCopilotUsageTotalNanoAiu+=s.totalNanoAiu,o.copilotUsage={...s,totalNanoAiu:this._turnCopilotUsageTotalNanoAiu}),this._logService.trace(`[Copilot:${n}] Usage: model=${r.data.model}, in=${r.data.inputTokens??"?"}, out=${r.data.outputTokens??"?"}, cacheRead=${r.data.cacheReadTokens??"?"}, cost=${r.data.cost??"?"}, totalNanoAiu=${o.copilotUsage?this._turnCopilotUsageTotalNanoAiu:"?"}`);let a={inputTokens:r.data.inputTokens,outputTokens:r.data.outputTokens,model:r.data.model,cacheReadTokens:r.data.cacheReadTokens,...Object.keys(o).length>0?{_meta:o}:{}};this._emitAction({type:"session/usage",turnId:this._turnId,usage:a})})),this._register(e.onReasoningDelta(r=>{this._logService.trace(`[Copilot:${n}] Reasoning delta: ${r.data.deltaContent.length} chars`),!this._shouldDropUnmappedSubagentEvent(r,"assistant.reasoning_delta")&&this._emitReasoningDelta(r.data.deltaContent,this._parentToolCallIdForSubagentEvent(r))})),this._register(e.onSessionModeChanged(r=>{this._logService.info(`[Copilot:${n}] session.mode_changed: ${r.data.previousMode} -> ${r.data.newMode}`);let o=r.data.newMode;o!=="interactive"&&o!=="plan"&&o!=="autopilot"||(this._lastAppliedMode=o,this._syncAhpConfigFromSdkMode(o))})),this._register(e.onMcpServersLoaded(r=>{this._applyMcpServerList(r.data.servers)})),this._register(e.onMcpServerStatusChanged(r=>{let o=this._toSdkMcpServer(r.data.serverName,r.data.status,r.data.error);if(!o){this._mcpCustomizations.remove(r.data.serverName);return}this._mcpCustomizations.applyOne(o)})),this._register(e.onToolsUpdated(()=>{this._fireMcpToolsListChanged()})),this._seedMcpServersFromRpc()}_seedMcpServersFromRpc(){let e=this._wrapper.session.rpc?.mcp;e&&e.list().then(n=>{this._store.isDisposed||this._applyMcpServerList(n.servers)},n=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to seed MCP server inventory`,n)})}_applyMcpServerList(e){let n=e.map(r=>this._toSdkMcpServer(r.name,r.status,r.error)).filter(tr);this._mcpCustomizations.applyAll(n)}_fireMcpToolsListChanged(){for(let{channel:e}of this._mcpCustomizations.readyChannels())this._onMcpNotification.fire({channel:e,method:"notifications/tools/list_changed"})}topLevelMcpCustomizations(){return this._mcpCustomizations.topLevelCustomizations()}_toSdkMcpServer(e,n,r){let o=this._translateSdkMcpStatus(n,r);if(o)return{name:e,state:o}}_translateSdkMcpStatus(e,n){switch(e){case"connected":return{kind:"ready"};case"failed":return{kind:"error",error:{errorType:"mcp-server-failed",message:n??"MCP server failed to start"}};case"pending":case"needs-auth":return{kind:"starting"};case"disabled":return{kind:"stopped"};case"not_configured":return;default:return}}_syncAhpConfigFromSdkMode(e){let n=this.sessionUri.toString(),r={};switch(e){case"plan":r.mode="plan";break;case"autopilot":r.mode="interactive",r.autoApprove="autopilot";break;case"interactive":r.mode="interactive";break}this._configurationService.updateSessionConfig(n,r)}async _handleExitPlanModeRequest(e,n){let r=N(),o=N();if(this._logService.info(`[Copilot:${this.sessionId}] exitPlanMode.request: rpcId=${r}, actions=[${e.actions.join(",")}], recommended=${e.recommendedAction}`),this._configurationService.getEffectiveValue(this.sessionUri.toString(),It,"autoApprove")==="autopilot"){let p=fO(e);return this._logService.info(`[Copilot:${this.sessionId}] exitPlanMode.request auto-accepted (autoApprove=autopilot): selectedAction=${p.selectedAction??"(none)"}`),p}let a=null;try{a=(await this._wrapper.session.rpc.plan.read()).path??null}catch(p){this._logService.warn(`[Copilot:${this.sessionId}] rpc.plan.read failed for exit_plan_mode: ${p instanceof Error?p.message:String(p)}`)}let l=e.summary||g(2090,null);if(a){let p=y.file(a);l+=`

[${g(2095,null)}](${p.toString()})`}this._emitMarkdownDelta(l);let d=e.actions.map(p=>{let m=aO(p);return{id:p,label:m?.label??p,description:m?.description,recommended:p===e.recommendedAction}}),c={id:r,questions:[{kind:"single-select",id:o,title:g(2094,null),message:g(2093,null),required:!0,options:d,allowFreeformInput:!0}]},u=new Ie;this._pendingPlanReviews.set(r,{actions:e.actions,recommendedAction:e.recommendedAction,questionId:o,deferred:u}),this._onDidSessionProgress.fire({kind:"action",session:this.sessionUri,action:{type:"session/inputRequested",request:c}});try{return await u.p}catch(p){return this._logService.error(p,`[Copilot:${this.sessionId}] exitPlanMode.request handler failed: rpcId=${r}`),{approved:!1}}}_subscribeForLogging(){let e=this._wrapper,n=this.sessionId;this._register(e.onSessionStart(r=>{this._logService.trace(`[Copilot:${n}] Session started: model=${r.data.selectedModel??"default"}, producer=${r.data.producer}`)})),this._register(e.onSessionResume(r=>{this._logService.trace(`[Copilot:${n}] Session resumed: eventCount=${r.data.eventCount}`)})),this._register(e.onSessionInfo(r=>{let o={infoType:r.data.infoType};r.data.tip&&(o.tip=r.data.tip);let s=`[Copilot:${n}] [${r.data.infoType}]: ${r.data.message}`,a=new Ws(o);r.data.infoType==="mcp"?this._logService.info(s,a):this._logService.trace(s,a)})),this._register(e.onSessionWarning(r=>{this._logService.warn(`[Copilot:${n}] ${r.data.message}`,new Ws({warningType:r.data.warningType}))})),this._register(e.onSessionModelChange(r=>{this._logService.trace(`[Copilot:${n}] Model changed: ${r.data.previousModel??"(none)"} -> ${r.data.newModel}`)})),this._register(e.onSessionHandoff(r=>{this._logService.trace(`[Copilot:${n}] Session handoff: sourceType=${r.data.sourceType}, remoteSessionId=${r.data.remoteSessionId??"(none)"}`)})),this._register(e.onSessionTruncation(r=>{this._logService.trace(`[Copilot:${n}] Session truncation: removed ${r.data.tokensRemovedDuringTruncation} tokens, ${r.data.messagesRemovedDuringTruncation} messages`)})),this._register(e.onSessionSnapshotRewind(r=>{this._logService.trace(`[Copilot:${n}] Snapshot rewind: upTo=${r.data.upToEventId}, eventsRemoved=${r.data.eventsRemoved}`)})),this._register(e.onSessionShutdown(r=>{this._logService.trace(`[Copilot:${n}] Session shutdown: type=${r.data.shutdownType}, apiDuration=${r.data.totalApiDurationMs}ms`)})),this._register(e.onSessionUsageInfo(r=>{this._logService.trace(`[Copilot:${n}] Usage info: ${r.data.currentTokens}/${r.data.tokenLimit} tokens, ${r.data.messagesLength} messages`)})),this._register(e.onSessionCompactionStart(()=>{this._logService.trace(`[Copilot:${n}] Compaction started`)})),this._register(e.onSessionCompactionComplete(r=>{this._logService.trace(`[Copilot:${n}] Compaction complete: success=${r.data.success}, tokensRemoved=${r.data.tokensRemoved??"?"}`)})),this._register(e.onUserMessage(r=>{this._logService.trace(`[Copilot:${n}] User message: ${r.data.content.length} chars, ${r.data.attachments?.length??0} attachments`)})),this._register(e.onPendingMessagesModified(()=>{this._logService.trace(`[Copilot:${n}] Pending messages modified`)})),this._register(e.onTurnStart(r=>{this._logService.trace(`[Copilot:${n}] Turn started: ${r.data.turnId}`)})),this._register(e.onIntent(r=>{this._logService.trace(`[Copilot:${n}] Intent: ${r.data.intent}`)})),this._register(e.onReasoning(r=>{this._logService.trace(`[Copilot:${n}] Reasoning: ${r.data.content.length} chars`)})),this._register(e.onTurnEnd(r=>{this._logService.trace(`[Copilot:${n}] Turn ended: ${r.data.turnId}`)})),this._register(e.onAbort(r=>{this._logService.trace(`[Copilot:${n}] Aborted: ${r.data.reason}`)})),this._register(e.onToolUserRequested(r=>{this._logService.trace(`[Copilot:${n}] Tool user-requested: ${r.data.toolName} (${r.data.toolCallId})`)})),this._register(e.onToolPartialResult(r=>{this._logService.trace(`[Copilot:${n}] Tool partial result: ${r.data.toolCallId} (${r.data.partialOutput.length} chars)`)})),this._register(e.onToolProgress(r=>{this._logService.trace(`[Copilot:${n}] Tool progress: ${r.data.toolCallId} - ${r.data.progressMessage}`)})),this._register(e.onSkillInvoked(r=>{this._logService.trace(`[Copilot:${n}] Skill invoked: ${r.data.name} (${r.data.path})`)})),this._register(e.onSubagentStarted(r=>{this._logService.trace(`[Copilot:${n}] Subagent started: ${r.data.agentName} (${r.data.agentDisplayName})`)})),this._register(e.onSubagentCompleted(r=>{r.agentId&&this._parentToolCallIdsByAgentId.delete(r.agentId),this._logService.trace(`[Copilot:${n}] Subagent completed: ${r.data.agentName}`),this._onDidSessionProgress.fire({kind:"subagent_completed",session:this.sessionUri,toolCallId:r.data.toolCallId})})),this._register(e.onSubagentFailed(r=>{r.agentId&&this._parentToolCallIdsByAgentId.delete(r.agentId),this._logService.error(`[Copilot:${n}] Subagent failed: ${r.data.agentName} - ${r.data.error}`),this._onDidSessionProgress.fire({kind:"subagent_completed",session:this.sessionUri,toolCallId:r.data.toolCallId})})),this._register(e.onSubagentSelected(r=>{this._logService.trace(`[Copilot:${n}] Subagent selected: ${r.data.agentName}`)})),this._register(e.onHookStart(r=>{this._logService.trace(`[Copilot:${n}] Hook started: ${r.data.hookType} (${r.data.hookInvocationId})`)})),this._register(e.onHookEnd(r=>{this._logService.trace(`[Copilot:${n}] Hook ended: ${r.data.hookType} (${r.data.hookInvocationId}), success=${r.data.success}`)})),this._register(e.onSystemMessage(r=>{this._logService.trace(`[Copilot:${n}] System message [${r.data.role}]: ${r.data.content.length} chars`)}))}getNextTurnEventId(e){return this._databaseRef.object.getNextTurnEventId(e)}getFirstTurnEventId(){return this._databaseRef.object.getFirstTurnEventId()}async truncateAtEventId(e,n){this._logService.info(`[Copilot:${this.sessionId}] Truncating via SDK RPC at eventId=${e}`);let r=await this._wrapper.session.rpc.history.truncate({eventId:e});this._logService.info(`[Copilot:${this.sessionId}] SDK truncation removed ${r.eventsRemoved} events`),n?await this._databaseRef.object.deleteTurnsAfter(n):await this._databaseRef.object.deleteAllTurns()}async remapTurnIds(e){await this._databaseRef.object.remapTurnIds(e)}_denyPendingPermissions(){for(let[e,n]of this._pendingPermissions)this._deletePendingEditContent(e),n.complete(!1);this._pendingPermissions.clear()}_deletePendingEditContent(e){let n=this._pendingEditContentUris.get(e);n&&(this._pendingEditContentUris.delete(e),this._fileService.del(n).catch(r=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to delete pending edit content: ${n.toString()}`,r)}))}_cancelPendingUserInputs(){for(let[,e]of this._pendingUserInputs)e.deferred.complete({response:"cancel"});this._pendingUserInputs.clear()}_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()}_cancelPendingMcpSamplings(){let e=Array.from(this._pendingMcpSamplings);this._pendingMcpSamplings.clear();for(let n of e)this._wrapper.session.rpc.mcp.cancelSamplingExecution({requestId:n}).catch(()=>{})}_cancelPendingClientToolCalls(){this._pendingClientToolCalls.denyAll({textResultForLlm:"Tool call cancelled: session ended",resultType:"failure",error:"Session ended"})}};Hs=x([C(1,ke),C(2,O),C(3,ft),C(4,Te),C(5,yn),C(6,$e),C(7,ai)],Hs);function fO(i){let t=i.actions??[],e=n=>n==="autopilot"||n==="autopilot_fleet";if(i.recommendedAction&&t.includes(i.recommendedAction)){let n=i.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 gO(i){let t=0,e=0;for(let n of i.split(`
`))n.startsWith("+++")||n.startsWith("---")||(n.startsWith("+")?t++:n.startsWith("-")&&e++);if(!(t===0&&e===0))return{added:t,removed:e}}async function mO(i,t){if(!i||i.scheme!==ie.file||!await t.isInsideWorkTree(i))return;let e=(await t.getWorktreeRoots(i))[0]??await t.getRepositoryRoot(i);if(e)return{uri:e,displayName:Ce(e.fsPath)||e.toString()}}function hO(i){let t=i.includes("://")?y.parse(i):y.parse(`https://github.com/${i}`),e=Ce(t.path)||i.split("/").filter(Boolean).pop()||i,n=e.endsWith(".git")?e.slice(0,-4):e;return{uri:t,displayName:n}}async function Mr(i,t){let e=typeof i?.cwd=="string"?y.file(i.cwd):typeof i?.gitRoot=="string"?y.file(i.gitRoot):void 0,n=await mO(e,t);if(n)return n;if(i?.repository)return hO(i.repository)}import{spawn as yO}from"child_process";function WT(i){let t={};for(let e of i){let n=e.configuration;n.type==="stdio"?t[e.name]={type:"local",command:n.command,args:n.args?[...n.args]:[],tools:["*"],...n.env&&{env:vO(n.env)},...n.cwd&&{cwd:n.cwd}}:t[e.name]={type:"http",url:n.url,tools:["*"],...n.headers&&{headers:{...n.headers}}}}return t}function vO(i){let t={};for(let[e,n]of Object.entries(i))n!==null&&(t[e]=String(n));return t}async function $T(i,t){let e=[];for(let n of i)try{let o=(await t.readFile(n.uri)).value.toString(),s=Us(o),a=s?.getStringValue("name")??n.name,l=s?.getStringValue("description"),d=s?.getStringArrayValue("tools"),c=s?.body??o,u=s?.getStringValue("model")??void 0,p=s?.getStringArrayValue("model")??void 0;!u&&p&&Array.isArray(p)&&p.length>0&&(u=p[0]),e.push({name:a,...l?{description:l}:{},...u?{model:u}:{},tools:d&&d.length>0?d:null,prompt:c})}catch{}return e}function Yh(i){let t=new Map,e=n=>{t.has(n.id)||t.set(n.id,n)};for(let n of i){for(let r of n.agents)e(r.customization);for(let r of n.skills)e(r.customization);for(let r of n.instructions)e(r.customization);for(let r of n.hooks)e(r.customization);for(let r of n.mcpServers)e(r.customization)}return[...t.values()]}function HT(i){return BT(i)}function qT(i){return BT(i)}function BT(i){let t=new Set,e=[];for(let n of i){let r=se(n.uri.fsPath);t.has(r)||(t.add(r),e.push(r))}return e}function SO(i,t){return t===1&&i.windows?i.windows:t===2&&i.osx?i.osx:t===3&&i.linux?i.linux:i.command}function zl(i,t){let e=SO(i,at);if(!e)return Promise.resolve("");let n=(i.timeout??30)*1e3,r=i.cwd?.fsPath;return new Promise((o,s)=>{let a=at===1,c=yO(a?"cmd.exe":"/bin/sh",a?["/c",e]:["-c",e],{cwd:r,env:{...process.env,...i.env},stdio:["pipe","pipe","pipe"],timeout:n}),u="",p="";c.stdout.on("data",m=>{u+=m.toString()}),c.stderr.on("data",m=>{p+=m.toString()}),t&&c.stdin.write(t),c.stdin.end(),c.on("error",s),c.on("close",m=>{m===0?o(u):s(new Error(`Hook command exited with code ${m}: ${p||u}`))})})}async function FT(i,t){if(!i)return;let e=JSON.stringify(t);for(let n of i)try{let r=await zl(n,e);if(r.trim())try{let o=JSON.parse(r);if(o&&typeof o=="object")return o}catch{}}catch{}}var bO={PreToolUse:"onPreToolUse",PostToolUse:"onPostToolUse",UserPromptSubmit:"onUserPromptSubmitted",SessionStart:"onSessionStart",SessionEnd:"onSessionEnd",ErrorOccurred:"onErrorOccurred"};function VT(i,t){let e=new Map;for(let c of i){let u=bO[c.type];if(!u)continue;let p=e.get(u)??[];p.push(...c.commands),e.set(u,p)}let n={},r=e.get("onPreToolUse");(r?.length||t)&&(n.onPreToolUse=async c=>(await t?.onPreToolUse(c),FT(r,c)));let o=e.get("onPostToolUse");(o?.length||t)&&(n.onPostToolUse=async c=>(await t?.onPostToolUse(c),FT(o,c)));let s=e.get("onUserPromptSubmitted");s?.length&&(n.onUserPromptSubmitted=async c=>{let u=JSON.stringify(c);for(let p of s)try{await zl(p,u)}catch{}});let a=e.get("onSessionStart");a?.length&&(n.onSessionStart=async c=>{let u=JSON.stringify(c);for(let p of a)try{await zl(p,u)}catch{}});let l=e.get("onSessionEnd");l?.length&&(n.onSessionEnd=async c=>{let u=JSON.stringify(c);for(let p of l)try{await zl(p,u)}catch{}});let d=e.get("onErrorOccurred");return d?.length&&(n.onErrorOccurred=async c=>{let u=JSON.stringify(c);for(let p of d)try{await zl(p,u)}catch{}}),n}function zT(i,t){let e=n=>JSON.stringify(n.map(r=>({hooks:r.hooks.map(o=>({type:o.type,commands:o.commands.map(s=>({command:s.command,windows:s.windows,linux:s.linux,osx:s.osx,cwd:s.cwd?.toString(),env:s.env,timeout:s.timeout}))})),mcpServers:r.mcpServers.map(o=>({name:o.name,configuration:o.configuration})),skills:r.skills.map(o=>({uri:o.uri.toString(),name:o.name})),agents:r.agents.map(o=>({uri:o.uri.toString(),name:o.name})),instructions:r.instructions.map(o=>({uri:o.uri.toString(),name:o.name}))})));return e(i)===e(t)}var jl=class extends T{constructor(e){super();this.session=e;this._register(k(()=>{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 onSessionWarning(){return this._onSessionWarning??=this._sdkEvent("session.warning")}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")}get onMcpServersLoaded(){return this._onMcpServersLoaded??=this._sdkEvent("session.mcp_servers_loaded")}get onMcpServerStatusChanged(){return this._onMcpServerStatusChanged??=this._sdkEvent("session.mcp_server_status_changed")}get onToolsUpdated(){return this._onToolsUpdated??=this._sdkEvent("session.tools_updated")}_sdkEvent(e){let n=this._register(new w),r=this.session.on(e,o=>n.fire(o));return this._register(k(r)),n.event}};var Np=$("sandboxHelperService");var IO=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"]),_O=new Set(["ai","cloud","com","dev","io","me","net","org","tech"]);function Kl(i,t=!1){if(!i)return;let e=i.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 r=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(r))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(IO.has(a)||!_O.has(a))return}return o?`*.${s}`:s}}function CO(i){let t=i.trim();if(t==="*"||!t.includes("://"))return t;try{return y.parse(t).authority}catch{return t}}function Qh(i,t){let e=Kl(CO(t),t.includes("://"));if(!e)return!1;if(e==="*")return!0;if(e.startsWith("*.")){let n=e.slice(2);return i===n||i.endsWith(`.${n}`)}return i===e}var Fp=$("windowsMxcTerminalSandboxRuntime"),Up=class{constructor(){this._configVersion="0.4.0-alpha";this._containerName="vscode-terminal-sandbox"}getExecutablePath(t,e){let n=e==="arm64"?"arm64":"x64";return le.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,le.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(d=>this._normalizeWindowsPath(d)))],readonlyPaths:[...new Set([n,...t.shell&&le.isAbsolute(t.shell)?[le.dirname(t.shell)]:[],...t.allowReadPaths].map(d=>this._normalizeWindowsPath(d)))],deniedPaths:[...new Set(t.denyReadPaths.map(d=>this._normalizeWindowsPath(d)))]},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,r=e.deniedDomains.length>0?e.deniedDomains:void 0,o=t||!!n?.length,s={allowOutbound:o};return o&&n&&(s.allowedHosts=n),o&&r&&(s.blockedHosts=r),s}_quotePowerShellArgument(t){return`'${t.replace(/'/g,"''")}'`}_quoteWindowsCommandLineArgument(t){return`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/\\+$/g,"$&$&")}"`}};var Wp=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--html-path","--info-path","--man-path","--namespace","--super-prefix","--work-tree"]);function $p(i,t,e){if(!t.keywords.includes(i.keyword.toLowerCase())||t.condition&&(!e||!t.condition(e)))return!1;if(t.subcommands){let n=TO(i.args,t.optionsWithValue);if(n===void 0||!t.subcommands.includes(n))return!1}return t.when?.(i)??!0}function TO(i,t){for(let e=0;e<i.length;e++){let n=i[e];if(n==="--")return;if(n.startsWith("-")){let r=n.includes("=")?n.substring(0,n.indexOf("=")):n;!n.includes("=")&&t?.has(r)&&e++;continue}return n.toLowerCase()}}var xO=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 KT(i,t){if(t===1)return[];switch(i){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 jT(i,t){let e=new Set;for(let r of t)for(let o of wO)$p(r,o,{os:i})&&e.add(o.value);let n=[...e].flatMap(r=>KT(r,i));return[...new Set(n)]}var wO=[{keywords:["gpg","gpg2"],value:"gnupg"},{keywords:["git"],value:"gnupg",subcommands:["commit"],optionsWithValue:Wp}];function Hp(i,t,e=[]){if(t.length===0)return jT(i,e);let n=new Set;for(let o of t){let s=xO.get(o.toLowerCase());s&&n.add(s)}let r=[...n].flatMap(o=>KT(o,i));return[...new Set([...r,...jT(i,e)])]}var RO=[{keywords:["node","npm","npx","pnpm","yarn","corepack","bun","deno","nvm","volta","fnm","asdf","mise"],value:"node"},{keywords:["git"],value:"gnupg",subcommands:["commit"],optionsWithValue:Wp,condition:({os:i})=>i!==1,when:AO}];function EO(i,t){switch(i){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 qp(i,t){let e=new Set;for(let r of t)for(let o of RO)$p(r,o,{os:i})&&PO(o.value,t)&&e.add(o.value);let n={};for(let r of e)JT(n,EO(r,i));return n}function PO(i,t){switch(i){case"gnupg":return t.length===1;case"node":return!0}}function AO(i){return i.args.some(t=>t==="-S"||t.startsWith("-S")||t==="--gpg-sign"||t.startsWith("--gpg-sign="))}function JT(i,t){for(let[e,n]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(i,e)){i[e]=n;continue}let r=i[e];if(Array.isArray(r)&&Array.isArray(n)){i[e]=[...new Set([...r,...n])];continue}GT(r)&&GT(n)&&JT(r,n)}}function GT(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}var Pse=$("terminalSandboxService");var an=class extends T{constructor(e,n,r,o){super();this._host=e;this._fileService=n;this._logService=r;this._windowsMxcRuntime=o;this._sandboxSettingsId=N();this._runtimeResolved=!1;this._runAsNode=!1;this._needsForceUpdateConfigFile=!0;this._commandAllowListKeywords=[];this._commandAllowListCommandDetails=[];this._commandAllowNetwork=!1;this._os=at;this._defaultWritePaths=[];this._buildSandboxPayload=(e,n,r,o,s)=>this._host.buildWindowsMxcSandboxPayload(e,n,r,o,s);this._pathJoin=(...e)=>(this._os===1?le: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,r,o,s,a){let l=this._areUnsandboxedCommandsAllowed(),d=this._areRetryWithAllowNetworkRequestsAllowed(),u=n!==!0&&a!==!0&&(d||l)?this._getBlockedDomains(e):{blockedDomains:[],deniedDomains:[]},p=d&&u.blockedDomains.length>0,m=n!==!0&&(a===!0&&d||p),h=this._normalizeCommandDetails(s??[]),v=this._normalizeCommandKeywords(h.map(L=>L.keyword)),I=Hp(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),b=Hp(this._os,v,h),S=qp(this._os,this._commandAllowListCommandDetails),_=qp(this._os,h);if((this._commandAllowListKeywords.length===0||this._needsForceUpdateConfigFile||!this._areStringArraysEqual(this._commandAllowListKeywords,v)||!this._areStringArraysEqual(I,b)||!this._areObjectsEqual(S,_)||this._commandCwd?.toString()!==o?.toString()||this._commandAllowNetwork!==m||this._os===1&&(this._commandLine!==e||this._commandShell!==r))&&(this._commandAllowListKeywords=v,this._commandAllowListCommandDetails=h,this._commandCwd=o,this._commandLine=e,this._commandShell=r,this._commandAllowNetwork=m,await this.getSandboxConfigPath(!0)),!this._sandboxConfigPath||!this._tempDir)throw new Error("Sandbox config path or temp dir not initialized");if(!n&&!d&&l&&u.blockedDomains.length>0)return{command:this._wrapUnsandboxedCommand(e,r),isSandboxWrapped:!1,blockedDomains:u.blockedDomains,deniedDomains:u.deniedDomains,requiresUnsandboxConfirmation:!0};if(n&&l)return{command:this._wrapUnsandboxedCommand(e,r),isSandboxWrapped:!1};let P=p?{blockedDomains:u.blockedDomains,deniedDomains:u.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 q=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(q)}`;if(this._runAsNode){let L=`ELECTRON_RUN_AS_NODE=1 ${E}`;return{command:this._wrapSandboxRuntimeCommandForLaunch(L,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 r=await this.getSandboxConfigPath(e,n);if(!r)return{enabled:!0,sandboxConfigPath:r,failedCheck:"config"};if(!await this._checkSandboxDependencies(e)){let o=await this.getMissingSandboxDependencies();return o.length===0&&this._sandboxDependencyStatus?.bubblewrapInstalled&&!this._sandboxDependencyStatus.bubblewrapUsable?{enabled:!0,sandboxConfigPath:r,failedCheck:"bubblewrap",remediations:this._getBubblewrapRemediations(),detail:this._sandboxDependencyStatus.bubblewrapError}:{enabled:!0,sandboxConfigPath:r,failedCheck:"dependencies",missingDependencies:o}}return{enabled:!0,sandboxConfigPath:r,failedCheck:void 0}}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=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.bubblewrapUsable&&this._sandboxDependencyStatus.socatInstalled;let r=await this._host.checkSandboxDependencies();return this._sandboxDependencyStatus=r,r&&!r.bubblewrapInstalled?this._logService.warn("TerminalSandboxEngine: bubblewrap (bwrap) is not installed"):r&&!r.bubblewrapUsable&&this._logService.warn("TerminalSandboxEngine: bubblewrap (bwrap) is installed but failed its capability check",r.bubblewrapError),r&&!r.socatInstalled&&this._logService.warn("TerminalSandboxEngine: socat is not installed"),r?r.bubblewrapInstalled&&r.bubblewrapUsable&&r.socatInstalled:!0}_getBubblewrapRemediations(){return["disableUserNamespaceRestriction"]}_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 r=this._tempDir?.path;return this._os===3&&n?.path&&r&&n.path!==r?`cd ${this._quoteShellArgument(r)}; ${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:r,deniedDomains:o}=this.getResolvedNetworkDomains(),s=new Set,a=new Set;for(let l of n){if(o.some(d=>Qh(l,d))){s.add(l),a.add(l);continue}r.some(d=>Qh(l,d))||s.add(l)}return{blockedDomains:[...s],deniedDomains:[...a]}}_extractDomains(e){let n=new Set,r;for(an._urlRegex.lastIndex=0;(r=an._urlRegex.exec(e))!==null;){let o=this._extractDomainFromUrl(r[0]);o&&n.add(o)}for(an._sshRemoteRegex.lastIndex=0;(r=an._sshRemoteRegex.exec(e))!==null;){let o=Kl(r[1],!0);o&&n.add(o)}for(an._hostRegex.lastIndex=0;(r=an._hostRegex.exec(e))!==null;){let o=Kl(r[1]);o&&n.add(o)}return[...n]}_extractDomainFromUrl(e){try{let n=y.parse(e).authority;return Kl(n,!0)}catch{return}}_normalizeCommandKeywords(e){return[...new Set(e.map(n=>n.toLowerCase()))].sort()}_normalizeCommandDetails(e){let n=new Set,r=[];for(let o of e){let s={keyword:o.keyword.toLowerCase(),args:[...o.args]},a=JSON.stringify(s);n.has(a)||(n.add(a),r.push(s))}return r.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((r,o)=>r===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",r=this._os===1?"rg.exe":"rg";this._rgPath=this._pathJoin(this._appRoot,"node_modules","@vscode","ripgrep-universal","bin",`${n}-${Hv}`,r),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")??{}:{},r=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=qp(this._os,this._commandAllowListCommandDetails),d=this._getCommandRuntimeFileSystemPaths(l,"allowRead"),c=this._getCommandRuntimeFileSystemPaths(l,"allowWrite"),u=y.joinPath(this._tempDir,`vscode-sandbox-settings-${this._sandboxSettingsId}.json`),p=[],m=[],h=[],v;if(this._os===1){let b=await this._getWindowsMxcFilesystemPolicy(),S=await this._getWindowsMxcEnvironment();p=await this._resolveFileSystemPaths([...await this._updateAllowWritePathsWithWorkspaceFolders(o.allowWrite),...b.readwritePaths]),m=await this._resolveFileSystemPaths([...o.allowRead??[],...b.readonlyPaths]),h=await this._resolveFileSystemPaths(o.denyRead??[]),this._windowsMxcEnvironment=S}else this._os===2?(p=await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(r.allowWrite,c)),m=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(r.allowRead,p,d)),h=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome(r.denyRead)),v=r.denyWrite?await this._resolveFileSystemPaths(r.denyWrite):void 0):this._os===3&&(p=await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(n.allowWrite,c)),m=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(n.allowRead,p,d)),h=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome(n.denyRead)),v=await this._resolveFileSystemPaths(n.denyWrite));let I=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:p,denyReadPaths:h,env:this._windowsMxcEnvironment??[]},this._buildSandboxPayload):{network:e?{allowedDomains:[],deniedDomains:[],enabled:!1}:this.getResolvedNetworkDomains(),filesystem:{denyRead:h,allowRead:m,allowWrite:p,denyWrite:v}};return this._os!==1&&(this._mergeAdditionalSandboxConfigProperties(I,e?this._withoutNetworkRuntimeSetting(a):a),this._mergeAdditionalSandboxConfigProperties(I,l)),this._sandboxConfigPath=this._getUriPath(u),await this._fileService.createFile(u,A.fromString(JSON.stringify(I,null,"	")),{overwrite:!0}),this._sandboxConfigPath}_getCommandRuntimeFileSystemPaths(e,n){let r=e.filesystem;if(!this._isObjectForSandboxConfigMerge(r))return[];let o=r[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[r,o]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(e,r)){e[r]=o;continue}let s=e[r];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?le: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 r=this._host.getWriteRoots().map(o=>this._getUriPath(o));return[...new Set([...r,...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,r=[]){return[...new Set([...e??[],...Hp(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),...r,...this._getSandboxRuntimeReadPaths(),...await this._getWorkspaceStorageReadPaths(),...n])]}async _resolveFileSystemPaths(e){let n=await Promise.all((e??[]).map(r=>this._resolveFileSystemPath(r)));return[...new Set(n.flat())]}async _resolveFileSystemPath(e){let n=this._os===3?this._expandHomePath(e):e;if(!this._isAbsoluteFileSystemPath(n))return[n];try{let r=await this._fileService.realpath(this._toFileSystemResource(n)),o=r?this._getUriPath(r):void 0;return o&&o!==n?[n,o]:[n]}catch{return[n]}}_isAbsoluteFileSystemPath(e){return(this._os===1?le: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 r=n.indexOf("/",2);return r===-1?y.from({scheme:"file",authority:n.slice(2),path:"/"}):y.from({scheme:"file",authority:n.slice(2,r),path:n.slice(r)||"/"})}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?le.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)}};an=x([C(1,Te),C(2,O),C(3,Fp)],an);var kO="tmp",Xh=class{constructor(t,e,n,r,o,s){this._sessionId=t;this._workingDirectory=e;this._environmentService=n;this._productService=r;this._agentConfigurationService=o;this.onDidChangeRoots=Q.None;this._sandboxHelper=s,this.onDidChangeSandboxSettings=this._agentConfigurationService.onDidRootConfigChange}async getOS(){return at}async getRuntimeInfo(){let t=se(dt.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,kO);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,r,o){return this._sandboxHelper.buildWindowsMxcSandboxPayload(t,e,n,r,o)}getSandboxSetting(t){let e=qI[t];return e===void 0?void 0:this._agentConfigurationService.getRootValue(Rr,"sandbox")?.[e]}};function YT(i,t,e,n,r,o,s){let a=new Xh(o,s,t,e,n,r);return i.createInstance(an,a)}var QT=8e4,DO=12e4,Zh="<<<COPILOT_SENTINEL_",OO="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 MO(i){let t=Math.max(i.lastIndexOf("/"),i.lastIndexOf("\\"));switch(i.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 G?"powershell":"bash"}}var oo=class extends T{constructor(e,n,r,o,s,a,l,d,c){super();this._sessionUri=e;this.workingDirectory=n;this._terminalManager=r;this._logService=o;this._instantiationService=s;this._environmentService=a;this._productService=l;this._agentConfigurationService=d;this._sandboxHelper=c;this._shells=new Map;this._toolCallShells=new Map;this._busyShellIds=new Set;this._heldShellReleaseListeners=new Map;this._onDidAssociateTerminal=this._register(new w);this.onDidAssociateTerminal=this._onDidAssociateTerminal.event;this._register(k(()=>{for(let u of this._heldShellReleaseListeners.values())u.dispose();this._heldShellReleaseListeners.clear();for(let u of this._shells.values())this._terminalManager.hasTerminal(u.terminalUri)&&this._terminalManager.disposeTerminal(u.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()??N(),n=YT(this._instantiationService,this._environmentService,this._productService,this._agentConfigurationService,this._sandboxHelper,e,this.workingDirectory);this._register(n),this._register(k(()=>{n.cleanupTempDir().catch(r=>this._logService.warn("[ShellManager] Sandbox temp dir cleanup failed",r))})),this._sandboxEngine=n}return this._sandboxEngine}async getOrCreateShell(e,n,r,o){for(let p of this._shells.values()){if(p.shellType!==e||!this._terminalManager.hasTerminal(p.terminalUri))continue;if(this._terminalManager.getExitCode(p.terminalUri)!==void 0){this._shells.delete(p.id);continue}if(!this._busyShellIds.has(p.id))return this._busyShellIds.add(p.id),this._trackToolCall(r,p.id),this._makeReference(p)}let s=N(),a=`agenthost-terminal://shell/${s}`,l={kind:"session",session:this._sessionUri.toString(),turnId:n,toolCallId:r},d=e==="bash"?"Bash":"PowerShell",c=await this.getResolvedExecutable();await this._terminalManager.createTerminal({channel:a,claim:l,name:d,cwd:o??this.workingDirectory?.fsPath},{shell:c,preventShellHistory:!0,nonInteractive:!0});let u={id:s,terminalUri:a,shellType:e,executable:c};return this._shells.set(s,u),this._busyShellIds.add(s),this._trackToolCall(r,s),this._logService.info(`[ShellManager] Created ${e} shell ${s} (terminal=${a},  executable=${c})`),this._makeReference(u)}_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,r=()=>{this._busyShellIds.delete(e.id),this._heldShellReleaseListeners.delete(e.id),n.dispose()};n.add(this._terminalManager.onCommandFinished(e.terminalUri,r)),n.add(this._terminalManager.onExit(e.terminalUri,r)),this._heldShellReleaseListeners.set(e.id,n)}_trackToolCall(e,n){this._toolCallShells.set(e,n);let r=this._shells.get(n);if(r){let o=r.shellType==="bash"?"Bash":"PowerShell";this._onDidAssociateTerminal.fire({toolCallId:e,terminalUri:r.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}};oo=x([C(2,is),C(3,O),C(4,ke),C(5,vl),C(6,gt),C(7,$e),C(8,Np)],oo);function LO(){return N().replace(/-/g,"")}function NO(i,t){return t==="powershell"?`Write-Output "${Zh}${i}_EXIT_$LASTEXITCODE>>>"`:`echo "${Zh}${i}_EXIT_$?>>>"`}function XT(i){return i==="powershell"?"":" "}function UO(i){let t=i.replace(/\r\n|\r/g,`
`);return/(?<!\\)\n/.test(t)}function ZT(i){return et||UO(i)}function FO(i,t){let e=`${Zh}${t}_EXIT_`,n=i.indexOf(e);if(n===-1)return{found:!1,exitCode:-1,outputBeforeSentinel:i};let r=i.substring(0,n),o=i.substring(n+e.length),s=o.indexOf(">>>"),a=s>=0?o.substring(0,s):o.trim(),l=parseInt(a,10);return{found:!0,exitCode:isNaN(l)?-1:l,outputBeforeSentinel:r}}function so(i){let t=lS(i).trim();return t.length>QT&&(t=t.substring(t.length-QT)),t}function zn(i){return{textResultForLlm:i,resultType:"success"}}function Rt(i,t){return{textResultForLlm:i,resultType:"failure",error:t}}function jn(i,t){return{toolResult:i,keepShellBusy:t?.keepShellBusy}}function ex(i){return jn(zn(i),{keepShellBusy:!0})}function WO(){return jn(Rt(OO,"alternateBuffer"),{keepShellBusy:!0})}function tx(i,t,e,n,r){t.createAltBufferPromise(i.terminalUri,n).then(()=>{e.info("[ShellTool] Command entered alternate buffer"),r(WO())})}async function $O(i,t,e,n,r){let o=n.supportsCommandDetection(i.terminalUri)?await HO(i,t,e,n,r):await qO(i,t,e,n,r);return{...o,toolResult:{...o.toolResult,textResultForLlm:`Shell ID: ${i.id}
${o.toolResult.textResultForLlm}`}}}async function HO(i,t,e,n,r){let o=new z,s=new Promise(a=>{let l=!1,d=u=>{l||(l=!0,o.dispose(),a(u))};o.add(n.onCommandFinished(i.terminalUri,u=>{let p=so(u.output),m=u.exitCode??0;r.info(`[ShellTool] Command completed (shell integration) with exit code ${m}`),d(jn(m===0?zn(`Exit code: ${m}
${p}`):Rt(`Exit code: ${m}
${p}`)))})),tx(i,n,r,o,d),o.add(n.onExit(i.terminalUri,u=>{r.info(`[ShellTool] Shell exited unexpectedly with code ${u}`);let p=n.getContent(i.terminalUri)??"",m=so(p);d(jn(Rt(`Shell exited with code ${u}
${m}`)))})),o.add(n.onClaimChanged(i.terminalUri,u=>{u.kind==="session"&&!u.toolCallId&&(r.info("[ShellTool] Continuing in background (claim narrowed)"),d(ex("The user chose to continue this command in the background. The terminal is still running.")))}));let c=setTimeout(()=>{r.warn(`[ShellTool] Command timed out after ${e}ms`);let u=n.getContent(i.terminalUri)??"",p=so(u);d(jn(Rt(`Command timed out after ${Math.round(e/1e3)}s. Partial output:
${p}`,"timeout")))},e);o.add(k(()=>clearTimeout(c)))});try{await n.sendText(i.terminalUri,`${XT(i.shellType)}${t}`,{shouldExecute:!0,bracketedPasteMode:ZT(t)})}catch(a){throw o.dispose(),a}return s}async function qO(i,t,e,n,r){let o=LO(),s=NO(o,i.shellType),a=new z,d=(n.getContent(i.terminalUri)??"").length,c=new Promise(u=>{let p=!1,m=I=>{p||(p=!0,a.dispose(),u(I))},h=()=>{let I=n.getContent(i.terminalUri)??"",b=Math.min(d,I.length),S=I.substring(b),_=FO(S,o);if(_.found){let R=so(_.outputBeforeSentinel);r.info(`[ShellTool] Command completed with exit code ${_.exitCode}`),_.exitCode===0?m(jn(zn(`Exit code: ${_.exitCode}
${R}`))):m(jn(Rt(`Exit code: ${_.exitCode}
${R}`)))}};a.add(n.onData(i.terminalUri,()=>{h()})),tx(i,n,r,a,m),a.add(n.onExit(i.terminalUri,I=>{r.info(`[ShellTool] Shell exited unexpectedly with code ${I}`);let S=(n.getContent(i.terminalUri)??"").substring(d),_=so(S);m(jn(Rt(`Shell exited with code ${I}
${_}`)))})),a.add(n.onClaimChanged(i.terminalUri,I=>{I.kind==="session"&&!I.toolCallId&&(r.info("[ShellTool] Continuing in background (claim narrowed)"),m(ex("The user chose to continue this command in the background. The terminal is still running.")))}));let v=setTimeout(()=>{r.warn(`[ShellTool] Command timed out after ${e}ms`);let b=(n.getContent(i.terminalUri)??"").substring(d),S=so(b);m(jn(Rt(`Command timed out after ${Math.round(e/1e3)}s. Partial output:
${S}`,"timeout")))},e);a.add(k(()=>clearTimeout(v))),h()});try{await n.sendText(i.terminalUri,`${XT(i.shellType)}${t}`,{shouldExecute:!0,bracketedPasteMode:ZT(t)}),await n.sendText(i.terminalUri,s,{shouldExecute:!0})}catch(u){throw a.dispose(),u}return c}async function nx(i,t,e,n){let r=await i.getResolvedExecutable(),o=MO(r),s=i.getOrCreateSandboxEngine(),a=await s.isEnabled(),l=a?s.getResolvedNetworkDomains():void 0,d={name:o,description:o==="bash"?Fc(r)?jO(a,l):zO(a,l):VO(o,r,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,S)=>{let _=b.timeout??DO,R=await i.getOrCreateShell(o,S.toolCallId,S.toolCallId),P=!0;try{let q=b.command;if(a){if(b.requestUnsandboxedExecution&&!s.areUnsandboxedCommandsAllowed())return Rt("Unsandboxed execution is disabled by the chat.agent.sandbox.allowUnsandboxedCommands setting.","unsandboxed_disabled");let L=s.isAutoApproveUnsandboxedCommands(),U=async ne=>{if(L)return!0;if(!n){let ba=ne?.join(", ")??"(unknown)";return Rt(`Command requires approval to run outside the sandbox. Blocked domains: ${ba}. Re-run with requestUnsandboxedExecution=true and requestUnsandboxedExecutionReason explaining why unsandboxed access is required.`,"sandbox_blocked")}return await n({toolCallId:S.toolCallId,toolName:S.toolName,shellExecutable:r,command:b.command,reason:b.requestUnsandboxedExecutionReason,blockedDomains:ne})},J=await s.wrapCommand(b.command,b.requestUnsandboxedExecution,r,R.object.shellType==="bash"?i.workingDirectory:void 0);if(b.requestUnsandboxedExecution&&!J.isSandboxWrapped){let ne=await U(J.blockedDomains);if(typeof ne!="boolean")return ne;if(!ne){let xe=J.blockedDomains?.join(", ")??"(none)";return Rt(`User declined to run command outside the sandbox. Blocked domains: ${xe}.`,"sandbox_blocked")}}if(J.requiresUnsandboxConfirmation){let ne=await U(J.blockedDomains);if(typeof ne!="boolean")return ne;if(!ne){let xe=J.blockedDomains?.join(", ")??"(unknown)";return Rt(`User declined to run command outside the sandbox. Blocked domains: ${xe}.`,"sandbox_blocked")}J=await s.wrapCommand(b.command,!0,r,R.object.shellType==="bash"?i.workingDirectory:void 0)}q=J.command}let E=await $O(R.object,q,_,t,e);return E.keepShellBusy&&(P=!1,i.holdShellUntilCommandFinishes(R.object)),E.toolResult}finally{P&&R.dispose()}}},c={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:b=>{let S=i.listShells(),_=b.shell_id?i.getShell(b.shell_id):S[S.length-1];if(!_)return Rt("No active shell found.","no_shell");let R=t.getContent(_.terminalUri);return zn(R?so(R):"(no output)")}},u={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 b=>{let S=i.listShells(),_=S[S.length-1];return _?(await t.sendText(_.terminalUri,b.command,{shouldExecute:!1}),zn("Input sent to shell.")):Rt("No active shell found.","no_shell")}},p={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:b=>{if(b.shell_id)return i.shutdownShell(b.shell_id)?zn("Shell stopped."):Rt("Shell not found.","not_found");let S=i.listShells(),_=S[S.length-1];return _?(i.shutdownShell(_.id),zn("Shell stopped.")):Rt("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 b=i.listShells();if(b.length===0)return zn("No active shells.");let S=b.map(_=>{let R=t.getExitCode(_.terminalUri),P=R!==void 0?`exited (${R})`:"running";return`- ${_.id}: ${_.shellType} [${P}]`});return zn(S.join(`
`))}},h=o==="bash"?"powershell":"bash",v=`This tool is disabled because the configured shell is ${r}. Use the \`${o}\` tool instead.`;return[d,c,u,p,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:()=>Rt(v,"wrong_shell")}]}function BO(i){return i.endsWith("System32\\WindowsPowerShell\\v1.0\\powershell.exe")}function VO(i,t,e,n){let r=BO(t),o=[`This tool allows you to execute ${r?"Windows PowerShell 5.1":"PowerShell"} commands in a persistent terminal session, preserving environment variables, working directory, and other context across multiple commands.`,"","Command Execution:",r?"- 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_${i} to send commands or input to a terminal session.`];return e&&o.push(...rx(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_${i}. Never send multiple answers in a single send.`,`- After each send, call read_${i} to read the next prompt before sending the next answer.`,"- Continue one prompt at a time until the command finishes."),o.join(`
`)}function rx(i){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(i){let e=new Set(i.deniedDomains),n=i.allowedDomains.filter(r=>!e.has(r));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(", ")}`),i.deniedDomains.length>0&&t.push(`- The following domains are explicitly blocked in the sandbox: ${i.deniedDomains.join(", ")}`)}return t}function ix(i,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_${i} to send commands or input to a terminal session.`];return t&&n.push(rx(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_${i}. Never send multiple answers in a single send.
- After each send, call read_${i} to read the next prompt before sending the next answer.
- Continue one prompt at a time until the command finishes.`),n.join("")}function zO(i,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.",ix("bash",i,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 jO(i,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.",ix("bash",i,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 ey="thinkingLevel",ty="contextTier",KO=["low","medium","high","xhigh"],GO=["default","long_context"],ox={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 JO(i){return KO.some(t=>t===i)}function YO(i){return GO.some(t=>t===i)}function sx(i){if(typeof i!="object"||i===null)return;let t=Object.getOwnPropertyDescriptor(i,"code")?.value;return typeof t=="number"?t:void 0}function ax(i){if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null){let t=Object.getOwnPropertyDescriptor(i,"message")?.value;if(typeof t=="string")return t}return String(i)}function QO(i){if(sx(i)!==-32603)return!1;let t=ax(i);return!/\b(corrupt|corrupted|invalid|validation|schema|must be|parse|malformed|unexpected token)\b/i.test(t)}function ny(i){let t=i?.config?.[ey];return JO(t)?t:void 0}function ry(i){let t=i?.config?.[ty];return YO(t)?t:void 0}var qs=class{constructor(t,e,n,r){this._configurationService=t;this._terminalManager=e;this._logService=n;this._fileService=r}async launch(t,e){let n=await this._buildSessionConfig(t,e),r=this._computeSandboxConfig();if(t.kind==="create")return this._createSession(t,n,r);try{this._logService.info(`[Copilot:${t.sessionId}] Calling SDK resumeSession...`);let o=await t.client.resumeSession(t.sessionId,{...n,workingDirectory:t.workingDirectory.fsPath,...t.resolvedAgentName?{agent:t.resolvedAgentName}:{}});return this._logService.info(`[Copilot:${t.sessionId}] SDK resumeSession succeeded`),await this._applySandboxConfig(o,r,t.sessionId),new jl(o)}catch(o){let s=sx(o),a=ax(o);if(this._logService.warn(`[Copilot:${t.sessionId}] SDK resumeSession failed: code=${s}, message=${a}`),!QO(o))throw o;this._logService.warn(`[Copilot:${t.sessionId}] Resume failed (code=-32603), falling back to createSession with same ID`);let l=await this._createSession({...t,kind:"create",model:t.fallback.model},n,r);return this._logService.info(`[Copilot:${t.sessionId}] Fallback createSession succeeded`),l}}async _createSession(t,e,n){let r=await t.client.createSession({...e,sessionId:t.sessionId,streaming:!0,model:t.model?.id,reasoningEffort:ny(t.model),contextTier:ry(t.model),...t.resolvedAgentName?{agent:t.resolvedAgentName}:{},workingDirectory:t.workingDirectory?.fsPath});return await this._applySandboxConfig(r,n,t.sessionId),new jl(r)}_computeSandboxConfig(){if(this._configurationService.getRootValue(jt,"enableCustomTerminalTool")!==!0)return Tp(process.platform,this._configurationService.getRootValue(Rr,"sandbox"))}async _applySandboxConfig(t,e,n){if(e)try{await t.rpc.options.update({sandboxConfig:e}),this._logService.info(`[Copilot:${n}] Applied SDK sandboxConfig via session.options.update`)}catch(r){this._logService.warn(`[Copilot:${n}] Failed to apply SDK sandboxConfig`,r)}}async _buildSessionConfig(t,e){let n=t.snapshot.plugins,r=this._configurationService.getRootValue(jt,"enableCustomTerminalTool")===!0,o=[];if(r){if(!t.shellManager)throw new Error(`ShellManager is required to launch Copilot session '${t.sessionId}'`);o=await nx(t.shellManager,this._terminalManager,this._logService,c=>e.requestUnsandboxedCommandConfirmation(c))}let s=n.filter(c=>!c.pluginDir||c.pluginDir.scheme!==ie.file),a=await $T(s.flatMap(c=>c.agents),this._fileService),l=HT(s.flatMap(c=>c.skills)),d=qT(n.flatMap(c=>c.instructions));return{clientName:"vscode",enableMcpApps:!0,onPermissionRequest:c=>e.handlePermissionRequest(c),onUserInputRequest:(c,u)=>e.handleUserInputRequest(c,u),onElicitationRequest:c=>e.handleElicitationRequest(c),hooks:VT(s.flatMap(c=>c.hooks),{onPreToolUse:c=>e.handlePreToolUse(c),onPostToolUse:c=>e.handlePostToolUse(c)}),mcpServers:WT(s.flatMap(c=>c.mcpServers)),onExitPlanModeRequest:(c,u)=>e.handleExitPlanModeRequest(c,u),workingDirectory:t.workingDirectory?.fsPath,customAgents:a,skillDirectories:l,instructionDirectories:d,systemMessage:ox,pluginDirectories:Wr(n.map(c=>c.pluginDir)).filter(c=>c.scheme===ie.file).map(c=>c.fsPath),tools:[...o,...e.createClientSdkTools(),...e.createServerSdkTools()],gitHubToken:t.githubToken,infiniteSessions:{enabled:!0},remoteSession:this._configurationService.getRootValue(Qi,gl)===!0?"export":void 0}}};qs=x([C(0,$e),C(1,is),C(2,O),C(3,Te)],qs);function XO(i){let t=new Map;if(!i)return t;let e=i.indexOf(":"),n=e===-1?i:i.substring(0,e);for(let r of n.split(";")){let o=r.indexOf("=");o<=0||t.set(r.substring(0,o),r.substring(o+1))}return t}function lx(i){return XO(i).get("rt")==="1"}function ux(i,t){if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++){let n=i[e],r=t[e];if(n.type!==r.type||n.uri.toString()!==r.uri.toString()||!e2(n.files,r.files))return!1}return!0}function ZO(i,t){let e=lr(i.type,t.type);return e!==0?e:lr(i.uri.toString(),t.uri.toString())}function e2(i,t){if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++){let n=i[e],r=t[e];if(n.uri.toString()!==r.uri.toString()||n.etag!==r.etag)return!1}return!0}function Bp(i,t){return lr(i.uri.toString(),t.uri.toString())}var t2=5;var n2=".md",r2=".instructions.md",i2="SKILL.md",o2="README.md",dx={workspace:[{path:[".github","agents"],type:"agent"},{path:[".agents","agents"],type:"agent"},{path:[".claude","agents"],type:"agent"},{path:[".github","skills"],recursive:!0,type:"skill"},{path:[".agents","skills"],recursive:!0,type:"skill"},{path:[".claude","skills"],recursive:!0,type:"skill"},{path:[".github","instructions"],recursive:!0,type:"instruction"}],user:[{path:[".copilot","agents"],type:"agent"},{path:[".agents","skills"],recursive:!0,type:"skill"},{path:[".copilot","instructions"],recursive:!0,type:"instruction"}]},cx={workspace:[{path:[".github"],filenames:["copilot-instructions.md"]},{path:[],filenames:["AGENTS.md","CLAUDE.md","GEMINI.md"]},{path:[".claude"],filenames:["CLAUDE.md"]}],user:[{path:[".copilot"],filenames:["copilot-instructions.md"]}]};function Kn(i){if(i.isCancellationRequested)throw new K}function iy(i,t,e,n){let r=i.get(t);r?e&&!r.recursive&&(r={recursive:!0,resourcesToWatch:r.resourcesToWatch},i.set(t,r)):(r={recursive:e,resourcesToWatch:new Ia},i.set(t,r)),r.resourcesToWatch.add(n)}var Bs=class extends T{constructor(e,n,r,o){super();this._workingDirectory=e;this._userHome=n;this._fileService=r;this._logService=o;this._onDidChange=this._register(new w);this.onDidChange=this._onDidChange.event;this._watchers=new Oe;this._register({dispose:()=>this._disposeAllWatchers()}),this._register(this._fileService.onDidFilesChange(s=>{for(let a of this._watchers.values())for(let l of a.resourcesToWatch)if(s.affects(l)){this._scheduleRefresh();return}}))}_scheduleRefresh(){this._onDidChange.fire()}async scan(e){Kn(e);let n=new Oe,r=new Ia,o=[];return await Promise.all([...dx.workspace.map(s=>this._scanRoot(this._workingDirectory,s,r,o,n,e)),...dx.user.map(s=>this._scanRoot(this._userHome,s,r,o,n,e)),this._scanAgentInstructions(this._workingDirectory,cx.workspace,r,o,n,e),this._scanAgentInstructions(this._userHome,cx.user,r,o,n,e)]),Kn(e),this._reconcileWatchers(n),o.sort(ZO)}async _watchAncestors(e,n,r,o){let s=e;for(let a of n){let l=s,d=X(l,a);if(!r.has(l)){Kn(o);try{if(!(await this._fileService.resolve(l)).isDirectory)return!1}catch{return!1}}iy(r,l,!1,d),s=d}return!0}_reconcileWatchers(e){for(let[n,r]of this._watchers.entries()){let o=e.get(n);(!o||o.recursive!==r.recursive)&&(r.disposable.dispose(),this._watchers.delete(n))}for(let[n,r]of e.entries()){let o=this._watchers.get(n);if(o){o.resourcesToWatch.clear();for(let s of r.resourcesToWatch)o.resourcesToWatch.add(s);continue}try{let s=this._fileService.watch(n,{recursive:r.recursive,excludes:[]});this._watchers.set(n,{recursive:r.recursive,resourcesToWatch:r.resourcesToWatch,disposable:s})}catch(s){this._logService.warn(`[SessionCustomizationDiscovery] Failed to watch '${n.toString()}': ${s instanceof Error?s.message:String(s)}`)}}}_disposeAllWatchers(){for(let e of this._watchers.values())e.disposable.dispose();this._watchers.clear()}async _scanAgentInstructions(e,n,r,o,s,a){let l=[];for(let d of n){if(Kn(a),!await this._watchAncestors(e,d.path,s,a))continue;let c=X(e,...d.path),u;try{u=await this._fileService.resolve(c,{resolveMetadata:!0})}catch{continue}if(!(!u.isDirectory||!u.children)){for(let p of d.filenames)iy(s,c,!1,X(c,p));for(let p of u.children)if(Kn(a),p.isFile&&d.filenames.includes(p.name)){let m=X(c,p.name);r.has(m)||(r.add(m),l.push({uri:m,etag:p.etag}))}}}l.length>0&&o.push({uri:e,type:"agentInstruction",files:l.sort(Bp)})}async _scanRoot(e,n,r,o,s,a){if(Kn(a),!await this._watchAncestors(e,n.path,s,a))return;let l=X(e,...n.path),d;try{d=await this._fileService.resolve(l,{resolveMetadata:!0})}catch{return}if(!(!d.isDirectory||!d.children))if(iy(s,l,n.recursive??!1,l),n.type==="skill"){let c=[];for(let u of d.children)if(Kn(a),u.isDirectory){let p=X(u.resource,i2);try{let m=await this._fileService.resolve(p,{resolveMetadata:!0});m.isFile&&!r.has(p)&&(r.add(p),c.push({uri:p,etag:m.etag}))}catch{}}o.push({uri:l,type:n.type,files:c.sort(Bp)})}else if(n.type==="agent"){let c=[];for(let u of d.children)if(Kn(a),u.isFile){let p=u.name;p.endsWith(n2)&&p!==o2&&!r.has(u.resource)&&(r.add(u.resource),c.push({uri:u.resource,etag:u.etag}))}o.push({uri:l,type:n.type,files:c.sort(Bp)})}else if(n.type==="instruction"){let c=[],u=async(p,m)=>{Kn(a);for(let h of p.children??[])if(Kn(a),h.isFile)h.name.toLowerCase().endsWith(r2)&&!r.has(h.resource)&&(r.add(h.resource),c.push({uri:h.resource,etag:h.etag}));else if(h.isDirectory&&m<t2){let v;try{v=await this._fileService.resolve(h.resource,{resolveMetadata:!0})}catch{}v&&await u(v,m+1)}};await u(d,0),o.push({uri:l,type:n.type,files:c.sort(Bp)})}else this._logService.warn(`[SessionCustomizationDiscovery] Unrecognized root type '${n.type}' for root '${l.toString()}'`)}};Bs=x([C(2,Te),C(3,O)],Bs);function l2(i){switch(i){case 0:return"none";case 1:return"all";case 2:return"debug";case 3:return"info";case 4:return"warning";case 5:return"error"}}function d2(i){return y.joinPath(i,"..",`${Ce(i.fsPath)}.worktrees`)}function c2(i){return i.replace(/\//g,"-")}function u2(i,t){return`agents/${t?`${t}-${i.substring(0,8)}`:i}`}function p2(i){let e=i.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 px(i){return g(2083,null,Ye(i))+`

`}function f2(i,t){if(i.length===0)return i;let e=i.slice(),n=e[0],r=n.responseParts[0];if(r?.kind==="markdown"){let o=n.responseParts.slice();o[0]={...r,content:t+r.content},e[0]={...n,responseParts:o}}else{let o=[{kind:"markdown",id:N(),content:t},...n.responseParts];e[0]={...n,responseParts:o}}return e}var me=class extends T{constructor(e,n,r,o,s,a,l,d){super();this._logService=e;this._instantiationService=n;this._sessionDataService=r;this._gitService=o;this._configurationService=s;this._otelService=a;this._checkpointService=d;this.id="copilotcli";this._onDidSessionProgress=this._register(new w);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidMaterializeSession=this._register(new w);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._onMcpNotification=this._register(new w);this.onMcpNotification=this._onMcpNotification.event;this._models=pn(this,[]);this.models=this._models;this._restrictedTelemetryEnabled=!1;this._onDidChangeRestrictedTelemetry=this._register(new w);this.onDidChangeRestrictedTelemetry=this._onDidChangeRestrictedTelemetry.event;this._sessions=this._register(new ve);this._mcpNotificationSubs=this._register(new ve);this._resumingSessions=new Map;this._provisionalSessions=new Map;this._createdWorktrees=new Map;this._pendingFirstTurnAnnouncements=new Map;this._sessionSequencer=new nt;this._activeClients=new Oe;this._lastSessionSyncEnabled=this._isSessionSyncEnabled();this._lastRubberDuckEnabled=this._isRubberDuckEnabled();this._plugins=this._register(this._instantiationService.createInstance(Gl)),this._sessionLauncher=this._instantiationService.createInstance(qs),this.onDidCustomizationsChange=this._plugins.onDidChange,this._register(l.registerProvider(new Cp(this.id,{hasHistory:c=>!this._provisionalSessions.has(c)&&this._sessions.has(c),isRubberDuckEnabled:()=>this._isRubberDuckEnabled()}))),this._register(this._configurationService.onDidRootConfigChange(()=>{this._restartClientIfStartupConfigChanged().catch(c=>this._logService.error("[Copilot] Failed to restart client after config change",c))}))}static{this._BRANCH_COMPLETION_LIMIT=25}setServerToolHost(e){this._serverToolHost=e}get restrictedTelemetryEnabled(){return this._restrictedTelemetryEnabled}_isSessionSyncEnabled(){return this._configurationService.getRootValue(Qi,gl)===!0}_isRubberDuckEnabled(){return this._configurationService.getRootValue(jt,"rubberDuck")===!0}async _restartClientIfStartupConfigChanged(){let e=this._isSessionSyncEnabled(),n=this._isRubberDuckEnabled();if(this._lastSessionSyncEnabled===e&&this._lastRubberDuckEnabled===n)return;let r=[this._lastSessionSyncEnabled!==e?`sessionSync=${e}`:void 0,this._lastRubberDuckEnabled!==n?`rubberDuck=${n}`:void 0].filter(o=>o!==void 0).join(", ");this._lastSessionSyncEnabled=e,this._lastRubberDuckEnabled=n,this._client&&(this._logService.info(`[Copilot] Startup config changed (${r}), restarting CopilotClient`),this._sessions.clearAndDisposeAll(),this._mcpNotificationSubs.clearAndDisposeAll(),await this._stopClient())}_createCopilotClient(e){return new s2(e)}getDescriptor(){return{provider:"copilotcli",displayName:"Copilot CLI",description:"Copilot SDK agent running in a dedicated process"}}getProtectedResources(){return[St]}getCustomizations(){return this._plugins.getConfiguredHostCustomizations()}async getSessionCustomizations(e){let n=await this._getSessionCustomizationDirectory(e),o=await this._getOrCreateActiveClient(e,n).pluginController.getCustomizationsSettled(),s=F.id(e),l=this._sessions.get(s)?.topLevelMcpCustomizations()??[];return l.length===0?o:[...o,...l]}async handleMcpRequest(e,n,r,o){let s=F.id(e),a=this._sessions.get(s);if(!a)throw new Error(`Method not found: no active session ${s}`);return a.handleMcpRequest(n,r,o)}async _getSessionCustomizationDirectory(e){let n=F.id(e),r=this._provisionalSessions.get(n);if(r)return r.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!==St.resource)return!1;let r=this._githubToken!==n;return this._githubToken=n,this._updateRestrictedTelemetry(n),this._logService.info(`[Copilot] Auth token ${r?"updated":"unchanged"}`),r&&this._client&&this._sessions.size===0&&(this._logService.info("[Copilot] Restarting CopilotClient with new token"),await this._stopClient()),r&&this._refreshModels(),!0}_updateRestrictedTelemetry(e){let n=lx(e);n!==this._restrictedTelemetryEnabled&&(this._restrictedTelemetryEnabled=n,this._logService.info(`[Copilot] Restricted telemetry ${n?"enabled":"disabled"}`),this._onDidChangeRestrictedTelemetry.fire())}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 r=n.sendRequest.bind(n);n.sendRequest=(o,s)=>(o==="session.create"||o==="session.resume")&&s&&typeof s=="object"?r(o,{...s,requestExitPlanMode:!0}):r(o,s)}async _ensureClient(){let e=this._githubToken;if(!e)throw new D(on,"Authentication is required to use Copilot",this.getProtectedResources());if(this._client)return this._client;if(this._clientStarting)return this._clientStarting;let n=this._isSessionSyncEnabled(),r=this._isRubberDuckEnabled(),o=(async()=>{this._logService.info("[Copilot] Starting CopilotClient... (with token)");let s=Object.assign({},process.env,{ELECTRON_RUN_AS_NODE:"1"});delete s.NODE_OPTIONS,delete s.VSCODE_INSPECTOR_OPTIONS,delete s.VSCODE_ESM_ENTRYPOINT,delete s.VSCODE_HANDLES_UNCAUGHT_ERRORS;for(let I of Object.keys(s))I!=="ELECTRON_RUN_AS_NODE"&&(I.startsWith("VSCODE_")||I.startsWith("ELECTRON_"))&&delete s[I];s.COPILOT_CLI_RUN_AS_NODE="1",s.USE_BUILTIN_RIPGREP="false",s.COPILOT_MCP_APPS="true",this._isRubberDuckEnabled()?s.RUBBER_DUCK_AGENT="true":delete s.RUBBER_DUCK_AGENT;let a=y.joinPath(dt.asFileUri(""),"..","node_modules"),l=y.joinPath(a,"@github","copilot","index.js").fsPath;s.MXC_BIN_DIR=y.joinPath(a,"@microsoft","mxc-sdk","bin").fsPath;let d=await Ps(),c=se(d),u=Object.keys(s).find(I=>I.toUpperCase()==="PATH")??"PATH",p=s[u];s[u]=p?`${p}${xo}${c}`:c,this._logService.info(`[Copilot] Resolved CLI path: ${l}`);let m=await this._otelService.getSdkTelemetryConfig(),h={gitHubToken:e,useLoggedInUser:!1,connection:a2.forStdio({path:l}),env:s,telemetry:m,logLevel:l2(this._logService.getLevel()),enableRemoteSessions:this._isSessionSyncEnabled()},v=this._createCopilotClient(h);if(await v.start(),this._githubToken!==e)throw await v.stop(),new Error("Copilot authentication changed while the client was starting");if(this._isSessionSyncEnabled()!==n||this._isRubberDuckEnabled()!==r)throw await v.stop(),new Error("Copilot startup config changed while the client was starting");return this._logService.info("[Copilot] CopilotClient started successfully"),this._enablePlanModeOnClient(v),this._client=v,this._clientStarting=void 0,v})();return this._clientStarting=o,o.catch(()=>{this._clientStarting=void 0}),o}_createThinkingLevelConfigSchemaProperty(e,n){if(!e?.length)return;let r=e.map(o=>{switch(o){case"low":return g(2078,null);case"medium":return g(2079,null);case"high":return g(2077,null);case"xhigh":return g(2081,null);default:return o}});return{type:"string",title:g(2080,null),description:g(2076,null),default:n,enum:[...e],enumLabels:r}}_createContextTierConfigSchemaProperty(e){let n=e?.tokenPrices,r=n?.contextMax,o=n?.longContext?.contextMax;if(!r||!o||r>=o)return;let s=typeof n?.longContext?.inputPrice=="number"||typeof n?.longContext?.outputPrice=="number";return{type:"string",title:g(2075,null),description:g(2072,null),default:"default",enum:["default","long_context"],enumLabels:[$h(r),$h(o)],enumDescriptions:[g(2071,null),s?g(2073,null):g(2074,null)]}}_createModelConfigSchema(e){let n={},r=this._createThinkingLevelConfigSchemaProperty(e.supportedReasoningEfforts,e.defaultReasoningEffort);r&&(n[ey]=r);let o=this._createContextTierConfigSchemaProperty(e.billing);if(o&&(n[ty]=o),Object.keys(n).length!==0)return{type:"object",properties:n}}_serializeModelSelection(e){return JSON.stringify(e)}_parseModelSelection(e){if(e){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.id=="string"){let r={id:n.id};if(n.config&&typeof n.config=="object"){let o={};for(let[s,a]of Object.entries(n.config))typeof a=="string"&&(o[s]=a);Object.keys(o).length>0&&(r.config=o)}return r}}catch{}return{id:e}}}_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,r){for(let l of n.plugins){let d=l.agents.find(c=>c.uri.toString()===r.uri);if(d)return d.name}let o=await this.getSessionCustomizations(e),a=hT(o).find(l=>l.uri.toString()===r.uri);if(a)return a.name}async listSessions(){this._logService.info("[Copilot] Listing sessions...");let n=await(await this._ensureClient()).listSessions(),r=new Po(4),o=new Map,a=(await Promise.all(n.map(async l=>{let d=F.uri(this.id,l.sessionId),c=await this._readStoredSessionMetadata(d);if(!c)return;let{project:u,resolved:p}=c;p||(u=await this._resolveSessionProject(l.context,r,o),this._storeSessionProjectResolution(d,u));let m=c.workingDirectory??(typeof l.context?.workingDirectory=="string"?y.file(l.context.workingDirectory):void 0);return{session:d,startTime:l.startTime.getTime(),modifiedTime:l.modifiedTime.getTime(),project:u,summary:l.summary,model:c.model,agent:c.agent,workingDirectory:m,customizationDirectory:c.customizationDirectory}}))).filter(l=>l!==void 0);return this._logService.info(`[Copilot] Found ${a.length} sessions`),a}async getSessionMetadata(e){let n=F.id(e),r=await this._readStoredSessionMetadata(e);if(!r)return;let s=await(await this._ensureClient()).getSessionMetadata(n);if(!s)return;let a=r?.project;if(r&&!r.resolved){let d=new Po(1);a=await this._resolveSessionProject(s?.context,d,new Map),this._storeSessionProjectResolution(e,a)}let l=r?.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:r?.model,agent:r?.agent,workingDirectory:l,customizationDirectory:r?.customizationDirectory}}async _listModels(){this._logService.info("[Copilot] Listing models...");let r=(await(await this._ensureClient()).listModels()).map(o=>({provider:this.id,id:o.id,name:o.name,maxContextWindow:o.capabilities?.limits?.max_context_window_tokens,supportsVision:!!o.capabilities?.supports?.vision,configSchema:this._createModelConfigSchema(o),policyState:o.policy?.state,_meta:typeof o.billing?.multiplier=="number"?{multiplierNumeric:o.billing.multiplier}:void 0}));return this._logService.info(`[Copilot] Found ${r.length} models`),r}async createSession(e){if(!e?.workingDirectory)throw new Error("workingDirectory is required to create a Copilot session");this._logService.info(`[Copilot] Creating session... ${e?.model?`model=${e.model.id}`:""}`);let n=await this._ensureClient();if(e?.fork){let l=F.id(e.fork.session);return this._sessionSequencer.queue(l,async()=>{this._logService.info(`[Copilot] Forking session ${l} at turnId=${e.fork.turnId}`);let c=await(this._sessions.get(l)??await this._resumeSession(l)).getNextTurnEventId(e.fork.turnId),p=(await n.rpc.sessions.fork({sessionId:l,...c?{toEventId:c}:{}})).sessionId,m=this._sessionDataService.getSessionDataDirById(p),h=y.joinPath(m,dl);try{let S=await this._sessionDataService.tryOpenDatabase(e.fork.session);if(S)try{await ao.mkdir(m.fsPath,{recursive:!0}),await S.object.vacuumInto(h.fsPath)}finally{S.dispose()}}catch(S){this._logService.warn(`[Copilot] Failed to copy session database for fork: ${S instanceof Error?S.message:String(S)}`)}let v=await this._resumeSession(p);e.fork.turnIdMapping&&await v.remapTurnIds(e.fork.turnIdMapping);let I=v.sessionUri;this._logService.info(`[Copilot] Forked session created: ${I.toString()}`);let b=await Mr({cwd:e.workingDirectory?.fsPath},this._gitService);return await this._storeSessionMetadata(I,e.model,e.workingDirectory,e.workingDirectory,b,!0),e.agent!==void 0&&await this._storeSessionAgentMetadata(I,e.agent),{session:I,workingDirectory:e.workingDirectory,...b?{project:b}:{}}})}let r=e.session?F.id(e.session):N(),o=F.uri(this.id,r);if(this._sessions.has(r)){this._logService.info(`[Copilot] createSession is a no-op: session already materialized: ${o.toString()}`);let l=await Mr({cwd:e.workingDirectory.fsPath},this._gitService);return{session:o,workingDirectory:e.workingDirectory,...l?{project:l}:{}}}let s=this._provisionalSessions.has(r);if(e.activeClient){let l=this._getOrCreateActiveClient(o,e.workingDirectory);l.updateTools(e.activeClient.clientId,e.activeClient.tools),e.activeClient.customizations!==void 0&&await l.pluginController.sync(e.activeClient.clientId,e.activeClient.customizations,{quiet:!0})}let a=await Mr({cwd:e.workingDirectory.fsPath},this._gitService);return s||this._provisionalSessions.set(r,{sessionId:r,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 r=this._provisionalSessions.get(e);if(!r)throw new Error(`Cannot materialize unknown provisional session: ${e}`);let o=await this._ensureClient(),s=r.sessionUri,a=this._configurationService.getSessionConfigValues(s.toString()),l={provider:this.id,session:s,workingDirectory:r.workingDirectory,model:r.model,config:a},d=r.workingDirectory,c=this._getOrCreateActiveClient(s,d),u=await c.snapshot(),p=await this._resolveSessionWorkingDirectory(l,e,n),m=this._instantiationService.createInstance(oo,s,p),h;try{let I=r.agent?await this._resolveAgentName(r.sessionUri,u,r.agent):void 0,b={kind:"create",client:o,sessionId:e,workingDirectory:p,resolvedAgentName:I,snapshot:u,activeClientState:c.state,shellManager:m,githubToken:this._githubToken,model:r.model};h=this._createAgentSession(b,d,c),await h.initializeSession(),this._registerInitializedSession(e,h)}catch(I){throw h?.dispose(),await this._removeCreatedWorktree(e),I}let v=await Mr({cwd:p?.fsPath},this._gitService);return this._provisionalSessions.delete(e),await this._storeSessionMetadata(s,r.model,p,d,v,!0),r.agent!==void 0&&await this._storeSessionAgentMetadata(s,r.agent),this._checkpointService.captureBaseline(s,p).catch(I=>{this._logService.warn(`[Copilot:${e}] Baseline checkpoint capture failed: ${I instanceof Error?I.message:String(I)}`)}),this._logService.info(`[Copilot] Session materialized: ${s.toString()}`),this._onDidMaterializeSession.fire({session:s,workingDirectory:p,project:v}),h}async resolveSessionConfig(e){let n=e.workingDirectory?await this._getGitInfo(e.workingDirectory):void 0,r=Ve({type:"string",title:g(2065,null),description:g(2070,null),enum:n?["folder","worktree"]:["folder"],enumLabels:n?[g(2066,null),g(2068,null)]:[g(2066,null)],enumDescriptions:n?[g(2067,null),g(2069,null)]:[g(2067,null)],default:n?"worktree":"folder",readOnly:!n,sessionMutable:!1}),o=n?"worktree":"folder",s=r.validate(e.config?.isolation)?e.config.isolation:o,a,l;if(n){let u=s==="folder";l=s==="worktree"?n.defaultBranch:n.currentBranch,a=Ve({type:"string",title:g(2063,null),description:g(2064,null),enum:[l],enumLabels:[l],default:l,enumDynamic:!u,readOnly:u,sessionMutable:!1})}let d=zt({isolation:r,...It.definition,...a?{branch:a}:{}}),c=d.validateOrDefault(e.config,{isolation:s,autoApprove:"default",mode:"interactive",...l!==void 0?{branch:l}:{}});return{schema:d.toProtocol(),values:c}}async sessionConfigCompletions(e){return e.property!=="branch"||!e.workingDirectory?{items:[]}:{items:(await this._getBranches(e.workingDirectory,e.query)).map(r=>({value:r,label:r}))}}async setClientCustomizations(e,n,r){let o=await this._getSessionCustomizationDirectory(e);return this._getOrCreateActiveClient(e,o).pluginController.sync(n,r)}setClientTools(e,n,r){let o=F.id(e),s=this._getOrCreateActiveClient(e,void 0),a=this._sessions.has(o);this._logService.info(`[Copilot:${o}] setClientTools: clientId=${n??"(none)"}, tools=[${r.map(l=>l.name).join(", ")||"(none)"}], hasCachedSdkSession=${a}`),s.updateTools(n,r)}onClientToolCallComplete(e,n,r){let o=e,s;for(;s=Xe(o);)o=s.parentSession;let a=F.id(o);this._sessions.get(a)?.handleClientToolCallComplete(n,r)}setCustomizationEnabled(e,n){for(let r of this._activeClients.values())r.pluginController.setEnabled(e,n)}async sendMessage(e,n,r,o){let s=F.id(e);await this._sessionSequencer.queue(s,async()=>{await this._activeClients.get(e)?.pluginController.retryFailedClientSyncIfNeeded();let a;this._provisionalSessions.has(s)?a=await this._materializeProvisional(s,n):a=this._sessions.get(s);let l=this._activeClients.get(e),d=!!a;this._logService.info(`[Copilot:${s}] sendMessage: cachedEntry=${d}, hasActiveClient=${!!l}, activeClientId=${l?"(set)":"(none)"}`),a&&l&&await l.requiresRestart(a.appliedSnapshot)&&(this._logService.info(`[Copilot:${s}] Session config changed (requiresRestart=true), refreshing session. clientId=${l.state.clientId??"(none)"}`),this._sessions.deleteAndDispose(s),a=void 0),a||this._logService.info(`[Copilot:${s}] No cached entry${d?" (was evicted by requiresRestart)":""}, calling _resumeSession`),a??=await this._resumeSession(s),o&&a.resetTurnState(o);let c=this._pendingFirstTurnAnnouncements.get(s);c!==void 0&&(this._pendingFirstTurnAnnouncements.delete(s),a.emitInitialMarkdown(c));try{let u=this._resolveSdkMode(e);await a.send(n,r,o,u)}catch(u){let p=u?.code,m=u instanceof Error?u.message:String(u);throw this._logService.error(`[Copilot:${s}] entry.send() failed: code=${p}, message=${m}, hadCachedEntry=${d}, errorType=${u?.constructor?.name}`),u}})}_resolveSdkMode(e){let n=e.toString(),r=this._configurationService.getEffectiveValue(n,It,"mode");if(r==="plan")return"plan";if(r==="interactive")return this._configurationService.getEffectiveValue(n,It,"autoApprove")==="autopilot"?"autopilot":"interactive"}setPendingMessages(e,n,r){let o=F.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=Xe(e);if(n){let l=n.parentSession,d;for(;d=Xe(l);)l=d.parentSession;let c=F.id(l),u=this._sessions.get(c)??await this._resumeSession(c).catch(p=>{this._logService.warn(`[Copilot:${c}] Failed to resume root for subagent restore`,p)});return u?u.getSubagentMessages(n.toolCallId):[]}let r=F.id(e);if(this._provisionalSessions.has(r))return[];let o=this._sessions.get(r)??await this._resumeSession(r).catch(l=>{this._logService.warn(`[Copilot:${r}] 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:${r}] Failed to read worktree branch metadata`,l)});return a?.branchName?f2(s,px(a.branchName)):s}async disposeSession(e){let n=F.id(e);await this._sessionSequencer.queue(n,async()=>{this._provisionalSessions.has(n)||await(await this._ensureClient()).deleteSession(n),await this._destroyAndDisposeSession(n)})}async onArchivedChanged(e,n){let r=F.id(e);await this._sessionSequencer.queue(r,async()=>{n?await this._cleanupWorktreeOnArchive(e,r):await this._recreateWorktreeOnUnarchive(e,r)})}async _cleanupWorktreeOnArchive(e,n){let r=await this._readWorktreeMetadata(e).catch(()=>{});if(!r?.worktreePath||!r.repositoryRoot)return;let{branchName:o,worktreePath:s,repositoryRoot:a}=r;try{await ao.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(c){this._logService.warn(`[Copilot:${n}] Failed to remove worktree '${s.fsPath}' on archive: ${c instanceof Error?c.message:String(c)}`)}finally{this._createdWorktrees.delete(n)}}async _recreateWorktreeOnUnarchive(e,n){let r=await this._readWorktreeMetadata(e).catch(()=>{});if(!r?.worktreePath||!r.repositoryRoot)return;let{branchName:o,worktreePath:s,repositoryRoot:a}=r;try{await ao.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 ao.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(d){this._logService.warn(`[Copilot:${n}] Failed to recreate worktree '${s.fsPath}' on unarchive: ${d instanceof Error?d.message:String(d)}`)}}async abortSession(e){let n=F.id(e);await this._sessionSequencer.queue(n,async()=>{let r=this._sessions.get(n);r&&await r.abort()})}async truncateSession(e,n){let r=F.id(e);this._provisionalSessions.has(r)||await this._sessionSequencer.queue(r,async()=>{this._logService.info(`[Copilot:${r}] Truncating session${n!==void 0?` at turnId=${n}`:" (all turns)"}`);let o=this._sessions.get(r)??await this._resumeSession(r),s;n?s=await o.getNextTurnEventId(n):s=await o.getFirstTurnEventId(),s?await o.truncateAtEventId(s,n):this._logService.info(`[Copilot:${r}] No event ID found for truncation, nothing to truncate`),this._logService.info(`[Copilot:${r}] Session truncated`)})}async changeModel(e,n){let r=F.id(e),o=this._provisionalSessions.get(r);if(o){o.model=n;return}let s=this._sessions.get(r);s&&await s.setModel(n.id,ny(n),ry(n)),await this._storeSessionMetadata(e,n,void 0,void 0,void 0)}async changeAgent(e,n){let r=F.id(e),o=this._provisionalSessions.get(r);if(o){o.agent=n;return}let s=this._sessions.get(r);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[,r]of this._sessions)if(r.respondToPermissionRequest(e,n))return}respondToUserInputRequest(e,n,r){for(let[,o]of this._sessions)if(o.respondToUserInputRequest(e,n,r))return}hasSession(e){let n=F.id(e);return this._sessions.has(n)||this._provisionalSessions.has(n)}_getOrCreateActiveClient(e,n){let r=this._activeClients.get(e);if(r)n&&r.pluginController.setDirectory(n);else{let o=this._plugins.createSessionController(n);r=new ay(e,o,this._onDidSessionProgress),this._activeClients.set(e,r)}return r}_createAgentSession(e,n,r){let o=F.uri(this.id,e.sessionId),s=this._instantiationService.createInstance(Hs,{sessionUri:o,rawSessionId:e.sessionId,onDidSessionProgress:this._onDidSessionProgress,sessionLauncher:this._sessionLauncher,launchPlan:e,shellManager:e.shellManager,workingDirectory:e.workingDirectory,customizationDirectory:n,clientSnapshot:e.snapshot,activeClientState:e.activeClientState,resolveMcpChildId:a=>QC(r.pluginController.getCustomizations(),a),serverToolHost:this._serverToolHost});return this._mcpNotificationSubs.set(e.sessionId,s.onMcpNotification(a=>this._onMcpNotification.fire(a))),s}_registerInitializedSession(e,n){if(this._shutdownPromise)throw n.dispose(),new K;this._sessions.set(e,n)}async _destroyAndDisposeSession(e){let n=this._provisionalSessions.get(e);if(n){this._provisionalSessions.delete(e),this._activeClients.get(n.sessionUri)?.dispose(),this._activeClients.delete(n.sessionUri);return}let r=this._sessions.get(e),o=F.uri(this.id,e);if(r)try{await r.destroySession()}catch(s){this._logService.warn(`[Copilot:${e}] Failed to destroy session before cleanup: ${s instanceof Error?s.message:String(s)}`)}this._sessions.deleteAndDispose(e),this._mcpNotificationSubs.deleteAndDispose(e),this._activeClients.get(o)?.dispose(),this._activeClients.delete(o),await this._removeCreatedWorktree(e)}_resumeSession(e){let n=this._resumingSessions.get(e);if(n)return n;let r=this._doResumeSession(e);this._resumingSessions.set(e,r);let o=()=>{this._resumingSessions.get(e)===r&&this._resumingSessions.delete(e)};return r.then(o,o),r}async _doResumeSession(e){this._logService.info(`[Copilot:${e}] _resumeSession called \u2014 session not in memory, resuming...`);let n=await this._ensureClient(),r=F.uri(this.id,e),o=await this._readSessionMetadata(r),s=o.customizationDirectory??o.workingDirectory,a=this._getOrCreateActiveClient(r,s),l=await a.snapshot(),d=await n.getSessionMetadata(e).catch(v=>{this._logService.warn(`[Copilot:${e}] getSessionMetadata failed`,v)}),c=o.workingDirectory??(typeof d?.context?.workingDirectory=="string"?y.file(d.context.workingDirectory):void 0);if(!c)throw new Error(`workingDirectory is required to resume Copilot session '${e}'`);let u=this._instantiationService.createInstance(oo,r,c),p=o.agent?await this._resolveAgentName(r,l,o.agent):void 0,m={kind:"resume",client:n,sessionId:e,workingDirectory:c,resolvedAgentName:p,snapshot:l,activeClientState:a.state,shellManager:u,githubToken:this._githubToken,fallback:{model:o.model}},h=this._createAgentSession(m,s,a);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",r=await this._gitService.getDefaultBranch(e)??n;return{currentBranch:n,defaultBranch:r}}async _getBranches(e,n){return this._gitService.getBranches(e,{query:n,limit:me._BRANCH_COMPLETION_LIMIT})}async _resolveSessionWorkingDirectory(e,n,r){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=d2(o),a=r?p2(r):void 0,l=u2(n,a),d=y.joinPath(s,c2(l));await ao.mkdir(s.fsPath,{recursive:!0});let c=typeof e.config.branch=="string"?e.config.branch:void 0;await this._gitService.addWorktree(o,d,l,c),this._createdWorktrees.set(n,{repositoryRoot:o,worktree:d}),this._pendingFirstTurnAnnouncements.set(n,px(l));let u=F.uri(this.id,n);try{await this._writeWorktreeMetadata(u,{branchName:l,baseBranch:c,worktreePath:d,repositoryRoot:o})}catch(p){this._logService.warn(`[Copilot:${n}] Failed to persist worktree branch metadata: ${p instanceof Error?p.message:String(p)}`)}return d}async _removeCreatedWorktree(e){let n=this._createdWorktrees.get(e);if(n)try{await this._gitService.removeWorktree(n.repositoryRoot,n.worktree)}catch(r){this._logService.warn(`[Copilot:${e}] Failed to remove worktree '${n.worktree.fsPath}': ${r instanceof Error?r.message:String(r)}`)}finally{this._createdWorktrees.delete(e)}}static{this._META_MODEL="copilot.model"}static{this._META_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 r=this._sessionDataService.openDatabase(e);try{let o=[r.object.setMetadata(me._META_WORKTREE_BRANCH,n.branchName),r.object.setMetadata(me._META_WORKTREE_PATH,n.worktreePath.toString()),r.object.setMetadata(me._META_WORKTREE_REPOSITORY_ROOT,n.repositoryRoot.toString())];n.baseBranch&&o.push(r.object.setMetadata(Qc,n.baseBranch)),await Promise.all(o)}finally{r.dispose()}}async _readWorktreeMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(n)try{let[r,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(!r)return;let a=o?y.parse(o):void 0,l=s?y.parse(s):void 0;return{branchName:r,worktreePath:a,repositoryRoot:l}}finally{n.dispose()}}async _storeSessionMetadata(e,n,r,o,s,a=s!==void 0){let l=this._sessionDataService.openDatabase(e),d=l.object;try{let c=[];n&&c.push(d.setMetadata(me._META_MODEL,this._serializeModelSelection(n))),r&&c.push(d.setMetadata(me._META_CWD,r.toString())),o&&c.push(d.setMetadata(me._META_CUSTOMIZATION_DIRECTORY,o.toString())),a&&c.push(d.setMetadata(me._META_PROJECT_RESOLVED,"true")),s&&(c.push(d.setMetadata(me._META_PROJECT_URI,s.uri.toString())),c.push(d.setMetadata(me._META_PROJECT_DISPLAY_NAME,s.displayName))),await Promise.all(c)}finally{l.dispose()}}async _readSessionMetadata(e){let n=await this._sessionDataService.tryOpenDatabase(e);if(!n)return{};try{let[r,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(r),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[r,o,s,a,l,d,c]=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)]),u=s?y.parse(s):void 0,p=d&&c?{uri:y.parse(d),displayName:c}:void 0;return{model:this._parseModelSelection(r),agent:this._parseAgentSelection(o),workingDirectory:u,customizationDirectory:a?y.parse(a):void 0,project:p,resolved:l==="true"||p!==void 0}}finally{n.dispose()}}async _storeSessionAgentMetadata(e,n){let r=this._sessionDataService.openDatabase(e);try{await r.object.setMetadata(me._META_AGENT,n?this._serializeAgentSelection(n):"")}finally{r.dispose()}}async _storeSessionProjectResolution(e,n){await this._storeSessionMetadata(e,void 0,void 0,void 0,n,!0)}_resolveSessionProject(e,n,r){let o=this._projectContextKey(e);if(!o)return Promise.resolve(void 0);let s=r.get(o);return s||(s=n.queue(()=>Mr(e,this._gitService)),r.set(o,s)),s}_projectContextKey(e){if(e?.cwd)return`cwd:${e.cwd}`;if(e?.gitRoot)return`gitRoot:${e.gitRoot}`;if(e?.repository)return`repository:${e.repository}`}dispose(){for(let e of this._activeClients.values())e.dispose();this._activeClients.clear(),this.shutdown().catch(e=>{this._logService.warn("[Copilot] Shutdown failed during dispose",e)}).finally(()=>super.dispose())}};me=x([C(0,O),C(1,ke),C(2,ft),C(3,tt),C(4,$e),C(5,vp),C(6,eu),C(7,Wn)],me);var g2=100,oy=class extends T{constructor(e,n,r,o,s){super();this._onDidRefresh=r;this._logService=o;this._refreshDelayer=this._register(new Ni(g2));this._refreshPromise=null;this._pendingRefreshNotify=!1;this._customizations=[];this._discovery=this._register(s.createInstance(Bs,e,n)),this._fileService=s.invokeFunction(a=>a.get(Te)),this._settled=this._queueRefresh(!1),this._register(this._discovery.onDidChange(()=>{this._settled=this._queueRefresh(!0)}))}dispose(){this._refreshPromise?.cancel(),this._refreshPromise=null,super.dispose()}whenSettled(){return this._settled}currentCustomizations(){return this._customizations}_queueRefresh(e){return this._refreshPromise?.cancel(),this._refreshPromise=null,this._pendingRefreshNotify=this._pendingRefreshNotify||e,this._refreshDelayer.trigger(()=>{let n=this._pendingRefreshNotify;this._pendingRefreshNotify=!1;let r=this._refreshPromise=Qr(async o=>{await this._refresh(o)&&n&&this._onDidRefresh()});return r.then(()=>{this._refreshPromise===r&&(this._refreshPromise=null)},o=>{if(this._refreshPromise===r&&(this._refreshPromise=null),!(o instanceof K))throw o})})}async _refresh(e){try{let n=await this._discovery.scan(e);if(e.isCancellationRequested||this._directories&&ux(this._directories,n))return!1;let r=await m2(n,this._fileService);return e.isCancellationRequested?!1:(this._customizations=r,this._directories=n,!0)}catch(n){if(e.isCancellationRequested)return!1;this._logService.warn(`[Copilot:SessionDiscoveredEntry] Discovery/bundle failed: ${n instanceof Error?n.message:String(n)}`);let r=this._customizations.length>0||this._directories!==void 0;return this._customizations=[],this._directories=void 0,r}}};function m2(i,t){return Promise.all(i.map(async e=>{let n=e.uri.toString();return{type:"directory",id:Rn(n),uri:n,name:pe(e.uri),enabled:!0,contents:h2(e.type),writable:!1,load:{kind:"loaded"},children:await Promise.all(e.files.map(r=>y2(r.uri,e.type,t)))}}))}function h2(i){switch(i){case"agent":return"agent";case"skill":return"skill";case"instruction":case"agentInstruction":return"rule"}}async function y2(i,t,e){let n=i.toString(),r=Rn(n);if(t==="agent"){let o=await Bh(i,e),s={type:"agent",id:r,uri:n,name:o.name,description:o.description};return o.userInvocable!==void 0&&(s._meta={userInvocable:o.userInvocable}),s}if(t==="skill"){let o=await Vh(i,e);return{type:"skill",id:r,uri:n,name:o.name,description:o.description}}if(t==="instruction"){let o=await fT(i,e);return{type:"rule",id:r,uri:n,name:o.name,description:o.description,globs:o.globs,alwaysApply:o.alwaysApply}}return{type:"rule",alwaysApply:!0,id:r,uri:n,name:pe(i)}}function v2(i){if(i.length===0)return;let t=[],e=[],n=[];for(let r of i)for(let o of r.children??[]){if(o.type==="agent"){t.push({uri:y.parse(o.uri),name:o.name,description:o.description,customization:o});continue}if(o.type==="skill"){e.push({uri:y.parse(o.uri),name:o.name,description:o.description,customization:o});continue}if(o.type==="rule"){if(o.alwaysApply&&o.name.match(/\.md$/i))continue;n.push({uri:y.parse(o.uri),name:o.name,description:o.description,customization:o})}}if(!(t.length===0&&e.length===0&&n.length===0))return{hooks:[],mcpServers:[],skills:e,agents:t,instructions:n}}var Gl=class extends T{constructor(e,n,r,o,s){super();this.pluginManager=e;this.logService=n;this.fileService=r;this._configurationService=o;this.instantiationService=s;this._onDidChange=this._register(new w);this.onDidChange=this._onDidChange.event;this._hostCustomizations=[];this._hostSync=Promise.resolve([]);this._hostRevision=0;this._lastAppliedRefs=[];this._applyHostCustomizations(),this._register(this._configurationService.onDidRootConfigChange(()=>{this._applyHostCustomizations()}))}getConfiguredHostCustomizations(){return this._hostCustomizations.map(e=>e.customization)}hostCustomizations(){return this._hostCustomizations}hostSync(){return this._hostSync}getUserHome(){return process.env.HOME??process.env.USERPROFILE??""}createSessionController(e){return new sy(this,e)}_applyHostCustomizations(){let n=(this._configurationService.getRootValue(jt,"customizations")??[]).map($I);if(We(n,this._lastAppliedRefs))return;this._lastAppliedRefs=n;let r=++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=>(r===this._hostRevision&&(this._hostCustomizations=o),o)).finally(()=>{r===this._hostRevision&&this._onDidChange.fire()})}async resolveConfiguredCustomization(e){let n=y.parse(e.uri),r=await this.tryParsePlugin(n);return r?{customization:{...e,load:{kind:"loaded"},children:Yh([r])},pluginDir:n,plugin:r}:{customization:{...e,load:{kind:"error",message:g(2082,null)}}}}async resolveSyncedCustomization(e,n,r){let o={...e.customization,clientId:n};if(!e.pluginDir)return{customization:o,input:r};let s=await this.tryParsePlugin(e.pluginDir);return s?{customization:{...o,children:Yh([s])},pluginDir:e.pluginDir,plugin:s,input:r}:{customization:{...o,load:{kind:"error",message:g(2082,null)}},input:r}}async tryParsePlugin(e){try{return await mT(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}}};Gl=x([C(0,yi),C(1,O),C(2,Te),C(3,$e),C(4,ke)],Gl);var sy=class extends T{constructor(e,n){super();this._parent=e;this._directory=n;this._onDidPublish=this._register(new w);this.onDidPublish=this._onDidPublish.event;this._enablement=new Map;this._clientCustomizations=[];this._clientSync=Promise.resolve([]);this._clientRevision=0;this._sessionDiscovered=this._register(new vt)}get directory(){return this._directory}setDirectory(e){this._directory||!e||(this._directory=e)}getCustomizations(){let e=[...this._parent.hostCustomizations().map(o=>this._applyEnablement(o.customization)),...this._clientCustomizations.map(o=>this._applyEnablement(o.customization))],r=this._discoveredEntry()?.currentCustomizations()??[];for(let o of r)e.push(this._applyEnablement(o));return e}async getCustomizationsSettled(){let e=this._discoveredEntry();return await Promise.all([this._parent.hostSync().catch(n=>this._parent.logService.warn("[Copilot:SessionPluginController] Host customization update failed",n)),this._clientSync.catch(n=>this._parent.logService.warn("[Copilot:SessionPluginController] Client customization sync failed",n)),e?.whenSettled()]),this.getCustomizations()}async getAppliedPlugins(){let e=this._discoveredEntry(),[n,r]=await Promise.all([this._parent.hostSync().catch(l=>(this._parent.logService.warn("[Copilot:SessionPluginController] Host customization update failed",l),this._parent.hostCustomizations())),this._clientSync.catch(l=>(this._parent.logService.warn("[Copilot:SessionPluginController] Client customization sync failed",l),this._clientCustomizations)),e?.whenSettled()]),o=e?.currentCustomizations()??[],s=o.some(l=>this._isEnabled(l))?v2(o):void 0,a=s?[s]:[];return[...n.filter(l=>!!l.plugin&&this._isEnabled(l.customization)).map(l=>({...l.plugin,pluginDir:l.pluginDir})),...r.filter(l=>!!l.plugin&&this._isEnabled(l.customization)).map(l=>({...l.plugin,pluginDir:l.pluginDir})),...a]}setEnabled(e,n){this._enablement.get(e)!==n&&this._enablement.set(e,n)}sync(e,n,r){let o=r?.quiet===!0;this._clientId=e;let s=++this._clientRevision;this._clientCustomizations=n.map(u=>({customization:{...u,clientId:e,load:{kind:"loading"}},input:u})),o||this._onDidPublish.fire({type:"session/customizationsChanged",customizations:[...this.getCustomizations()]});let a=new Map;for(let u of this._clientCustomizations){let p=this._applyEnablement(u.customization);a.set(p.uri,p)}let l=u=>{let p=this._applyEnablement(u.customization);We(a.get(p.uri),p)||(a.set(p.uri,p),o||this._onDidPublish.fire({type:"session/customizationUpdated",customization:p}))},d=this._clientSync;return(this._clientSync=d.catch(u=>{this._parent.logService.warn("[Copilot:SessionPluginController] Previous customization sync failed",u)}).then(async()=>{let u=new Map(n.map(h=>[h.uri,h])),p=await this._parent.pluginManager.syncCustomizations(e,n,h=>{s===this._clientRevision&&l({customization:{...h,clientId:e},input:u.get(h.uri)})}),m=await Promise.all(p.map(h=>this._parent.resolveSyncedCustomization(h,e,u.get(h.customization.uri))));if(s===this._clientRevision){this._clientCustomizations=m;for(let h of m)l(h)}return m})).then(u=>u.map(p=>({customization:this._applyEnablement(p.customization),...p.pluginDir?{pluginDir:p.pluginDir}:{}})))}async retryFailedClientSyncIfNeeded(){if(await this._clientSync.catch(()=>{}),!this._clientId)return;let e=this._clientCustomizations.filter(r=>r.customization.load?.kind==="error"&&r.input!==void 0);if(e.length===0)return;let n=e.map(r=>r.input);this._parent.logService.info(`[Copilot:SessionPluginController] Retrying ${n.length} previously-failed client customization(s)`),await this.sync(this._clientId,n).catch(r=>{this._parent.logService.warn("[Copilot:SessionPluginController] Retried client customization sync failed",r)})}_discoveredEntry(){if(this._directory)return this._sessionDiscovered.value||(this._sessionDiscovered.value=new oy(this._directory,y.file(this._parent.getUserHome()),()=>this._onDidPublish.fire({type:"session/customizationsChanged",customizations:[...this.getCustomizations()]}),this._parent.logService,this._parent.instantiationService)),this._sessionDiscovered.value}_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}}},ay=class extends T{constructor(e,n,r){super();this._sessionUri=e;this.state=new Fs;this.pluginController=this._register(n),this._register(this.pluginController.onDidPublish(o=>{r.fire({kind:"action",session:this._sessionUri,action:o})}))}updateTools(e,n){this.state.update(e,n)}async snapshot(){return{tools:this.state.tools,plugins:await this.pluginController.getAppliedPlugins()}}async requiresRestart(e){let n=await this.pluginController.getAppliedPlugins();return zT(e.plugins,n)?!this.state.structuralEquals({tools:e.tools}):!0}};function Vs(i){switch(i){case"default":case"acceptEdits":case"bypassPermissions":case"plan":case"dontAsk":case"auto":return i;default:return}}var fx="thinkingLevel";function ly(i){if(i!==void 0)return i==="max"?"xhigh":i}function Jl(i){let t=i?.config?.[fx];switch(t){case"low":case"medium":case"high":case"xhigh":case"max":return t;default:return}}var S2=["low","medium","high","xhigh","max"];function gx(i){return S2.includes(i)}function b2(i){switch(i){case"low":return g(1898,null);case"medium":return g(1900,null);case"high":return g(1897,null);case"xhigh":return g(1902,null);case"max":return g(1899,null)}}function mx(i){if(i.length===0)return;let t=i.includes("high")?"high":void 0;return{type:"object",properties:{[fx]:{type:"string",title:g(1901,null),description:g(1896,null),enum:[...i],enumLabels:i.map(b2),...t!==void 0?{default:t}:{}}}}}import{pathToFileURL as Ix}from"url";import*as Sx from"fs";import*as bx from"tar";var Vp,hx=!1;function yx(){return hx||(Se?Vp=process.report?.getReport()?.header?.glibcVersionRuntime?"glibc":"musl":Vp=void 0,hx=!0),Vp}var I2=new Set(["linux","darwin","win32"]),_2=new Set(["x64","arm64"]);function vx(i,t={platform:process.platform,arch:process.arch,libc:yx()}){if(!(!I2.has(t.platform)||!_2.has(t.arch)))return t.platform==="linux"&&i.hasSeparateMuslLinuxPackage&&t.libc==="musl"?`linux-${t.arch}-musl`:`${t.platform}-${t.arch}`}var js=$("agentSdkDownloader"),C2=3e4,zs=class{constructor(t,e,n,r,o){this._environmentService=t;this._productService=e;this._requestService=n;this._fileService=r;this._logService=o;this._pendingDownloads=new Map;this._failureLatch=new Map}isAvailable(t){return process.env[t.devOverrideEnvVar]?!0:!!this._productService.agentSdks?.[t.id]&&vx(t)!==void 0}async loadSdkRoot(t,e){let n=process.env[t.devOverrideEnvVar];if(n)return this._logService.info(`[AgentSdkDownloader] ${t.id}: using dev override at ${n}`),n;let r=this._failureLatch.get(t.id);if(r&&r.expiresAt>Date.now())throw r.error;try{let o=await this._resolveOrDownload(t,e);return this._failureLatch.delete(t.id),o}catch(o){if(e.isCancellationRequested)throw o;let s=o instanceof Error?o:new Error(String(o));throw this._failureLatch.set(t.id,{error:s,expiresAt:Date.now()+C2}),s}}async _resolveOrDownload(t,e){let n=this._productService.agentSdks?.[t.id];if(!n)throw new Error(`Cannot load ${t.id} SDK: no \`product.agentSdks.${t.id}\` configured and no ${t.devOverrideEnvVar} dev override set.`);let r=vx(t);if(!r)throw new Error(`Cannot load ${t.id} SDK: no SDK target for this host (${process.platform}/${process.arch}). Set ${t.devOverrideEnvVar} to a local SDK root to bypass.`);let o=nS(n.urlTemplate,{sdkTarget:r}),s=/{[^}]+}/.exec(o);if(s)throw new Error(`Cannot load ${t.id} SDK: \`product.agentSdks.${t.id}.urlTemplate\` contains an unknown placeholder ${s[0]} \u2014 only {sdkTarget} is substituted. Template: ${n.urlTemplate}`);let a=this._cacheDir(t.id,n.version,r),l=y.joinPath(y.file(a),".complete");if(await this._fileService.exists(l))return a;let d=this._pendingDownloads.get(a);return d||(d=this._download(t,o,a,l,e).finally(()=>{this._pendingDownloads.delete(a)}),this._pendingDownloads.set(a,d)),d}_cacheDir(t,e,n){return W(this._environmentService.userDataPath,"agent-host","sdk-cache",t,e,n)}async _download(t,e,n,r,o){this._logService.info(`[AgentSdkDownloader] ${t.id}: downloading from ${e}`);let s=Date.now(),a=se(n);await this._fileService.createFolder(y.file(a));let l=`${n}.tmp.${process.pid}`,d=y.file(l);await this._delIgnoringMissing(d),await this._fileService.createFolder(d);try{let c=W(l,"sdk.tgz");await this._fetch(e,c,o),await this._extractTarGz(c,l),await this._fileService.del(y.file(c)),await this._fileService.writeFile(y.joinPath(d,".complete"),A.fromString(""));try{await this._fileService.move(d,y.file(n))}catch(p){if(await this._handleRenameLoser(p,r,d))return this._logService.info(`[AgentSdkDownloader] ${t.id}: lost rename race, using existing cache`),n;throw p}let u=Math.round((Date.now()-s)/1e3);return this._logService.info(`[AgentSdkDownloader] ${t.id}: downloaded in ${u}s`),n}catch(c){throw await this._delIgnoringMissing(d),o.isCancellationRequested?new K:new Error(`Failed to download ${t.id} SDK from ${e} (cache target: ${n}). Set ${t.devOverrideEnvVar} to a local SDK root to bypass. Cause: ${c instanceof Error?c.message:String(c)}`)}}async _handleRenameLoser(t,e,n){return!(t instanceof Ke)||t.fileOperationResult!==4||!await this._fileService.exists(e)?!1:(await this._delIgnoringMissing(n),!0)}async _fetch(t,e,n){if(n.isCancellationRequested)throw new K;let r=await this._requestService.request({url:t,type:"GET",callSite:"agentSdkDownloader"},n);if(n.isCancellationRequested)throw r.stream.destroy(),new K;let o=r.res.statusCode??0;if(o<200||o>=300)throw r.stream.destroy(),new Error(`HTTP ${o} fetching ${t}`);await new Promise((s,a)=>{let l=Sx.createWriteStream(e),d=!1,c=()=>{d||(d=!0,p.dispose(),s())},u=m=>{d||(d=!0,p.dispose(),r.stream.destroy(),l.destroy(),a(m))},p=n.onCancellationRequested(()=>u(new K));l.on("error",u),l.on("finish",c),l.on("drain",()=>r.stream.resume()),r.stream.on("data",m=>{l.write(m.buffer)||r.stream.pause()}),r.stream.on("end",()=>l.end()),r.stream.on("error",u)})}async _extractTarGz(t,e){await bx.x({file:t,cwd:e})}async _delIgnoringMissing(t){try{await this._fileService.del(t,{recursive:!0})}catch(e){if(Ja(e)!==1)throw e}}};zs=x([C(0,yn),C(1,gt),C(2,Lu),C(3,Te),C(4,O)],zs);var zp={id:"claude",devOverrideEnvVar:Wg,hasSeparateMuslLinuxPackage:!0},Gs=$("claudeAgentSdkService"),Ks=class{constructor(t,e){this._logService=t;this._downloader=e;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,r){return(await this._getSdk()).tool(t,e,n,r)}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[Wg];if(t){let e=W(t,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(Ix(e).href)}if(this._downloader.isAvailable(zp)){let e=await this._downloader.loadSdkRoot(zp,Ee.None),n=W(e,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(Ix(n).href)}return import("@anthropic-ai/claude-agent-sdk")}};Ks=x([C(0,O),C(1,js)],Ks);var Ql={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}},Yl="mcp__";function jp(i){let t=Ql[i];return t?t.permissionKind:i.startsWith(Yl)?"mcp":"custom-tool"}function Yt(i){switch(i){case"Bash":return g(1966,null);case"BashOutput":return g(1967,null);case"KillBash":return g(1972,null);case"Read":return g(1978,null);case"Glob":return g(1970,null);case"Grep":return g(1971,null);case"LS":return g(1973,null);case"NotebookRead":return g(1977,null);case"Write":return g(1982,null);case"Edit":return g(1968,null);case"MultiEdit":return g(1975,null);case"NotebookEdit":return g(1976,null);case"TodoWrite":return g(1980,null);case"WebFetch":return g(1981,null);case"Task":case"Agent":return g(1979,null);case"ExitPlanMode":return g(1969,null);case"AskUserQuestion":return g(1965,null)}return i.startsWith(Yl)?g(1974,null,i.slice(Yl.length)):i}function Jn(i,t){let e=Ql[i];if(!e?.pathField||typeof t!="object"||t===null)return;let n=t[e.pathField];return typeof n=="string"?n:void 0}function _x(i){return Ql[i]?.isFileEdit===!0}var Cx=new Set(Object.entries(Ql).filter(([,i])=>i.interactive).map(([i])=>i));function Tx(i){switch(jp(i)){case"shell":return g(1962,null);case"write":return g(1964,null);case"read":return g(1961,null);case"url":return g(1963,null);case"mcp":{let t=i.startsWith(Yl)?i.slice(Yl.length).split("__")[0]:void 0;return t?g(1960,null,t):g(1959,null)}default:return g(1959,null)}}function Yn(i){let t=Ql[i];if(t?.toolKind)return{toolKind:t.toolKind}}function Jt(i){return{markdown:i}}function Js(i){let t=y.file(i);return`[${Ns(pe(t))}](${t})`}function Gn(i,t){if(i===null||typeof i!="object")return;let e=i[t];return typeof e=="string"&&e.length>0?e:void 0}function xx(i){let t=Gn(i,"command");return t?t.split(`
`)[0]:void 0}function Lr(i,t,e){switch(i){case"Bash":{let n=xx(e);return n?Jt(g(2004,null,Ye(ar(n,80)))):g(2003,null)}case"BashOutput":return g(2005,null);case"KillBash":return g(2012,null);case"Read":case"NotebookRead":{let n=Jn(i,e);return n?Jt(g(2016,null,Js(n))):g(2015,null)}case"LS":{let n=Jn(i,e);return n?Jt(g(2014,null,Js(n))):g(2013,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let n=Jn(i,e);return n?Jt(g(2007,null,Js(n))):g(2006,null)}case"TodoWrite":return g(2017,null);case"Grep":{let n=Gn(e,"pattern");return n?Jt(g(2011,null,Ye(ar(n,80)))):g(2010,null)}case"Glob":{let n=Gn(e,"pattern");return n?Jt(g(2009,null,Ye(ar(n,80)))):g(2008,null)}case"WebFetch":{let n=Gn(e,"url");return n?Jt(g(2018,null,`[${Ns(ar(n,80))}](${n})`)):g(2019,null)}case"Task":case"Agent":{let n=Gn(e,"description");return n||t}default:return t}}function Kp(i,t,e,n){if(!n)return g(1988,null,t);switch(i){case"Bash":{let r=xx(e);return r?Jt(g(1984,null,Ye(ar(r,80)))):g(1983,null)}case"BashOutput":return g(1985,null);case"KillBash":return g(1994,null);case"Read":case"NotebookRead":{let r=Jn(i,e);return r?Jt(g(1998,null,Js(r))):g(1997,null)}case"LS":{let r=Jn(i,e);return r?Jt(g(1996,null,Js(r))):g(1995,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let r=Jn(i,e);return r?Jt(g(1987,null,Js(r))):g(1986,null)}case"TodoWrite":return g(2000,null);case"Grep":{let r=Gn(e,"pattern");return r?Jt(g(1993,null,Ye(ar(r,80)))):g(1992,null)}case"Glob":{let r=Gn(e,"pattern");return r?Jt(g(1991,null,Ye(ar(r,80)))):g(1990,null)}case"WebFetch":{let r=Gn(e,"url");return r?Jt(g(2001,null,`[${Ns(ar(r,80))}](${r})`)):g(2002,null)}case"Task":case"Agent":return g(1999,null);default:return g(1989,null,t)}}function bi(i,t){if(t!==void 0){if(i==="Bash"||i==="BashOutput"||i==="KillBash"){let e=Gn(t,"command");if(e)return e}if(i==="Grep"||i==="Glob"){let e=Gn(t,"pattern");if(e)return e}try{return JSON.stringify(t,null,2)}catch{return}}}import{z as ht}from"zod";function Jp(i){if(!i||i.type!=="object"||!i.properties)return{};let t=new Set(i.required??[]),e={};for(let[n,r]of Object.entries(i.properties)){let o;try{o=Gp(r)}catch{o=ht.any()}t.has(n)||(o=o.optional()),e[n]=o}return e}function Gp(i){if(!i||typeof i!="object")return ht.any();let t;if(Array.isArray(i.enum)&&i.enum.length>0){let e=i.enum.filter(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null);e.length===0?t=ht.any():e.length===1?t=ht.literal(e[0]):t=ht.union(e.map(n=>ht.literal(n)))}else if(Array.isArray(i.oneOf)&&i.oneOf.length>0)t=wx(i.oneOf);else if(Array.isArray(i.anyOf)&&i.anyOf.length>0)t=wx(i.anyOf);else switch(Array.isArray(i.type)?i.type[0]:i.type){case"string":t=ht.string();break;case"number":t=ht.number();break;case"integer":t=ht.number().int();break;case"boolean":t=ht.boolean();break;case"array":t=ht.array(i.items?Gp(i.items):ht.any());break;case"object":{let n={},r=new Set(i.required??[]);for(let[o,s]of Object.entries(i.properties??{})){let a;try{a=Gp(s)}catch{a=ht.any()}r.has(o)||(a=a.optional()),n[o]=a}t=ht.object(n);break}case"null":t=ht.null();break;default:t=ht.any()}return i.nullable&&(t=t.nullable()),i.description&&(t=t.describe(i.description)),i.default!==void 0&&(t=t.default(i.default)),t}function wx(i){let t=i.map(e=>{try{return Gp(e)}catch{return ht.any()}});return t.length===1?t[0]:ht.union(t)}var Rx="claudecode/toolUseId";async function Ex(i,t,e){let n=await Promise.all(i.map(r=>e.tool(r.name,r.description??"",Jp(r.inputSchema),async(o,s)=>{let a=T2(s);return a===void 0?{content:[{type:"text",text:`Client tool "${r.name}" could not run: SDK omitted tool_use_id (expected at extra._meta["${Rx}"]).`}],isError:!0}:t(a)})));return e.createSdkMcpServer({name:dy,tools:n})}function T2(i){if(!i||typeof i!="object")return;let t=i._meta;if(!t||typeof t!="object")return;let e=t[Rx];return typeof e=="string"?e:void 0}var dy="client";function Ys(i){let t=`mcp__${dy}__`;return i.startsWith(t)?i.slice(t.length):i}function Px(i){return i.startsWith(`mcp__${dy}__`)}function Xl(i,t,e){let n=new cy(t,e);for(let r of i){let o=x2(r);o!==void 0&&n.consume(o)}return n.finish()}function x2(i){switch(i.type){case"user":return w2(i);case"assistant":return R2(i);case"system":return E2(i);default:return}}function w2(i){let t=A2(i.message);if(t===void 0||N2(t))return;if(typeof t=="string")return{kind:"user-text",uuid:i.uuid,text:t};let e=t.filter(n=>n.type==="text");if(e.length===0){let n=t.filter(r=>r.type==="tool_result");return n.length>0?{kind:"user-tool-results",uuid:i.uuid,results:n}:void 0}return{kind:"user-text",uuid:i.uuid,text:e.map(n=>n.text).join(`
`)}}function R2(i){let t=k2(i.message);if(!(t===void 0||t.length===0))return{kind:"assistant",uuid:i.uuid,blocks:t}}function E2(i){let t=D2(i.message);if(t===void 0||!P2.has(t))return;let e=O2(i.message)??`[${t}]`;return{kind:"system-notification",uuid:i.uuid,subtype:t,text:e}}var P2=new Set(["compact_boundary","notification"]),Ax=/^<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat)>/,cy=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 r of t.blocks)r.type==="text"&&typeof r.text=="string"?this._active.responseParts.push({kind:"markdown",id:`${this._active.id}#${t.uuid}#text-${e++}`,content:r.text}):r.type==="thinking"&&typeof r.thinking=="string"?this._active.responseParts.push({kind:"reasoning",id:`${this._active.id}#${t.uuid}#thinking-${n++}`,content:r.thinking}):r.type==="tool_use"&&typeof r.id=="string"&&typeof r.name=="string"&&this._openToolUse(r.id,Ys(r.name),r.input)}_openToolUse(t,e,n){if(this._active===void 0)return;let r=Yt(e),o=n!==null&&typeof n=="object"?n:void 0,s=Yn(e),a={status:"cancelled",toolCallId:t,toolName:e,displayName:r,invocationMessage:Lr(e,r,o),toolInput:o!==void 0?bi(e,o):typeof n=="string"?n:n!==void 0?L2(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,r=this._findToolCallPart(n,t.tool_use_id);if(r===void 0)return;let o=t.is_error,s=r.toolCall,a=s._meta?.toolKind==="subagent",l=M2(t.content)??[];a&&l.push({type:"subagent",resource:Qo(this._session.toString(),s.toolCallId),title:s.displayName});let d={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:Kp(s.toolName,s.displayName,e.parsedInput,!o),content:l.length>0?l:void 0,...s._meta?{_meta:s._meta}:{}};r.toolCall=d,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 r of this._turns[n].responseParts)if(r.kind==="toolCall"&&r.toolCall.toolCallId===e)return r;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 A2(i){if(i===null||typeof i!="object")return;let t=i.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 r=n;r.type==="text"&&typeof r.text=="string"?e.push({type:"text",text:r.text}):r.type==="tool_result"&&typeof r.tool_use_id=="string"&&e.push({type:"tool_result",tool_use_id:r.tool_use_id,content:r.content,is_error:r.is_error===!0})}return e.length>0?e:void 0}function k2(i){if(i===null||typeof i!="object")return;let t=i.content;if(!Array.isArray(t))return;let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let r=n;typeof r.type=="string"&&e.push({type:r.type,text:typeof r.text=="string"?r.text:void 0,thinking:typeof r.thinking=="string"?r.thinking:void 0,id:typeof r.id=="string"?r.id:void 0,name:typeof r.name=="string"?r.name:void 0,input:r.input})}return e}function D2(i){if(i===null||typeof i!="object")return;let t=i.subtype;return typeof t=="string"?t:void 0}function O2(i){if(i===null||typeof i!="object")return;let t=i;if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message}function M2(i){if(typeof i=="string")return i.length>0?[{type:"text",text:i}]:void 0;if(!Array.isArray(i))return;let t=[];for(let e of i){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 L2(i){try{return JSON.stringify(i)}catch{return}}function N2(i){if(typeof i=="string")return Ax.test(i);let t=i.find(e=>e.type==="text");return t!==void 0&&Ax.test(t.text)}var uy=class{validateOrThrow(t){let e=this.validate(t);if(e.error)throw new Error(e.error.message);return e.content}},Qs=class extends uy{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}}},U2=new Qs("string");function kx(){return U2}var Sce=new Qs("number");var bce=new Qs("boolean");var F2=new Qs("object");function Dx(){return F2}var Zl=new Set(["Task","Agent"]),W2=/^\s*agentId:\s+([a-z0-9]+)\b/im,py=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)}},Yp=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 r=this._spawns.get(e);return r||(r=new py(e),this._spawns.set(e,r)),n?.agentId!==void 0&&r.setAgentId(n.agentId),n?.subagentType!==void 0&&r.subagentType===void 0&&(r.subagentType=n.subagentType),n?.description!==void 0&&r.description===void 0&&(r.description=n.description),r}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,r]of fy(e))this.recordSpawn(n,{agentId:r})}_evictInnerEdgesFor(e){for(let[n,r]of this._innerToParent)r===e&&this._innerToParent.delete(n)}};function fy(i){let t=new Map;for(let e of i)for(let n of e.responseParts){let r=$2(n);r&&t.set(r.toolCallId,r.agentId)}return t}function $2(i){if(i.kind!=="toolCall")return;let t=i.toolCall;if(!Zl.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 r=e[n];if(r.type!=="text")continue;let o=W2.exec(r.text);if(o)return{toolCallId:t.toolCallId,agentId:o[1]}}}var gy=class{constructor(t,e){this._sdk=t;this._logService=e;this.name="text_suffix"}async lookup(t,e){let n=await Ox(this._sdk,this._logService,e,"TextSuffix");if(n)return fy(n).get(t)}};async function Ox(i,t,e,n){if(e.parentTranscript)return e.parentTranscript;try{let r=await i.getSessionMessages(e.parentSessionId,{includeSystemMessages:!0});return Xl(r,e.parentUri,t)}catch(r){t.warn(`[claudeSubagentResolver] ${n}: parent transcript fetch failed: ${r}`);return}}function Mx(i){let t=kx().validate(i);return t.error?void 0:t.content}function my(i){let t=Dx().validate(i);if(!(t.error||t.content===null||Array.isArray(t.content)))return t.content}var hy=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 r;try{r=await this._sdk.listSubagents(e.parentSessionId)}catch(o){this._logService.warn(`[claudeSubagentResolver] PromptMatch: listSubagents failed: ${o}`);return}for(let o of r){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=q2(s);if(a!==void 0&&a===n)return o}}async _loadParentPrompt(t,e){let n=await Ox(this._sdk,this._logService,e,"PromptMatch");if(n)return H2(n,t)}};function H2(i,t){for(let e of i)for(let n of e.responseParts){if(n.kind!=="toolCall")continue;let r=n.toolCall;if(r.toolCallId!==t)continue;if(!Zl.has(r.toolName)||r.status==="streaming")return;let o=r.toolInput;if(typeof o!="string")return;let s;try{s=JSON.parse(o)}catch{return}let a=my(s);return a?Mx(a.prompt):void 0}}function q2(i){for(let t of i){if(t.type!=="user")continue;let e=my(t.message);if(!e)continue;let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))for(let r of n){let o=my(r);if(!o||o.type!=="text")continue;let s=Mx(o.text);if(s!==void 0)return s}}}var yy=class{constructor(){this.name="native"}async lookup(){}};async function B2(i,t,e){let n=e.cacheGet(i);if(n)return n;for(let r of e.strategies){if(t.token.isCancellationRequested)return;let o=await r.lookup(i,t);if(o)return e.cacheSet(i,o),o}}function V2(i,t){return[new gy(i,t),new hy(i,t),new yy]}async function Lx(i,t,e,n,r){let o=Xe(i);if(!o)throw new Error(`getSubagentTranscript: not a subagent URI: ${i.toString()}`);let{parentSession:s,toolCallId:a}=o,l=F.id(s),d=await B2(a,{parentUri:s,parentSessionId:l,token:r},{strategies:V2(e,n),cacheGet:u=>t.getSpawn(u)?.agentId,cacheSet:(u,p)=>{t.recordSpawn(u,{agentId:p})}});if(!d)return[];let c;try{c=await e.getSubagentMessages(l,d)}catch(u){return n.warn(`[getSubagentTranscript] getSubagentMessages(${d}) failed: ${u}`),[]}return Xl(c,i,n)}async function vy(i,t,e,n){let r=z2(),o=await Ps(),s={ANTHROPIC_BASE_URL:t.baseUrl,ANTHROPIC_AUTH_TOKEN:`${t.nonce}.${i.sessionId}`,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",USE_BUILTIN_RIPGREP:"0",PATH:`${se(o)}${xo}${process.env.PATH??""}`};return{cwd:i.workingDirectory.fsPath,executable:process.execPath,env:r,abortController:i.abortController,allowDangerouslySkipPermissions:!0,canUseTool:i.canUseTool,onElicitation:async a=>(n(a.message??""),{action:"cancel"}),disallowedTools:["WebSearch"],includePartialMessages:!0,forwardSubagentText:!0,enableFileCheckpointing:!0,model:i.model?.id,effort:Jl(i.model),permissionMode:i.permissionMode,...i.isResume?{resume:i.sessionId}:{sessionId:i.sessionId},...i.mcpServers?{mcpServers:i.mcpServers}:{},...i.allowedTools&&i.allowedTools.length>0?{allowedTools:[...i.allowedTools]}:{},...i.plugins&&i.plugins.length>0?{plugins:i.plugins.map(a=>({type:"local",path:a.fsPath}))}:{},...i.agent?{agent:i.agent}:{},settingSources:["user","project","local"],settings:{env:s},systemPrompt:{type:"preset",preset:"claude_code"},stderr:e}}async function Nx(i,t,e){let{tools:n}=i.consume();return!n||n.length===0?void 0:{client:await Ex(n,o=>t.register(o),e)}}function z2(){let i={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_"))&&(i[t]=void 0);return i}var Qp="host";function Ux(i){return i.map(t=>`mcp__${Qp}__${t}`)}async function Fx(i,t,e){let n=await Promise.all(i.definitions.map(r=>e.tool(r.name,r.description??"",Jp(r.inputSchema),async o=>{try{return{content:[{type:"text",text:i.executeTool(t,r.name,o)}]}}catch(s){return{content:[{type:"text",text:s instanceof Error?s.message:String(s)}],isError:!0}}})));return e.createSdkMcpServer({name:Qp,tools:n})}var j2="claude-client";function Wx(i,t){let r={content:(i.content??[]).map((o,s)=>K2(o,t,s))};return i.structuredContent!==void 0&&(r.structuredContent=i.structuredContent),(!i.success||i.error)&&(r.isError=!0),r}function K2(i,t,e){switch(i.type){case"text":return{type:"text",text:i.text};case"embeddedResource":return G2(i,t,e);default:{console.warn(`[Claude] convertToolCallResult: unsupported tool-result block kind '${i.type}'; degrading to text`);let n;try{n=JSON.stringify(i)}catch{n=`[unserializable ${i.type} block]`}return{type:"text",text:n}}}}function G2(i,t,e){return i.contentType.startsWith("image/")?{type:"image",data:i.data,mimeType:i.contentType}:{type:"resource",resource:{uri:`${j2}://${encodeURIComponent(t)}/${e}`,mimeType:i.contentType,blob:i.data}}}function Xs(i,t){return Vs(i.getSessionConfigValues(t.toString())?.permissionMode)}var J2={tools:void 0,clientId:void 0},Sy=class{constructor(){this._state=Bi({owner:this,equalsFn:Y2},J2);this.state=this._state}setTools(t,e){let n=this._state.get();this._state.set({tools:t,clientId:e??n.clientId},void 0)}},Xp=class extends T{constructor(){super();this.model=new Sy;this._dirty=!1;this._ignoreNextFire=!0;this._lastAppliedTools=void 0;this._register(Un(e=>{let n=this.model.state.read(e);if(this._ignoreNextFire){this._ignoreNextFire=!1,this._lastAppliedTools=n.tools;return}Sp(n.tools,this._lastAppliedTools)||(this._dirty=!0)}))}get hasDifference(){return this._dirty}consume(){let e=this.model.state.get();return this._dirty=!1,this._lastAppliedTools=e.tools,e}markDirty(){this._dirty=!0}};function Y2(i,t){return i.clientId===t.clientId&&Sp(i.tools,t.tools)}var Q2={synced:[],enablement:new Map},by=class{constructor(){this._state=Bi({owner:this,equalsFn:X2},Q2);this.state=this._state;this.enabledPluginPaths=Ka({owner:this,equalsFn:(t,e)=>Xt(t,e,(n,r)=>n.toString()===r.toString())},t=>{let e=this._state.read(t),n=[];for(let r of e.synced)r.pluginDir&&e.enablement.get(r.customization.id)!==!1&&n.push(r.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(),r=n.enablement.get(t);if(r===e||e&&r===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)}},Zp=class extends T{constructor(){super();this.model=new by;this._dirty=!1;this._ignoreNextFire=!0;this.onDidChange=Q.fromObservableLight(this.model.state);this._register(Un(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 X2(i,t){return Z2(i.synced,t.synced)&&tM(i.enablement,t.enablement)}function Z2(i,t){if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++){let n=i[e].customization,r=t[e].customization;if(n.id!==r.id||n.uri!==r.uri||n.nonce!==r.nonce||n.name!==r.name||n.enabled!==r.enabled||n.load?.kind!==r.load?.kind||Hx(n.load)!==Hx(r.load)||!eM(n.children,r.children)||i[e].pluginDir?.toString()!==t[e].pluginDir?.toString())return!1}return!0}function Hx(i){return i&&i.message?i.message:void 0}function eM(i,t){if(i===t)return!0;if(!i||!t||i.length!==t.length)return!1;for(let e=0;e<i.length;e++)if(i[e].id!==t[e].id||i[e].name!==t[e].name)return!1;return!0}function tM(i,t){if(i.size!==t.size)return!1;for(let[e,n]of i)if(t.get(e)!==n)return!1;return!0}function qx(i,t,e){let n=[];for(let r of i){let o=t.get(r.customization.id)??r.customization.enabled;n.push({...r.customization,enabled:o})}return e&&n.push(e),n}var nM="claude-discovered",rM=g(2020,null),iM="claude-discovered",oM="general-purpose",Zs=class extends T{constructor(e,n,r){super();this._fileService=n;let o=`claude-${rn(e.toString())}`;this._rootUri=y.joinPath(r.basePath,iM,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 r=String(rn(n.join(`
`)));if(this._lastNonce!==r){try{await this._fileService.del(this._rootUri,{recursive:!0})}catch{}let l=y.joinPath(this._rootUri,".plugin","plugin.json");await this._fileService.writeFile(l,A.fromString(JSON.stringify({name:nM,description:"Customizations discovered by the Claude agent"},null,"	")));for(let d of e.agents){let c=y.joinPath(this._rootUri,"agents",`${ef(d.name)}.md`);await this._fileService.writeFile(c,A.fromString(sM(d.name,d.description)))}for(let d of e.commands){let c=ef(d.name),u=y.joinPath(this._rootUri,"skills",c,"SKILL.md");await this._fileService.writeFile(u,A.fromString(aM(c,d.description,d.argumentHint)))}this._lastNonce=r}let o=e.agents.filter(l=>l.name!==oM).map(l=>{let d=y.joinPath(this._rootUri,"agents",`${ef(l.name)}.md`).toString();return{type:"agent",id:Rn(d),uri:d,name:l.name,description:l.description}}),s=e.commands.map(l=>{let d=ef(l.name),c=y.joinPath(this._rootUri,"skills",d,"SKILL.md").toString();return{type:"skill",id:Rn(c),uri:c,name:d,description:l.description}}),a=this._rootUri.toString();return{type:"plugin",id:Rn(a),uri:a,name:rM,enabled:!0,load:{kind:"loaded"},children:[...o,...s]}}};Zs=x([C(1,Te),C(2,yi)],Zs);function ef(i){return i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,128)||"unnamed"}function sM(i,t){return`---
name: ${tf(i)}
description: ${tf(Bx(t,1024))}
---
`}function aM(i,t,e){let n=e?`
Usage: \`${e}\`
`:"";return`---
name: ${tf(i)}
description: ${tf(Bx(t,1024))}
---
${n}`}function tf(i){return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r?\n/g," ")}"`}function Bx(i,t){return i.length<=t?i:`${i.slice(0,t-1)}\u2026`}function nf(i,t){let e=[{type:"text",text:i}];if(!t?.length)return e;let n=[],r=[];for(let o of t){if(o.type==="simple"){o.modelRepresentation&&r.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(`- ${Vx(s)}${a}`)}else n.push(`- ${Vx(s)}`)}return r.length>0&&e.push({type:"text",text:r.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 Vx(i){return i.scheme==="file"?i.fsPath:i.toString()}var ea=class extends T{constructor(e,n,r,o){super();this._sessionId=e;this._getAbortSignal=n;this._onSteeringYielded=r;this._logService=o;this._toYield=[];this._yielded=[];this._popped=[];this._pendingPromptDeferred=new Ie;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 Ie}}})}}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=r=>{for(let o of r)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 Ie}};ea=x([C(3,O)],ea);var ta=class extends T{constructor(e,n,r,o){super();this._logService=r;this._editToolPaths=new Map;this._register(n),this._editTracker=o.createInstance(li,e,n.object)}observeAssistant(e){let n=e.message.content;if(Array.isArray(n))for(let r of n){if(r.type!=="tool_use"||!_x(r.name))continue;let o=Jn(r.name,r.input);o&&(this._editToolPaths.set(r.id,o),this._editTracker.trackEditStart(o).catch(s=>this._logService.warn(`[ClaudeFileEditObserver] trackEditStart failed for ${o}: ${s}`)))}}async observeUser(e,n,r){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&&r.cacheFileEdit(s.tool_use_id,l)}catch(l){this._logService.warn(`[ClaudeFileEditObserver] file edit tracking failed for ${a}: ${l}`)}}}}};ta=x([C(2,O),C(3,ke)],ta);var Iy=Zl;function rf(i,t,e,n){if(!e)return i;let r=i.map(a=>a.kind==="action"?{...a,parentToolCallId:e}:a.kind==="pending_confirmation"?{...a,parentToolCallId:e}:a),o=n.getSpawn(e);return!o||!o.markAnnounced()?r:[{kind:"subagent_started",session:t,toolCallId:e,agentName:o.subagentType??"subagent",agentDisplayName:o.subagentType??"Subagent",agentDescription:o.description},...r]}function zx(i,t,e){let n=i.subtype;if(n==="task_started"){let r=i.tool_use_id,o=r?e.getSpawn(r):void 0;return o&&(o.background=!0),[]}if(n==="task_notification"){let r=i;if(!r.tool_use_id)return[];let o=r.status;if(o!=="completed"&&o!=="failed"&&o!=="stopped")return[];let s=e.getSpawn(r.tool_use_id);if(!s||!s.markCompleted())return[];let a=r.tool_use_id;return e.removeSpawn(a),[{kind:"subagent_completed",session:t,toolCallId:a}]}return[]}function jx(i,t,e,n){let r=i.input,o=typeof r?.description=="string"?r.description:void 0,s=typeof r?.subagent_type=="string"?r.subagent_type:void 0,a=i.input!==void 0?lM(i.input):void 0;n.recordSpawn(i.id,{subagentType:s,description:o});let l={...Yn(i.name)??{toolKind:"subagent"}};return o&&(l.subagentDescription=o),s&&(l.subagentAgentName=s),{kind:"action",session:t,action:{type:"session/toolCallReady",turnId:e,toolCallId:i.id,invocationMessage:Lr(i.name,Yt(i.name),i.input),...a!==void 0?{toolInput:a}:{},confirmed:"not-needed",_meta:l}}}function Kx(i,t,e,n,r,o){let s=i.message.id,a=[];for(let l=0;l<i.message.content.length;l++){let d=i.message.content[l];if(d.type==="text"){a.push({kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"markdown",id:`${e}#${s}#${l}`,content:d.text}}});continue}if(d.type==="thinking"){a.push({kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"reasoning",id:`${e}#${s}#${l}`,content:d.thinking}}});continue}if(d.type==="tool_use"){let c=Ys(d.name);n.startToolBlock(l,d.id,c,e),n.toolCalls.seedParsedInput(d.id,d.input),o.noteInnerTool(d.id,r);let u=Yt(c),p=Yn(c),m=bi(c,d.input);a.push({kind:"action",session:t,action:{type:"session/toolCallStart",turnId:e,toolCallId:d.id,toolName:c,displayName:u,...p?{_meta:p}:{}}}),a.push({kind:"action",session:t,action:{type:"session/toolCallReady",turnId:e,toolCallId:d.id,invocationMessage:Lr(c,u,d.input),...m!==void 0?{toolInput:m}:{},confirmed:"not-needed"}});continue}}return a}function lM(i){try{return JSON.stringify(i)}catch{return}}var of=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 r=e.inputBuffer.length>0?e.inputBuffer:void 0;this._writeInfo(e,n,r),e.inputBuffer=""}seedParsedInput(t,e){let n=this._entries.get(t);if(!n)return;let r=e!==null&&typeof e=="object"?e:void 0;this._writeInfo(n,r)}_writeInfo(t,e,n){let r=Yt(t.toolName);t.info={toolName:t.toolName,displayName:r,parsedInput:e,invocationMessage:Lr(t.toolName,r,e),toolInput:bi(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 af=class{constructor(){this._activeToolBlocks=new Map;this.toolCalls=new of;this._completedFileEdits=new Map}resetMessage(t){this._activeToolBlocks.clear(),this._currentMessageId=t}getCurrentMessageId(){return this._currentMessageId}startToolBlock(t,e,n,r){this._activeToolBlocks.set(t,{toolUseId:e,toolName:n}),this.toolCalls.begin(e,n,r)}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 Gx(i,t,e,n,r,o,s){if(r.getLevel()<=1)try{let a=JSON.stringify(i,(l,d)=>typeof d=="string"&&d.length>200?d.slice(0,200)+"\u2026":d);r.trace(`[claudeMapSessionEvents] SDK message type=${i.type}: ${a?.slice(0,2e3)??"<unserializable>"}`)}catch{r.trace(`[claudeMapSessionEvents] SDK message type=${i.type} (unserializable)`)}switch(i.type){case"stream_event":return rf(mM(i.event,t,e,n,r,i.parent_tool_use_id,o,s),t,i.parent_tool_use_id,o);case"result":return fM(i,t,e,n,r,o);case"assistant":return rf(dM(i,t,e,n,i.parent_tool_use_id,o),t,i.parent_tool_use_id,o);case"user":return rf(cM(i,t,n,r,o),t,i.parent_tool_use_id,o);default:return i.type==="system"?zx(i,t,o):[]}}function dM(i,t,e,n,r,o){if(r===null){let s=[];for(let a of i.message.content)a.type!=="tool_use"||!Iy.has(a.name)||s.push(jx(a,t,e,o));return s}return Kx(i,t,e,n,r,o)}function cM(i,t,e,n,r){let o=i.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 d=a.is_error===!0,c=uM(a.content)??[],u=e.takeFileEdit(a.tool_use_id);u&&c.push(u);let p=e.toolCalls.lookup(a.tool_use_id)?.info,m=p?Kp(p.toolName,p.displayName,p.parsedInput,!d):`${Yt(l.toolName)} finished`;s.push({kind:"action",session:t,action:{type:"session/toolCallComplete",turnId:l.turnId,toolCallId:a.tool_use_id,result:{success:!d,pastTenseMessage:m,content:c.length>0?c:void 0}}}),e.completeToolCall(a.tool_use_id);let h=r.getSpawn(a.tool_use_id);h&&!h.background&&h.markCompleted()&&(s.push({kind:"subagent_completed",session:t,toolCallId:a.tool_use_id}),r.removeSpawn(a.tool_use_id))}return s}function uM(i){if(typeof i=="string")return[{type:"text",text:i}];if(!Array.isArray(i))return;let t=[];for(let e of i)pM(e)&&t.push({type:"text",text:e.text});return t.length>0?t:void 0}function pM(i){if(i===null||typeof i!="object")return!1;let t=i;return t.type==="text"&&typeof t.text=="string"}function fM(i,t,e,n,r,o){let s=[];if(i.subtype==="success"){let l=Object.keys(i.modelUsage)[0];s.push({kind:"action",session:t,action:{type:"session/usage",turnId:e,usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens,cacheReadTokens:i.usage.cache_read_input_tokens,...l?{model:l}:{}}}})}let a=gM(i);a!==void 0&&s.push({kind:"action",session:t,action:{type:"session/error",turnId:e,error:{errorType:i.subtype,...fs(a)}}}),n.clearPendingToolCalls(r);for(let l of o.drainForegroundSpawns())r.warn(`[claudeMapSessionEvents] turn ended with pending subagent-spawning tool_use ${l.toolUseId} (agentId=${l.agentId??"<unresolved>"}); dropping cross-message state`);return s}function gM(i){if(i.subtype==="success")return i.is_error?i.result:void 0;if(i.subtype==="error_during_execution")return i.errors?.join(`
`)}function mM(i,t,e,n,r,o,s,a){switch(i.type){case"message_start":return n.resetMessage(i.message.id),[];case"content_block_start":{let l=i.content_block;if(l.type==="text")return[{kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"markdown",id:sf(e,n,i.index,r),content:""}}}];if(l.type==="thinking")return[{kind:"action",session:t,action:{type:"session/responsePart",turnId:e,part:{kind:"reasoning",id:sf(e,n,i.index,r),content:""}}}];if(l.type==="tool_use"){let d=Ys(l.name),c=Px(l.name);n.startToolBlock(i.index,l.id,d,e);let u=!c&&Iy.has(d);o===null?u&&s.recordSpawn(l.id):s.noteInnerTool(l.id,o);let p=Yn(d),m=c?a:void 0;return[{kind:"action",session:t,action:{type:"session/toolCallStart",turnId:e,toolCallId:l.id,toolName:d,displayName:Yt(d),...m?{contributor:{kind:"client",clientId:m}}:{},...p?{_meta:p}:{}}}]}return[]}case"content_block_delta":{if(i.delta.type==="text_delta")return[{kind:"action",session:t,action:{type:"session/delta",turnId:e,partId:sf(e,n,i.index,r),content:i.delta.text}}];if(i.delta.type==="thinking_delta")return[{kind:"action",session:t,action:{type:"session/reasoning",turnId:e,partId:sf(e,n,i.index,r),content:i.delta.thinking}}];if(i.delta.type==="input_json_delta"){let l=n.getActiveToolBlock(i.index);return l?(n.appendToolBlockInputDelta(i.index,i.delta.partial_json),[{kind:"action",session:t,action:{type:"session/toolCallDelta",turnId:e,toolCallId:l.toolUseId,content:i.delta.partial_json}}]):(r.warn(`[claudeMapSessionEvents] input_json_delta for unknown content-block index ${i.index}`),[])}return[]}case"content_block_stop":{let l=n.getActiveToolBlock(i.index);if(n.finalizeToolBlock(i.index),n.endToolBlock(i.index),!l)return[];let c=n.toolCalls.lookup(l.toolUseId)?.info;if(!c)return[];let u=Yn(l.toolName);return[{kind:"action",session:t,action:{type:"session/toolCallReady",turnId:e,toolCallId:l.toolUseId,invocationMessage:c.invocationMessage,...c.toolInput!==void 0?{toolInput:c.toolInput}:{},confirmed:"not-needed",...u?{_meta:u}:{}}}]}case"message_delta":case"message_stop":return[];default:return[]}}function sf(i,t,e,n){let r=t.getCurrentMessageId();return r===void 0?(n.warn(`[claudeMapSessionEvents] content block at index ${e} arrived before message_start; using turn-scoped id`),`${i}#${e}`):`${i}#${r}#${e}`}var na=class extends T{constructor(e,n,r,o=void 0,s,a){super();this._sessionUri=e;this._subagents=r;this._logService=a;this._onDidProduceSignal=this._register(new w);this.onDidProduceSignal=this._onDidProduceSignal.event;this._mapperState=new af;this._clientId=o,this._editObserver=this._register(s.createInstance(ta,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 r=Gx(e,this._sessionUri,n,this._mapperState,this._logService,this._subagents,this._clientId);for(let o of r)this._onDidProduceSignal.fire(o)}catch(r){this._logService.warn(`[ClaudeSdkMessageRouter] mapper threw, skipping message: ${r}`)}}};na=x([C(4,ke),C(5,O)],na);var ra=class extends T{constructor(e,n,r,o,s,a,l=void 0,d,c){super();this.sessionId=e;this.sessionUri=n;this._logService=c;this._isResumed=!1;this._needsRebind=!1;this._consumerLoopRunning=!1;this._onDidProduceSignal=this._register(new w);this.onDidProduceSignal=this._onDidProduceSignal.event;this._warm=r,this._abortController=o,this._wireAbortHandler(o),this._queue=this._register(d.createInstance(ea,e,()=>this._abortController.signal,u=>this._onDidProduceSignal.fire({kind:"steering_consumed",session:this.sessionUri,id:u}))),this._router=this._register(d.createInstance(na,n,s,a,l)),this._register(this._router.onDidProduceSignal(u=>this._onDidProduceSignal.fire(u))),this._register(k(()=>this._abortController.abort())),this._register(k(()=>{Promise.resolve(this._warm[Symbol.asyncDispose]()).catch(u=>this._logService.warn(`[ClaudeSdkPipeline] WarmQuery dispose failed: ${u}`))}))}async reloadPlugins(){await(await this._ensureQueryBound()).reloadPlugins()}async snapshotResolvedCustomizations(){let e=await this._ensureQueryBound(),[n,r,o]=await Promise.all([e.supportedCommands(),e.supportedAgents(),e.mcpServerStatus()]);return{commands:n,agents:r,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,r){this._currentModel=e,this._currentEffort=n,this._currentPermissionMode=r,this._appliedModel=e,this._appliedEffort=n,this._appliedPermissionMode=r}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 K;this._query||(this._query=this._warm.query(this._queue.iterable),await this._replayCurrentConfig()),this._ensureConsumerLoop();let r={sdkMessage:e,sdkUuid:typeof e.uuid=="string"?e.uuid:n,turnId:n,deferred:new Ie};return this._queue.push(r)}injectSteering(e,n){if(this._abortController.signal.aborted){this._logService.warn(`[Claude:${this.sessionId}] injectSteering: dropped (controller aborted) id=${n}`);return}let r=this._queue.peekParent();if(!r){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:r.turnId,deferred:new Ie,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 K),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,r=new AbortController;this._abortController=r;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 K;if(r.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 K),this._query=void 0,this._needsRebind=!0,new K;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 K;n.type==="system"&&n.subtype==="init"&&!this._isResumed&&(this._isResumed=!0);let r=this._queue.peekParent()?.turnId;try{await this._router.handle(n,r)}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 K:new Error("Claude SDK stream ended without a result message")}catch(n){let r=n instanceof Error?n:new Error(String(n));if(this._query===e&&(this._queue.failAll(r),this._query=void 0,this._needsRebind=!0),!Zn(r))throw r}}};ra=x([C(7,ke),C(8,O)],ra);function hM(i,t,e){return Xs(i,t)??e}var Nr=class extends T{constructor(e,n,r,o,s,a,l,d,c,u,p,m,h,v,I,b,S){super();this.sessionId=e;this.sessionUri=n;this.workingDirectory=r;this._pendingClientToolCalls=c;this._permissionModeFallback=p;this._metadataStore=m;this._instantiationService=h;this._configurationService=v;this._sdkService=I;this._sessionDataService=b;this._logService=S;this.subagents=this._register(new Yp);this._pendingPermissions=new sn;this._pendingUserInputs=new sn;this.clientCustomizationsDiff=this._register(new Zp);this._onDidSessionProgress=this._register(new w);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidCustomizationsChange=this._register(new w);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this.project=o,this._provisionalModel=s,this._provisionalAgent=a,this.provisionalConfig=l,this.abortController=d,this.toolDiff=this._register(u),this._register(this.clientCustomizationsDiff.onDidChange(()=>this._onDidCustomizationsChange.fire()))}get pendingClientToolCalls(){return this._pendingClientToolCalls}get permissionModeFallback(){return this._permissionModeFallback}static createProvisional(e,n,r,o,s,a,l,d,c,u,p){return p.createInstance(Nr,e,n,r,o,s,a,l,new AbortController,d,new Xp,c,u)}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=Xs(this._configurationService,this.sessionUri)??this._permissionModeFallback,{mcpServers:r,allowedTools:o}=await this._buildStartupToolWiring(e.serverToolHost),s=await vy({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:this.abortController,permissionMode:n,canUseTool:e.canUseTool,isResume:e.isResume,mcpServers:r,allowedTools:o,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=${s.enableFileCheckpointing} isResume=${e.isResume}`);let a=await this._sdkService.startup({options:s});if(this.abortController.signal.aborted)throw await a[Symbol.asyncDispose](),new K;let l=this._sessionDataService.openDatabase(this.sessionUri),d;try{d=this._register(this._instantiationService.createInstance(ra,this.sessionId,this.sessionUri,a,this.abortController,l,this.subagents,this.toolDiff.model.state.get().clientId))}catch(c){throw l.dispose(),await a[Symbol.asyncDispose](),c}if(this._register(d.onDidProduceSignal(c=>this._onDidSessionProgress.fire(c))),this._pipeline=d,this._sdkBundler=this._register(this._instantiationService.createInstance(Zs,this.workingDirectory)),d.seedCurrentConfig(this._provisionalModel?.id,ly(Jl(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 K;d.attachRematerializer(async c=>{let u=Xs(this._configurationService,this.sessionUri)??this._permissionModeFallback;try{let{mcpServers:p,allowedTools:m}=await this._buildStartupToolWiring(e.serverToolHost),h=new AbortController,v=await vy({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:h,permissionMode:u,canUseTool:e.canUseTool,isResume:!0,mcpServers:p,allowedTools:m,plugins:this.clientCustomizationsDiff.consume(),agent:this._resolveAgentName(this._provisionalAgent)},e.proxyHandle,b=>this._logService.error(`[Claude SDK stderr] ${b}`),b=>this._logService.info(`[Claude] declining elicitation from MCP server (Phase 7 stub): ${b}`));return this._logService.info(`[Claude] session ${this.sessionId}: resume rebuild agent=${v.agent??"(none)"}`),{warm:await this._sdkService.startup({options:v}),abortController:h}}catch(p){throw this.toolDiff.markDirty(),this.clientCustomizationsDiff.markDirty(),p}}),e.serverToolHost?.advertise(this.sessionUri.toString()),this._onDidCustomizationsChange.fire()}async _buildStartupToolWiring(e){let n=await Nx(this.toolDiff,this._pendingClientToolCalls,this._sdkService),r=e?await Fx(e,this.sessionUri.toString(),this._sdkService):void 0;return{mcpServers:!n&&!r?void 0:{...n??{},...r?{[Qp]:r}:{}},allowedTools:e?Ux(e.toolNames):void 0}}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 r=this._requirePipeline();return this.toolDiff.hasDifference||this.clientCustomizationsDiff.hasDifference?await this._rebindForSyncedState():await r.setPermissionMode(hM(this._configurationService,this.sessionUri,this._permissionModeFallback)),r.send(e,n)}async _rebindForSyncedState(){this._pendingClientToolCalls.rejectAll(new K),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=Jl(e),r=ly(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),r!==void 0&&await this._pipeline.setEffort(r)}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:nf(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,r){return this._pendingUserInputs.respond(e,{response:n,answers:r})}setClientTools(e,n){this.toolDiff.model.setTools(e,n),this._pipeline&&this._pipeline.setClientId(this.toolDiff.model.state.get().clientId)}completeClientToolCall(e,n){let r=Wx(n,e);return this._pendingClientToolCalls.respond(e,r)}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(),r;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{r=await this._sdkBundler.bundle(o)}catch(s){this._logService.warn(`[Claude:${this.sessionId}] SDK bundle failed`,s)}}return qx(e,n,r)}dispose(){this._pendingPermissions.denyAll(!1),this._pendingUserInputs.denyAll({response:"cancel"}),this._pendingClientToolCalls.rejectAll(new K),super.dispose()}};Nr=x([C(12,ke),C(13,$e),C(14,Gs),C(15,ft),C(16,O)],Nr);function Jx(i,t){let e=typeof i.plan=="string"?i.plan:"";return{status:"pending-confirmation",toolCallId:t,toolName:"ExitPlanMode",displayName:Yt("ExitPlanMode"),invocationMessage:{markdown:e},toolInput:JSON.stringify(i),confirmationTitle:g(1958,null),options:[{id:"approve",label:g(1956,null),kind:"approve"},{id:"deny",label:g(1957,null),kind:"deny"}]}}function Yx(i){let t=i;if(t.questions?.length)return{questions:t.questions}}function Qx(i,t){return i||`q-${t}`}function Xx(i){return i.questions.map((t,e)=>{let n=t.options.map(o=>({id:o.label,label:o.label,...o.description!==void 0?{description:o.description}:{}})),r=Qx(t.header,e);return t.multiSelect?{id:r,kind:"multi-select",title:t.header,message:t.question,options:n,allowFreeformInput:t.allowFreeformInput??!1}:{id:r,kind:"single-select",title:t.header,message:t.question,options:n,allowFreeformInput:t.allowFreeformInput??!1}})}function Zx(i,t){let e={};for(let n=0;n<i.questions.length;n++){let r=i.questions[n],o=t[Qx(r.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[r.question]=s.join(", "))}return e}async function _y(i,t,e,n,r){let o=i.getSession(t);if(!o)return{behavior:"deny",message:"Session is no longer active"};if(r.signal.aborted)return{behavior:"deny",message:"SDK aborted the tool request"};let s=()=>{o.respondToPermissionRequest(r.toolUseID,!1),o.respondToUserInputRequest(r.toolUseID,"cancel")};r.signal.addEventListener("abort",s);try{return await yM(i,o,e,n,r)}finally{r.signal.removeEventListener("abort",s)}}async function yM(i,t,e,n,r){if(Cx.has(e))return vM(i,t,e,n,r);let o=jp(e),s=Yt(e),a=r.blockedPath??Jn(e,n),l=bi(e,n),d=Yn(e),c={status:"pending-confirmation",toolCallId:r.toolUseID,toolName:e,displayName:s,invocationMessage:Lr(e,s,n),toolInput:l,confirmationTitle:Tx(e),...d?{_meta:d}:{}},u=Cy(t,r);return await t.requestPermission({toolUseID:r.toolUseID,state:c,permissionKind:o,...a!==void 0?{permissionPath:a}:{},...u!==void 0?{parentToolCallId:u}:{}})?{behavior:"allow",updatedInput:n}:{behavior:"deny",message:"User declined"}}function Cy(i,t){if(!t.agentID)return;let e=i.subagents.getParentSpawn(t.toolUseID);if(e)return e.setAgentId(t.agentID),e.toolUseId}function vM(i,t,e,n,r){switch(e){case"ExitPlanMode":return SM(i,t,n,r);case"AskUserQuestion":return bM(i,t,n,r);default:return Promise.resolve({behavior:"deny",message:`Unsupported interactive tool: ${e}`})}}async function SM(i,t,e,n){let r=n.toolUseID,o=Cy(t,n);return await t.requestPermission({toolUseID:r,state:Jx(e,r),permissionKind:jp("ExitPlanMode"),...o!==void 0?{parentToolCallId:o}:{}})?(i.configurationService.updateSessionConfig(t.sessionUri.toString(),{permissionMode:"acceptEdits"}),{behavior:"allow",updatedInput:e}):{behavior:"deny",message:"The user declined the plan, maybe ask why?"}}async function bM(i,t,e,n){let r=n.toolUseID,o=Yx(e);if(!o)return{behavior:"deny",message:"AskUserQuestion called without questions"};let s=Cy(t,n),a=await t.requestUserInput({id:r,questions:Xx(o)},s);if(a.response!=="accept"||!a.answers)return{behavior:"deny",message:"The user cancelled the question"};let l=Zx(o,a.answers);return Object.keys(l).length===0?{behavior:"deny",message:"The user cancelled the question"}:{behavior:"allow",updatedInput:{...e,answers:l}}}var IM=new Map([["opus",new Set(["1m"])]]),Ty=new Map;function ia(i){let t=i.toLowerCase();if(Ty.has(t))return Ty.get(t);let e=CM(t);return Ty.set(t,e),e}var _M=/^(?<base>.*)-(?<date>\d{8})$/;function CM(i){let t="",e=i,n=_M.exec(i);n?.groups&&(e=n.groups.base,t=n.groups.date);let r=e.match(/^claude-(?<name>\w+)-(?<major>\d+)-(?<minor>\d+)(?:-(?<mod>.+))?$/);if(r?.groups)return td(r.groups.name,r.groups.major,r.groups.minor,ed(r.groups.mod,t));let o=e.match(/^claude-(?<major>\d+)-(?<minor>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(o?.groups)return td(o.groups.name,o.groups.major,o.groups.minor,ed(o.groups.mod,t));let s=e.match(/^claude-(?<name>\w+)-(?<major>\d+)\.(?<minor>\d+)(?:-(?<mod>.+))?$/);if(s?.groups)return td(s.groups.name,s.groups.major,s.groups.minor,ed(s.groups.mod,t));let a=e.match(/^claude-(?<name>\w+)-(?<major>\d+)(?:-(?<mod>.+))?$/);if(a?.groups)return td(a.groups.name,a.groups.major,void 0,ed(a.groups.mod,t));let l=e.match(/^claude-(?<major>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(l?.groups)return td(l.groups.name,l.groups.major,void 0,ed(l.groups.mod,t));let d=e.match(/^(?<name>\w+)$/);if(d?.groups)return TM(d.groups.name)}function ed(i,t){return i&&t?`${i}-${t}`:i||t}function e1(i,t,e,n,r){let o=e!==void 0?`claude-${i}-${t}${n}${e}`:`claude-${i}-${t}`;return r?`${o}-${r}`:o}function TM(i){return{name:i,version:"",modifiers:"",toSdkModelId:()=>i,toEndpointModelId:()=>i}}function td(i,t,e,n){let r=e!==void 0?`${t}.${e}`:t,o=xM(i,n);return{name:i,version:r,modifiers:n,toSdkModelId:()=>e1(i,t,e,"-",o),toEndpointModelId:()=>e1(i,t,e,".",o)}}function xM(i,t){if(!t)return"";let e=IM.get(i);if(!e)return"";if(e.has(t))return t;let n=t.split("-")[0];return e.has(n)?n:""}import{once as RM}from"events";var wM=["interleaved-thinking","context-management","advanced-tool-use"];function t1(i){let t=i.split(",").map(e=>e.trim()).filter(e=>e&&wM.some(n=>e.startsWith(n+"-")));return t.length>0?t.join(","):void 0}function xy(i,t){return{type:"error",error:{type:i,message:t},request_id:null}}function Sn(i,t,e,n){i.writeHead(t,{"Content-Type":"application/json"}),i.end(JSON.stringify(xy(e,n)))}function n1(i,t,e){i.writeHead(t,{"Content-Type":"application/json"}),i.end(JSON.stringify(e))}function r1(i){return`event: error
data: ${JSON.stringify(i)}

`}var wy=Object.freeze({valid:!1,sessionId:void 0});function i1(i,t){let e=i.authorization;if(typeof e!="string"||!e.startsWith("Bearer "))return wy;let n=e.slice(7),r=n.indexOf(".");if(r===-1)return wy;let o=n.slice(0,r),s=n.slice(r+1);return o!==t||s.length===0?wy:{valid:!0,sessionId:s}}var lf=$("claudeProxyService"),EM=new Set(["anthropic"]),PM="/v1/messages",Ii="ClaudeProxyService",o1="vscode_claude_code";function AM(){let i=new Uint8Array(32);crypto.getRandomValues(i);let t="";for(let e=0;e<i.length;e++)t+=i[e].toString(16).padStart(2,"0");return t}var oa=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(`[${Ii}] server.close error: ${e.message}`)})}}async _startServer(t){let e=AM(),n=new Set,o=(await import("http")).createServer();await new Promise((d,c)=>{let u=p=>{c(p)};o.once("error",u),o.listen(0,"127.0.0.1",()=>{o.removeListener("error",u),d()})});let s=o.address();if(!s||typeof s=="string")throw o.close(),new Error(`${Ii} failed to bind: unexpected address ${String(s)}`);let a=`http://127.0.0.1:${s.port}`;this._logService.info(`[${Ii}] listening on ${a}`);let l={server:o,baseUrl:a,nonce:e,inFlight:n,githubToken:t,refcount:0};return o.on("request",(d,c)=>{this._handleRequest(d,c,l).catch(u=>{if(this._logService.error(`[${Ii}] unhandled request error: ${nd(u)}`),c.headersSent){if(!c.writableEnded)try{c.end()}catch{}}else try{Sn(c,500,"api_error","Internal proxy error")}catch{}})}),l}async _handleRequest(t,e,n){let r=t.method??"GET",o=new URL(t.url??"/","http://127.0.0.1").pathname;if(this._logService.trace(`[${Ii}] ${r} ${o}`),r==="GET"&&o==="/"){e.writeHead(200,{"Content-Type":"text/plain"}),e.end("ok");return}if(!i1(t.headers,n.nonce).valid){Sn(e,401,"authentication_error","Invalid authentication");return}if(r==="GET"&&o==="/v1/models"){await this._handleModels(t,e,n);return}if(r==="POST"&&o==="/v1/messages"){await this._handleMessages(t,e,n);return}if(r==="POST"&&o==="/v1/messages/count_tokens"){Sn(e,501,"api_error","count_tokens not supported by CAPI");return}Sn(e,404,"not_found_error",`No route for ${r} ${o}`)}async _handleModels(t,e,n){let r=s1(t.headers),o;try{o=await this._copilotApiService.models(n.githubToken,{headers:r})}catch(l){this._writeUpstreamErrorResponse(e,l);return}let s=[];for(let l of o){if(!kM(l))continue;let d=ia(l.id),c=d?d.toSdkModelId():l.id;s.push({id:c,type:"model",display_name:l.name||c,created_at:"1970-01-01T00:00:00Z",capabilities:null,max_input_tokens:null,max_tokens:null})}let a={data:s,has_more:!1,first_id:s.length>0?s[0].id:null,last_id:s.length>0?s[s.length-1].id:null};e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(a))}async _handleMessages(t,e,n){let r;try{r=await MM(t)}catch(h){Sn(e,400,"invalid_request_error",`Failed to read request body: ${nd(h)}`);return}let o;try{o=JSON.parse(r)}catch{Sn(e,400,"invalid_request_error","Request body is not valid JSON");return}if(!o||typeof o!="object"){Sn(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){Sn(e,400,"invalid_request_error","Missing required field: model");return}if(!Array.isArray(s.messages)){Sn(e,400,"invalid_request_error","Missing required field: messages");return}let l=ia(a);if(!l){Sn(e,404,"not_found_error",`Unknown model: ${a}`);return}let d=l.toEndpointModelId();s.model=d;let c=s.stream===!0,u=s1(t.headers),p={ac:new AbortController,res:e,clientGone:!1};n.inFlight.add(p);let m=()=>{p.clientGone=!0,p.ac.abort()};e.on("close",m);try{c?await this._streamMessages(s,u,e,p,n,a):await this._sendNonStreamingMessage(s,u,e,p,n,a)}finally{e.removeListener("close",m),n.inFlight.delete(p)}}async _sendNonStreamingMessage(t,e,n,r,o,s){let a={headers:e,signal:r.ac.signal,suppressIntegrationId:!0},l;try{l=await this._copilotApiService.messages(o.githubToken,t,a)}catch(u){if(r.ac.signal.aborted){!r.clientGone&&!n.writableEnded&&n.destroy();return}this._writeUpstreamErrorResponse(n,u,!0);return}let d=l1(l.model,this._logService)??s,c={...l,model:d};n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(c))}async _streamMessages(t,e,n,r,o,s){let a={headers:e,signal:r.ac.signal,suppressIntegrationId:!0},l;try{l=this._copilotApiService.messages(o.githubToken,t,a)}catch(u){if(r.ac.signal.aborted){!r.clientGone&&!n.writableEnded&&n.destroy();return}this._writeUpstreamErrorResponse(n,u,!0);return}let d;try{d=await l.next()}catch(u){if(r.ac.signal.aborted){!r.clientGone&&!n.writableEnded&&n.destroy();return}this._writeUpstreamErrorResponse(n,u,!0);return}n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),n.flushHeaders(),LM(n);let c=async u=>{let p=DM(u,this._logService),m=`event: ${p.type}
data: ${JSON.stringify(p)}

`;if(!n.write(m))try{await RM(n,"drain",{signal:r.ac.signal})}catch{return!1}return!0};try{if(!d.done&&!await c(d.value))return;for(;;){let u;try{u=await l.next()}catch(m){if(r.ac.signal.aborted){!r.clientGone&&!n.writableEnded&&n.destroy();return}let h=m instanceof Pn?a1(m):xy("api_error",nd(m));if(!n.writableEnded){try{n.write(r1(h))}catch{}try{n.end()}catch{}}return}if(u.done)break;if(!await c(u.value))return}n.writableEnded||n.end()}catch(u){if(this._logService.warn(`[${Ii}] stream loop unexpected error: ${nd(u)}`),!n.writableEnded)try{n.end()}catch{}}}_writeUpstreamErrorResponse(t,e,n=!1){if(t.headersSent){if(this._logService.warn(`[${Ii}] cannot write upstream error after headers sent: ${nd(e)}`),!t.writableEnded)try{t.end()}catch{}return}if(e instanceof Pn){let r=e.status===Tl?502:e.status;n1(t,r,n?a1(e):e.envelope);return}Sn(t,502,"api_error",e instanceof Error?e.message:String(e))}};oa=x([C(0,O),C(1,Kt)],oa);function kM(i){return EM.has(i.vendor.toLowerCase())?Array.isArray(i.supported_endpoints)&&i.supported_endpoints.includes(PM):!1}function l1(i,t){let e=ia(i);if(!e){t.warn(`[${Ii}] outbound model ID could not be parsed for SDK rewrite: ${i}`);return}return e.toSdkModelId()}function DM(i,t){if(i.type!=="message_start")return i;let e=l1(i.message.model,t);return e===void 0||e===i.message.model?i:{...i,message:{...i.message,model:e}}}function s1(i){let t={},e=i["anthropic-version"];typeof e=="string"&&e.length>0&&(t["anthropic-version"]=e);let n=i["anthropic-beta"];if(typeof n=="string"&&n.length>0){let o=t1(n);o!==void 0&&(t["anthropic-beta"]=o)}let r=i["user-agent"];return typeof r=="string"&&r.length>0&&(t["User-Agent"]=OM(r)),t}function OM(i){let t=i.indexOf("/");return t===-1?`${o1}/${i}`:`${o1}${i.substring(t)}`}function MM(i){return new Promise((t,e)=>{let n=[];i.on("data",r=>n.push(Buffer.isBuffer(r)?r:Buffer.from(r))),i.on("end",()=>t(Buffer.concat(n).toString("utf8"))),i.on("error",e)})}function LM(i){let t=i.socket;if(t&&typeof t.setNoDelay=="function")try{t.setNoDelay(!0)}catch{}}function nd(i){return i instanceof Error?i.message:String(i)}function a1(i){let t=fu(pu(i));return{...i.envelope,error:{...i.envelope.error,message:`${i.envelope.error.message} ${t}`}}}var Dt=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),r=n.object;try{let o=[];e.customizationDirectory&&o.push(r.setMetadata(Dt.KEY_CUSTOMIZATION_DIRECTORY,e.customizationDirectory.toString())),e.model&&o.push(r.setMetadata(Dt.KEY_MODEL,UM(e.model))),e.permissionMode&&o.push(r.setMetadata(Dt.KEY_PERMISSION_MODE,e.permissionMode)),e.agent!==void 0&&o.push(r.setMetadata(Dt.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,r,o,s]=await Promise.all([e.object.getMetadata(Dt.KEY_CUSTOMIZATION_DIRECTORY),e.object.getMetadata(Dt.KEY_MODEL),e.object.getMetadata(Dt.KEY_PERMISSION_MODE),e.object.getMetadata(Dt.KEY_AGENT)]);return{customizationDirectory:n?y.parse(n):void 0,model:FM(r),permissionMode:Vs(o),agent:NM(s)}}finally{e.dispose()}}project(t,e){return{session:F.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}}};Dt=x([C(1,ft)],Dt);function NM(i){if(i)try{let t=JSON.parse(i);if(t&&typeof t=="object"&&typeof t.uri=="string")return{uri:t.uri}}catch{}}function UM(i){return JSON.stringify(i)}function FM(i){if(i){try{let t=JSON.parse(i);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[r,o]of Object.entries(t.config))typeof o=="string"&&(n[r]=o);Object.keys(n).length>0&&(e.config=n)}return e}}catch{}return{id:i}}}var WM="vscode_claude_code";function $M(i){return i.vendor==="Anthropic"&&!!i.supported_endpoints?.includes("/v1/messages")&&!!i.model_picker_enabled&&!!i.capabilities?.supports?.tool_calls&&ia(i.id)!==void 0}function HM(i,t){let e=i.capabilities?.supports,n=(e?.reasoning_effort??[]).filter(gx),r=mx(n),o=i.policy?.state,s=i.billing?.multiplier;return{provider:t,id:i.id,name:i.name,maxContextWindow:i.capabilities?.limits?.max_context_window_tokens,supportsVision:!!e?.vision,...r?{configSchema:r}:{},...o?{policyState:o}:{},...typeof s=="number"?{_meta:{multiplierNumeric:s}}:{}}}var sa=class extends T{constructor(e,n,r,o,s,a,l,d,c){super();this._logService=e;this._copilotApiService=n;this._claudeProxyService=r;this._sdkService=o;this._gitService=s;this._configurationService=a;this._instantiationService=l;this._pluginManager=d;this._productService=c;this.id="claude";this._onDidSessionProgress=this._register(new w);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidCustomizationsChange=this._register(new w);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this._models=pn(this,[]);this.models=this._models;this._sessions=this._register(new ve);this._onDidMaterializeSession=this._register(new w);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._disposeSequencer=new nt;this._sessionSequencer=new nt;this._metadataStore=l.createInstance(Dt,this.id)}_findAnySession(e){return this._sessions.get(e)?.session}getDescriptor(){return{provider:this.id,displayName:g(1955,null),description:g(1954,null)}}getProtectedResources(){return[St]}_ensureAuthenticated(){let e=this._proxyHandle;if(!e)throw new D(on,"Authentication is required to use Claude",this.getProtectedResources());return e}async authenticate(e,n){if(e!==St.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=`${WM}/${this._productService.version}`,r=await this._copilotApiService.models(e,{headers:{"User-Agent":n}});if(this._githubToken!==e)return;let o=r.filter($M).sort((s,a)=>Number(a.is_chat_default)-Number(s.is_chat_default)).map(s=>HM(s,this.id));this._logService.info(`[Claude] Models refreshed. Count: ${o.length}`),this._models.set(o,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?F.id(e.session):N(),r=F.uri(this.id,n),o=this._findAnySession(n);if(o)return o.isPipelineReady?{session:r,workingDirectory:e.workingDirectory}:{session:o.sessionUri,workingDirectory:o.workingDirectory,provisional:!0,...o.project?{project:o.project}:{}};let s=e.workingDirectory?await Mr({cwd:e.workingDirectory.fsPath},this._gitService):void 0,a=this._resolvePermissionMode(e.config),l=Nr.createProvisional(n,r,e.workingDirectory,s,e.model,e.agent,e.config,new sn,a,this._metadataStore,this._instantiationService),d=new df(l);return d.addDisposable(l.onDidSessionProgress(c=>this._onDidSessionProgress.fire(c))),d.addDisposable(l.onDidCustomizationsChange(()=>this._onDidCustomizationsChange.fire())),this._sessions.set(n,d),{session:r,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 r=this._ensureAuthenticated(),o=(s,a,l)=>_y({getSession:d=>this._findAnySession(d),configurationService:this._configurationService},e,s,a,l);try{await n.materialize({proxyHandle:r,canUseTool:o,isResume:!1,serverToolHost:this._serverToolHost})}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 r=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=Xs(this._configurationService,n)??a.permissionMode??"default",d;try{d=await Mr({cwd:s.fsPath},this._gitService)}catch(m){this._logService.warn(`[Claude:${e}] project resolution failed during resume; continuing without project`,m)}let c=Nr.createProvisional(e,n,s,d,a.model,a.agent,void 0,new sn,l,this._metadataStore,this._instantiationService),u=new df(c);u.addDisposable(c.onDidSessionProgress(m=>this._onDidSessionProgress.fire(m))),u.addDisposable(c.onDidCustomizationsChange(()=>this._onDidCustomizationsChange.fire())),this._sessions.set(e,u);let p=(m,h,v)=>_y({getSession:I=>this._findAnySession(I),configurationService:this._configurationService},e,m,h,v);try{await c.materialize({proxyHandle:r,canUseTool:p,isResume:!0,serverToolHost:this._serverToolHost})}catch(m){throw this._sessions.deleteAndDispose(e),m}return this._onDidMaterializeSession.fire({session:n,workingDirectory:s,project:d}),c}_resolvePermissionMode(e){return Vs(e?.permissionMode)??"default"}disposeSession(e){let n=F.id(e);return this._disposeSequencer.queue(n,async()=>{let r=this._findAnySession(n);r&&!r.isPipelineReady&&r.abortController.abort(),this._sessions.deleteAndDispose(n)})}getSessionForTesting(e){let n=this._sessions.get(F.id(e))?.session;return n?.isPipelineReady?n:void 0}async getSessionMessages(e){let n=F.id(e),r=this._findAnySession(n);if(r&&!r.isPipelineReady)return[];if(Xo(e)){let l=Xe(e),d=l?this._sessions.get(F.id(l.parentSession))?.session:void 0;if(!d)return this._logService.warn(`[Claude] getSessionMessages: parent session not found for subagent ${e.toString()} (registry unavailable)`),[];try{return await Lx(e,d.subagents,this._sdkService,this._logService,Ee.None)}catch(c){return this._logService.warn(`[Claude] getSubagentTranscript threw for ${e.toString()}`,c),[]}}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=Xl(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 r=F.uri(this.id,n.sessionId),o=await this._metadataStore.read(r);return this._metadataStore.project(n,o)}catch(r){this._logService.warn(`[Claude] Overlay read failed for session ${n.sessionId}`,r)}return this._metadataStore.project(n,{})}))}async getSessionMetadata(e){let n=F.id(e),r=await this._sdkService.getSessionInfo(n);if(!r)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(r,o)}resolveSessionConfig(e){let n=zt({permissionMode:Ve({type:"string",title:g(1940,null),description:g(1953,null),enum:["default","acceptEdits","bypassPermissions","plan","dontAsk","auto"],enumLabels:[g(1947,null),g(1941,null),g(1945,null),g(1951,null),g(1949,null),g(1943,null)],enumDescriptions:[g(1948,null),g(1942,null),g(1946,null),g(1952,null),g(1950,null),g(1944,null)],default:"default",sessionMutable:!0}),permissions:It.definition.permissions}),r=n.validateOrDefault(e.config,{permissionMode:"default"});return Promise.resolve({schema:n.toProtocol(),values:r})}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,r,o){let s=F.id(e),a=o??N();return this._sessionSequencer.queue(s,async()=>{let l=this._findAnySession(s),d;l?.isPipelineReady?d=l:l?d=await this._materializeProvisional(s):d=await this._resumeSession(s,e);let u={type:"user",message:{role:"user",content:nf(n,r)},session_id:s,parent_tool_use_id:null,uuid:a};await d.send(u,a)})}respondToPermissionRequest(e,n){for(let r of this._sessions.values())if(r.session.respondToPermissionRequest(e,n))return}respondToUserInputRequest(e,n,r){for(let o of this._sessions.values())if(o.session.respondToUserInputRequest(e,n,r))return}async abortSession(e){let n=F.id(e),r=this._findAnySession(n);if(r){if(!r.isPipelineReady){r.abortController.abort();return}r.abort()}}setPendingMessages(e,n,r){let o=F.id(e);this._logService.info(`[Claude:${o}] setPendingMessages called: steering=${n?.id??"none"} queued=${r.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 r=F.id(e);await this._sessionSequencer.queue(r,async()=>{let o=this._findAnySession(r);o?await o.setModel(n):await this._metadataStore.write(e,{model:n})})}async changeAgent(e,n){let r=F.id(e);await this._sessionSequencer.queue(r,async()=>{let o=this._findAnySession(r);o?await o.setAgent(n):await this._metadataStore.write(e,{agent:n??null})})}setServerToolHost(e){this._serverToolHost=e}setClientTools(e,n,r){let o=F.id(e);this._logService.info(`[Claude:${o}] setClientTools clientId=${n} tools=[${r.map(a=>a.name).join(", ")||"(none)"}]`);let s=this._findAnySession(o);s&&s.setClientTools(r,n)}onClientToolCallComplete(e,n,r){let o=e,s;for(;s=Xe(o);)o=s.parentSession;let a=F.id(o);this._sessions.get(a)?.session.completeClientToolCall(n,r)}async setClientCustomizations(e,n,r){let o=F.id(e),s=this._findAnySession(o);return s?this._sessionSequencer.queue(o,async()=>{let a=await this._pluginManager.syncCustomizations(n,r,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 r of this._sessions.values())r.session.setClientCustomizationEnabled(e,n)}getCustomizations(){return[]}async getSessionCustomizations(e){let n=this._findAnySession(F.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)}};sa=x([C(0,O),C(1,Kt),C(2,lf),C(3,Gs),C(4,tt),C(5,$e),C(6,ke),C(7,yi),C(8,gt)],sa);var df=class extends T{constructor(t){super(),this.session=this._register(t)}addDisposable(t){this._register(t)}};import{spawn as eL}from"child_process";import*as Ci from"fs";var _i=class extends Error{constructor(e,n,r){super(n);this.code=e;this.data=r;this.name="JsonRpcError"}},qM=2e3,cf=class extends T{constructor(e,n,r=qM){super();this._transport=e;this._onLog=n;this._graceKillMs=r;this._onExit=this._register(new w);this.onExit=this._onExit.event;this._onTransportError=this._register(new w);this.onTransportError=this._onTransportError.event;this._nextId=1;this._pending=new Map;this._notificationHandlers=new Map;this._requestHandlers=new Map;this._exited=!1;this._disposed=!1;this._buf="";this._register(this._transport.onExit(o=>this._handleExit(o))),this._transport.stdout.setEncoding?.("utf8"),this._register(this._listenToStdout())}_listenToStdout(){let e=n=>{let r=typeof n=="string"?n:n.toString("utf8");this._buf+=r;let o;for(;(o=this._buf.indexOf(`
`))>=0;){let s=this._buf.slice(0,o);this._buf=this._buf.slice(o+1);let a=s.trim();if(a.length===0)continue;let l;try{l=JSON.parse(a)}catch{this._log("error",`parse error on line: ${a.slice(0,200)}`);continue}this._dispatch(l)}};return this._transport.stdout.on("data",e),k(()=>this._transport.stdout.off("data",e))}_dispatch(e){let n=ye(e,{id:!0}),r=ye(e,{method:!0});if(n&&!r&&(ye(e,{result:!0})||ye(e,{error:!0}))){if(typeof e.id!="number"){this._log("warn",`unsolicited response id=${e.id}`);return}let o=e.id,s=this._pending.get(o);if(!s){this._log("warn",`unsolicited response id=${e.id}`);return}this._pending.delete(o),ye(e,{error:!0})&&e.error?s.reject(new _i(e.error.code,e.error.message,e.error.data)):s.resolve(e.result);return}if(r&&n&&e.id!==void 0&&e.method!==void 0){this._handleServerRequest(e);return}if(r&&e.method!==void 0){this._handleServerNotification(e);return}this._log("warn",`unrecognized message: ${JSON.stringify(e).slice(0,200)}`)}async _handleServerRequest(e){let n=this._requestHandlers.get(e.method);if(!n){this._writeMessage({id:e.id,error:{code:-32601,message:`Method not found: ${e.method}`}});return}try{let r=await n(e.params);r.error?this._writeMessage({id:e.id,error:r.error}):this._writeMessage({id:e.id,result:r.result})}catch(r){let o=r instanceof Error?r.message:String(r);this._log("error",`handler for ${e.method} threw: ${o}`),this._writeMessage({id:e.id,error:{code:-32603,message:o}})}}_handleServerNotification(e){let n=this._notificationHandlers.get(e.method);if(!n){this._log("warn",`dropping unhandled notification: ${e.method}`);return}try{n(e.params)}catch(r){this._log("error",`notification handler ${e.method} threw: ${r instanceof Error?r.message:String(r)}`)}}_writeMessage(e){if(this._exited||this._disposed)return!1;try{return this._transport.stdin.write(JSON.stringify(e)+`
`),!0}catch(n){return this._onTransportError.fire(n instanceof Error?n:new Error(String(n))),!1}}_handleExit(e){if(this._exited)return;this._exited=!0;let n=`codex app-server exited (code=${e.code}, signal=${e.signal})`;for(let[r,o]of this._pending)o.reject(new _i(-32603,`${n}; request id=${r} (${o.method}) aborted`));this._pending.clear(),this._onExit.fire(e)}request(e,n){if(this._disposed)return Promise.reject(new K);if(this._exited)return Promise.reject(new _i(-32603,"transport has exited"));let r=this._nextId++;return new Promise((o,s)=>{this._pending.set(r,{method:e,resolve:o,reject:s}),this._writeMessage({id:r,method:e,params:n})||(this._pending.delete(r),s(new _i(-32603,"write failed; transport closed")))})}notify(e,n){let r={method:e};n!==void 0&&(r.params=n),this._writeMessage(r)}onNotification(e,n){return this._notificationHandlers.set(e,n),k(()=>{this._notificationHandlers.get(e)===n&&this._notificationHandlers.delete(e)})}onRequest(e,n){let r=async o=>await n(o);return this._requestHandlers.set(e,r),k(()=>{this._requestHandlers.get(e)===r&&this._requestHandlers.delete(e)})}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._pending.values())e.reject(new K);this._pending.clear();try{this._transport.stdin.end()}catch{}if(!this._exited){let e=setTimeout(()=>{try{this._transport.kill("SIGKILL")}catch{}},this._graceKillMs);this._transport.onExitOnce(()=>{clearTimeout(e)}),e.unref?.()}super.dispose()}}_log(e,n){this._onLog?.(e,n)}};function d1(i){if(!i.stdin||!i.stdout)throw new Error("Child process has no stdio pair");return{stdin:i.stdin,stdout:i.stdout,kill:t=>i.kill(t),onExit:Q.fromNodeEventEmitter(i,"exit",(t,e)=>({code:t,signal:e})),onExitOnce:t=>i.once("exit",(e,n)=>t({code:e,signal:n}))}}import*as da from"fs";var uf=$("codexProxyService"),it="CodexProxyService",BM="VSCODE_CODEX_PROXY_DUMP_DIR",VM=0;function zM(){return String(++VM).padStart(4,"0")}function jM(){let i=process.env[BM];if(i)try{return da.mkdirSync(i,{recursive:!0}),i}catch{return}}function KM(){let i=new Uint8Array(32);crypto.getRandomValues(i);let t="";for(let e=0;e<i.length;e++)t+=i[e].toString(16).padStart(2,"0");return t}function aa(i,t,e,n){i.headersSent||i.writableEnded||(i.writeHead(t,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:{type:e,message:n}})))}function GM(i){return new Promise((t,e)=>{let n=[];i.on("data",r=>n.push(r)),i.on("end",()=>t(Buffer.concat(n).toString("utf8"))),i.on("error",e)})}var la=class{constructor(t,e){this._logService=t;this._copilotApiService=e;this._disposed=!1}async start(t){if(this._disposed)throw new Error("CodexProxyService has been disposed");let e=await this._ensureRuntime(t);if(this._disposed||this._runtime!==e)throw new Error("CodexProxyService has been disposed");e.githubToken=t,e.refcount++;let n=!1;return{baseUrl:e.baseUrl,nonce:e.nonce,setToken:r=>{n||(e.githubToken=r)},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("CodexProxyService 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(`[${it}] server.close error: ${e.message}`)})}}async _startServer(t){let e=KM(),n=new Set,o=(await import("http")).createServer();await new Promise((d,c)=>{let u=p=>c(p);o.once("error",u),o.listen(0,"127.0.0.1",()=>{o.removeListener("error",u),d()})});let s=o.address();if(!s||typeof s=="string")throw o.close(),new Error(`${it} failed to bind: unexpected address ${String(s)}`);let a=`http://127.0.0.1:${s.port}`;this._logService.info(`[${it}] listening on ${a}`);let l={server:o,baseUrl:a,nonce:e,inFlight:n,githubToken:t,refcount:0};return o.on("request",(d,c)=>{this._handleRequest(d,c,l).catch(u=>{if(this._logService.error(`[${it}] unhandled request error`,u),c.headersSent){if(!c.writableEnded)try{c.end()}catch{}}else try{aa(c,500,"api_error","Internal proxy error")}catch{}})}),l}async _handleRequest(t,e,n){let r=t.method??"GET",o=new URL(t.url??"/","http://127.0.0.1").pathname,s=Object.keys(t.headers).join(", ");if(this._logService.info(`[${it}] >>> ${r} ${o} (headers: ${s})`),r==="GET"&&o==="/"){e.writeHead(200,{"Content-Type":"text/plain"}),e.end("ok");return}let a=t.headers.authorization,l=`Bearer ${n.nonce}`;if(typeof a!="string"||a!==l){aa(e,401,"authentication_error","Invalid authentication");return}if(r==="POST"&&(o==="/v1/responses"||o==="/responses"||o==="//responses")){await this._handleResponses(t,e,n);return}aa(e,404,"not_found_error",`No route for ${r} ${o}`)}async _handleResponses(t,e,n){let r;try{r=await GM(t)}catch(c){aa(e,400,"invalid_request_error",`Failed to read request body: ${c instanceof Error?c.message:String(c)}`);return}let o=jM(),s=o?zM():void 0;if(o&&s){let c=W(o,`req-${s}-${Date.now()}.json`);try{da.writeFileSync(c,r),this._logService.info(`[${it}] dumped request body to ${c}`)}catch(u){this._logService.warn(`[${it}] failed to dump request body: ${u instanceof Error?u.message:String(u)}`)}}try{let c=JSON.parse(r);if(this._logService.info(`[${it}] >>> /responses body: model=${c.model??"<none>"}, previous_response_id=${c.previous_response_id??"<none>"}, stream=${c.stream??"<none>"}, input_items=${Array.isArray(c.input)?c.input.length:"<not-array>"}`),Array.isArray(c.input))for(let p=0;p<c.input.length;p++){let m=c.input[p],h=m?.type??"<none>",v=m&&typeof m=="object"?Object.keys(m).join(","):typeof m,I="";if(h==="message"){let b=m?.content?.[0]?.text??"";I=`role=${m?.role??"?"} chars=${b.length}`}else if(h==="function_call")I=`name=${m?.name??"?"} call_id=${m?.call_id??"?"}`;else if(h==="function_call_output"){let b=m?.output??"";I=`call_id=${m?.call_id??"?"} output_chars=${typeof b=="string"?b.length:0}`}else if(h==="reasoning"){let b=m?.summary??m?.content??"";I=`summary_chars=${typeof b=="string"?b.length:JSON.stringify(b).length} encrypted=${typeof m?.encrypted_content=="string"}`}else I=JSON.stringify(m).slice(0,120);this._logService.info(`[${it}]   input[${p}] type=${h} keys=[${v}] ${I}`)}let u=Object.keys(c).filter(p=>p!=="input").sort();this._logService.info(`[${it}]   top-level keys (excl. input)=[${u.join(", ")}]`);for(let p of u){if(p==="instructions"||p==="tools"){let v=c[p],I=typeof v=="string"?v.length:JSON.stringify(v).length;this._logService.info(`[${it}]     ${p}=<${I} chars elided>`);continue}let m=c[p],h=typeof m=="object"?JSON.stringify(m).slice(0,300):String(m);this._logService.info(`[${it}]     ${p}=${h}`)}}catch{this._logService.info(`[${it}] >>> /responses body (unparseable): ${r.slice(0,200)}`)}let a={ac:new AbortController,res:e,clientGone:!1};n.inFlight.add(a);let l=()=>{a.clientGone=!0,a.ac.abort()};e.on("close",l);let d=n.githubToken;try{this._logService.info(`[${it}] forwarding to CAPI responses...`);let c=await this._copilotApiService.responses(d,r,{signal:a.ac.signal,suppressIntegrationId:!0}),u=c.headers.get("content-type")??"application/json",p=[...c.headers.entries()].map(([b,S])=>`${b}: ${S}`).join(", ");if(this._logService.info(`[${it}] <<< CAPI response: status=${c.status}, contentType=${u}, headers=[${p}]`),e.writeHead(c.status,{"Content-Type":u}),!c.body){e.end();return}let m=c.body.getReader(),h=o&&s?da.createWriteStream(W(o,`res-${s}-${Date.now()}.txt`)):void 0,v="",I={};try{for(;;){let{done:b,value:S}=await m.read();if(b||a.clientGone)break;if(S&&S.byteLength>0){let _=Buffer.from(S);e.write(_),h&&h.write(_),v+=_.toString("utf8");let R;for(;(R=v.indexOf(`
`))>=0;){let P=v.slice(0,R).trimEnd();if(v=v.slice(R+1),P.startsWith("event:")){let q=P.slice(6).trim();I[q]=(I[q]??0)+1}}}}}finally{try{m.releaseLock()}catch{}h?.end()}if(Object.keys(I).length){let b=Object.entries(I).map(([S,_])=>`${S}=${_}`).join(", ");this._logService.info(`[${it}] <<< SSE event counts: ${b}`)}e.end()}catch(c){if(a.clientGone){this._logService.info(`[${it}] client disconnected during upstream call`);return}if(c instanceof Pn){this._logService.error(`[${it}] CAPI error: status=${c.status}, message=${c.message}`);let u=fu(pu(c));aa(e,c.status,"api_error",`${c.message} ${u}`);return}this._logService.error(`[${it}] upstream error: ${c instanceof Error?c.message:String(c)}`),aa(e,502,"api_error",c instanceof Error?c.message:String(c))}finally{e.removeListener("close",l),n.inFlight.delete(a)}}};la=x([C(0,O),C(1,Kt)],la);function Ry(){return{itemToPartId:new Map,itemToToolCall:new Map,itemToReasoningPartId:new Map,currentTurnId:void 0}}function Ey(i,t,e){return`${i}:${t}:${e}`}function Py(i,t,e){let n=i.itemToReasoningPartId.get(e);if(n)return{partId:n,actions:[]};let r=N();return i.itemToReasoningPartId.set(e,r),{partId:r,actions:[{type:"session/responsePart",turnId:t,part:{kind:"reasoning",id:r,content:""}}]}}function p1(i,t){return t?.type==="search"?t.queries?.join(", ")??t.query??i:t?.type==="openPage"?t.url??i:t?.type==="findInPage"&&[t.pattern,t.url].filter(Boolean).join(" in ")||i}function f1(i){return i.map(t=>`${t.kind.type==="update"&&t.kind.move_path?`rename from ${t.kind.move_path}`:t.kind.type}: ${t.path}`).join(`
`)}function Ay(i){return i.map(t=>`${f1([t])}
${t.diff}`.trim()).join(`

`)}function c1(i){return typeof i=="string"?i:JSON.stringify(i,null,2)}function u1(i){return JSON.stringify(i,null,2)}function g1(i){return i?.map(t=>t.type==="inputText"?t.text:t.imageUrl).join(`
`)??""}function JM(i,t){if(t)return t;if(!i)return"";let e=i.content.map(c1).join(`
`),n=i.structuredContent!==null?c1(i.structuredContent):"";return[e,n].filter(Boolean).join(`
`)}function m1(i,t,e){i.currentTurnId=t.turn.id,i.itemToPartId.clear(),i.itemToToolCall.clear(),i.itemToReasoningPartId.clear();let n=e,r=t.turn.items?.[0];if(r&&r.type==="userMessage"){let o=[];for(let s of r.content)s.type==="text"&&o.push(s.text);o.length>0&&(n=o.join(`

`))}return[{type:"session/turnStarted",turnId:t.turn.id,message:{text:n,origin:{kind:"user"}}}]}function h1(i,t){return Py(i,t.turnId,Ey(t.itemId,"summary",t.summaryIndex)).actions}function y1(i,t){let e=Py(i,t.turnId,Ey(t.itemId,"summary",t.summaryIndex));return[...e.actions,{type:"session/reasoning",turnId:t.turnId,partId:e.partId,content:t.delta}]}function v1(i,t){let e=Py(i,t.turnId,Ey(t.itemId,"text",t.contentIndex));return[...e.actions,{type:"session/reasoning",turnId:t.turnId,partId:e.partId,content:t.delta}]}function YM(i,t){for(let e of[...i.itemToReasoningPartId.keys()])e.startsWith(`${t}:`)&&i.itemToReasoningPartId.delete(e)}function S1(i){let t=i.tokenUsage.last;return[{type:"session/usage",turnId:i.turnId,usage:{inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheReadTokens:t.cachedInputTokens,_meta:{reasoningOutputTokens:t.reasoningOutputTokens,modelContextWindow:i.tokenUsage.modelContextWindow}}}]}function b1(i,t){if(t.item.type==="agentMessage"){let e=N();return i.itemToPartId.set(t.item.id,e),[{type:"session/responsePart",turnId:t.turnId,part:{kind:"markdown",id:e,content:t.item.text??""}}]}if(t.item.type==="commandExecution"){let e=N();i.itemToToolCall.set(t.item.id,{toolCallId:e,turnId:t.turnId,toolName:"shell",output:""});let n=t.item.command??"";return[{type:"session/toolCallStart",turnId:t.turnId,toolCallId:e,toolName:"shell",displayName:"Run shell command",_meta:{toolKind:"terminal"}},{type:"session/toolCallDelta",turnId:t.turnId,toolCallId:e,content:n},{type:"session/toolCallReady",turnId:t.turnId,toolCallId:e,invocationMessage:n,toolInput:n,confirmed:"not-needed",_meta:{toolKind:"terminal"}}]}if(t.item.type==="webSearch"){let e=N();i.itemToToolCall.set(t.item.id,{toolCallId:e,turnId:t.turnId,toolName:"web_search",output:""});let n=p1(t.item.query,t.item.action);return[{type:"session/toolCallStart",turnId:t.turnId,toolCallId:e,toolName:"web_search",displayName:"Web search",_meta:{toolKind:"search"}},{type:"session/toolCallDelta",turnId:t.turnId,toolCallId:e,content:n},{type:"session/toolCallReady",turnId:t.turnId,toolCallId:e,invocationMessage:n,toolInput:n,confirmed:"not-needed",_meta:{toolKind:"search"}}]}if(t.item.type==="fileChange"){let e=N(),n=Ay(t.item.changes);i.itemToToolCall.set(t.item.id,{toolCallId:e,turnId:t.turnId,toolName:"file_edit",output:n});let r=f1(t.item.changes)||"Apply file changes";return[{type:"session/toolCallStart",turnId:t.turnId,toolCallId:e,toolName:"file_edit",displayName:"Apply file changes"},{type:"session/toolCallDelta",turnId:t.turnId,toolCallId:e,content:r},{type:"session/toolCallReady",turnId:t.turnId,toolCallId:e,invocationMessage:r,toolInput:r,confirmed:"not-needed"},...n?[{type:"session/toolCallContentChanged",turnId:t.turnId,toolCallId:e,content:[{type:"text",text:n}]}]:[]]}if(t.item.type==="mcpToolCall"){let e=N(),n=`${t.item.server}.${t.item.tool}`,r=u1(t.item.arguments);return i.itemToToolCall.set(t.item.id,{toolCallId:e,turnId:t.turnId,toolName:n,output:""}),[{type:"session/toolCallStart",turnId:t.turnId,toolCallId:e,toolName:n,displayName:t.item.tool},{type:"session/toolCallDelta",turnId:t.turnId,toolCallId:e,content:r},{type:"session/toolCallReady",turnId:t.turnId,toolCallId:e,invocationMessage:`Calling ${n}`,toolInput:r,confirmed:"not-needed"}]}if(t.item.type==="dynamicToolCall"){let e=N(),n=t.item.namespace?`${t.item.namespace}.${t.item.tool}`:t.item.tool,r=u1(t.item.arguments),o=g1(t.item.contentItems);return i.itemToToolCall.set(t.item.id,{toolCallId:e,turnId:t.turnId,toolName:n,output:o}),[{type:"session/toolCallStart",turnId:t.turnId,toolCallId:e,toolName:n,displayName:t.item.tool},{type:"session/toolCallDelta",turnId:t.turnId,toolCallId:e,content:r},{type:"session/toolCallReady",turnId:t.turnId,toolCallId:e,invocationMessage:`Calling ${n}`,toolInput:r,confirmed:"not-needed"},...o?[{type:"session/toolCallContentChanged",turnId:t.turnId,toolCallId:e,content:[{type:"text",text:o}]}]:[]]}return[]}function I1(i,t){let e=i.itemToToolCall.get(t.itemId);return e?(e.output+=t.delta,[{type:"session/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:[{type:"text",text:e.output}]}]):[]}function _1(i,t){let e=i.itemToToolCall.get(t.itemId);return e?(e.output=Ay(t.changes),[{type:"session/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:e.output?[{type:"text",text:e.output}]:[]}]):[]}function C1(i,t){let e=i.itemToToolCall.get(t.itemId);return e?(e.output+=t.delta,[{type:"session/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:[{type:"text",text:e.output}]}]):[]}function T1(i,t){let e=i.itemToToolCall.get(t.itemId);return e?(e.output=[e.output,t.message].filter(Boolean).join(`
`),[{type:"session/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:[{type:"text",text:e.output}]}]):[]}function x1(i,t){let e=i.itemToPartId.get(t.itemId);return e?[{type:"session/delta",turnId:t.turnId,partId:e,content:t.delta}]:[]}function w1(i,t){if(t.item.type==="agentMessage")return i.itemToPartId.delete(t.item.id),[];if(t.item.type==="reasoning")return YM(i,t.item.id),[];if(t.item.type==="commandExecution"){let e=i.itemToToolCall.get(t.item.id);if(!e)return[];i.itemToToolCall.delete(t.item.id);let n=t.item.status==="completed"&&(t.item.exitCode===0||t.item.exitCode===null),r=t.item.aggregatedOutput??e.output,o=t.item.command??"",s=t.item.exitCode,a=n?`Ran \`${o}\``:s!==null?`Ran \`${o}\` (exit ${s})`:`Ran \`${o}\` (failed)`;return[{type:"session/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:n,pastTenseMessage:a,content:r?[{type:"text",text:r}]:void 0,error:n?void 0:{message:s!==null?`Exit code ${s}`:"Command failed"}}}]}if(t.item.type==="webSearch"){let e=i.itemToToolCall.get(t.item.id);if(!e)return[];i.itemToToolCall.delete(t.item.id);let n=p1(t.item.query,t.item.action);return[{type:"session/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:!0,pastTenseMessage:`Searched ${n}`}}]}if(t.item.type==="fileChange"){let e=i.itemToToolCall.get(t.item.id);if(!e)return[];i.itemToToolCall.delete(t.item.id);let n=Ay(t.item.changes)||e.output,r=t.item.status==="completed",o=n?[{type:"text",text:n}]:void 0,s={success:r,pastTenseMessage:r?"Applied file changes":"Failed to apply file changes",content:o,...r?{}:{error:{message:`Patch ${t.item.status}`}}};return[{type:"session/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:s}]}if(t.item.type==="mcpToolCall"){let e=i.itemToToolCall.get(t.item.id);if(!e)return[];i.itemToToolCall.delete(t.item.id);let n=t.item.status==="completed"&&!t.item.error,r=JM(t.item.result,t.item.error?.message)||e.output,o=r?[{type:"text",text:r}]:void 0;return[{type:"session/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:n,pastTenseMessage:n?`Called ${e.toolName}`:`Failed to call ${e.toolName}`,content:o,...n?{}:{error:{message:t.item.error?.message??`MCP tool ${t.item.status}`}}}}]}if(t.item.type==="dynamicToolCall"){let e=i.itemToToolCall.get(t.item.id);if(!e)return[];i.itemToToolCall.delete(t.item.id);let n=t.item.success===!0||t.item.status==="completed",r=g1(t.item.contentItems)||e.output,o=r?[{type:"text",text:r}]:void 0;return[{type:"session/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:n,pastTenseMessage:n?`Called ${e.toolName}`:`Failed to call ${e.toolName}`,content:o,...n?{}:{error:{message:`Dynamic tool ${t.item.status}`}}}}]}return[]}function R1(i,t){i.currentTurnId=void 0,i.itemToPartId.clear(),i.itemToReasoningPartId.clear();let e=[...i.itemToToolCall.values()];i.itemToToolCall.clear();let n=t.turn.id,r=t.turn.status,o=e.map(s=>({type:"session/toolCallComplete",turnId:s.turnId,toolCallId:s.toolCallId,result:{success:!1,pastTenseMessage:`Stopped ${s.toolName}`,content:s.output?[{type:"text",text:s.output}]:void 0,error:{message:r==="interrupted"?"Turn interrupted before the tool completed":"Turn completed before the tool reported completion"}}}));if(r==="failed"&&t.turn.error){let s=t.turn.error.message??"Codex turn failed";return[...o,{type:"session/error",turnId:n,error:{errorType:"CodexError",...fs(s)}},{type:"session/turnComplete",turnId:n}]}return r==="interrupted"?[...o,{type:"session/turnCancelled",turnId:n}]:[...o,{type:"session/turnComplete",turnId:n}]}function E1(i){switch(i){case"completed":return"complete";case"interrupted":return"cancelled";case"failed":return"error";default:return"complete"}}import*as P1 from"crypto";import*as A1 from"fs";import*as k1 from"os";var QM=[];function ky(i,t){let e=[],n=[],r=[i];if(t&&t.length>0)for(let s of t)switch(s.type){case"resource":{let a=y.parse(s.uri);a.scheme==="file"?r.push(`@${a.fsPath}`):r.push(a.toString());break}case"embeddedResource":{if(s.contentType.startsWith("image/")){let a=XM(s.contentType),l=W(k1.tmpdir(),`codex-img-${P1.randomBytes(8).toString("hex")}${a}`);try{A1.writeFileSync(l,Buffer.from(s.data,"base64")),e.push(l),n.push({type:"localImage",path:l})}catch{}}break}case"simple":{let a=s.modelRepresentation;typeof a=="string"&&a.length>0&&r.push(a);break}}let o=r.filter(s=>s.length>0).join(`

`);return n.unshift({type:"text",text:o,text_elements:QM}),{input:n,cleanupPaths:e}}function XM(i){switch(i.slice(6).toLowerCase()){case"jpeg":case"jpg":return".jpg";case"png":return".png";case"gif":return".gif";case"webp":return".webp";case"bmp":return".bmp";default:return""}}function D1(i){let t=[];for(let e of i.turns??[]){let n=ZM(e);n&&t.push(n)}return t}function ZM(i){let t="",e=[];for(let n of i.items??[])if(n.type==="userMessage"){let r=[];for(let o of n.content)o.type==="text"&&r.push(o.text);r.length>0&&(t=r.join(`

`))}else n.type==="agentMessage"&&n.text&&n.text.length>0&&e.push({kind:"markdown",id:N(),content:n.text});if(!(!t&&e.length===0))return{id:i.id,message:{text:t,origin:{kind:"user"}},responseParts:e,usage:void 0,state:E1(i.status)}}var ln=class{constructor(t,e){this._sessionDataService=t;this._logService=e}static{this.KEY_THREAD_ID="codex.threadId"}static{this.KEY_CWD="codex.cwd"}static{this.KEY_MODEL="codex.model"}async write(t,e){try{let n=this._sessionDataService.openDatabase(t),r=n.object;try{let o=[];e.threadId!==void 0&&o.push(r.setMetadata(ln.KEY_THREAD_ID,e.threadId)),e.cwd!==void 0&&o.push(r.setMetadata(ln.KEY_CWD,e.cwd.toString())),e.modelId!==void 0&&o.push(r.setMetadata(ln.KEY_MODEL,e.modelId)),await Promise.all(o)}finally{n.dispose()}}catch(n){this._logService.warn(`[Codex] metadata write failed for ${t.toString()}: ${n instanceof Error?n.message:String(n)}`)}}async read(t){try{let e=await this._sessionDataService.tryOpenDatabase(t);if(!e)return{};try{let[n,r,o]=await Promise.all([e.object.getMetadata(ln.KEY_THREAD_ID),e.object.getMetadata(ln.KEY_CWD),e.object.getMetadata(ln.KEY_MODEL)]);return{threadId:n??void 0,cwd:r?y.parse(r):void 0,modelId:o??void 0}}finally{e.dispose()}}catch(e){return this._logService.warn(`[Codex] metadata read failed for ${t.toString()}: ${e instanceof Error?e.message:String(e)}`),{}}}};ln=x([C(0,ft),C(1,O)],ln);function pf(i,t){return i.toLowerCase()==="auto"?!1:/^(gpt-5|codex)/i.test(i)||/codex/i.test(t??"")}function O1(i){if(pf(i))return i;let t=i.lastIndexOf("/");if(t===-1||t===i.length-1)return;let e=i.substring(t+1);return pf(e)?e:void 0}function Dy(i){switch(i){case"never":case"on-request":case"on-failure":case"untrusted":return i;default:return}}function Oy(i){switch(i){case"read-only":case"workspace-write":case"danger-full-access":return i;default:return}}function M1(i){if(Array.isArray(i))return i.filter(t=>typeof t=="string"&&t.length>0)}function L1(i){return typeof i=="boolean"?i:void 0}function N1(i){switch(i){case"disabled":case"cached":case"live":return i;default:return}}function My(i){switch(i){case"none":case"minimal":case"low":case"medium":case"high":case"xhigh":return i;default:return}}var tL={name:"vscode_agent_host",title:"VS Code Agent Host",version:"0.1.0"},U1="thinkingLevel",F1=["minimal","low","medium","high"],ua=zt({"codex.approvalPolicy":Ve({type:"string",title:g(2030,null),description:g(2039,null),enum:["never","on-request","on-failure","untrusted"],enumLabels:[g(2031,null),g(2035,null),g(2033,null),g(2037,null)],enumDescriptions:[g(2032,null),g(2036,null),g(2034,null),g(2038,null)],default:"on-request",sessionMutable:!0}),"codex.sandboxMode":Ve({type:"string",title:g(2048,null),description:g(2055,null),enum:["read-only","workspace-write","danger-full-access"],enumLabels:[g(2051,null),g(2053,null),g(2049,null)],enumDescriptions:[g(2052,null),g(2054,null),g(2050,null)],default:"workspace-write",sessionMutable:!0}),"codex.webSearchMode":Ve({type:"string",title:g(2056,null),description:g(2060,null),enum:["disabled","cached","live"],enumLabels:[g(2058,null),g(2057,null),g(2059,null)],default:"disabled",sessionMutable:!1}),"codex.modelReasoningEffort":Ve({type:"string",title:g(2040,null),description:g(2045,null),enum:[...F1],enumLabels:[g(2044,null),g(2042,null),g(2043,null),g(2041,null)],default:"medium",sessionMutable:!0}),"codex.additionalDirectories":Ve({type:"array",title:g(2027,null),description:g(2029,null),items:{type:"string",title:g(2028,null)},enumDynamic:!0,default:[],sessionMutable:!0}),"codex.networkAccessEnabled":Ve({type:"boolean",title:g(2046,null),description:g(2047,null),default:!1,sessionMutable:!0}),permissions:It.definition.permissions}),W1=zt({"codex.approvalPolicy":ua.definition["codex.approvalPolicy"],"codex.sandboxMode":ua.definition["codex.sandboxMode"],"codex.webSearchMode":ua.definition["codex.webSearchMode"],permissions:It.definition.permissions}),nL=zt({...W1.definition,"codex.networkAccessEnabled":ua.definition["codex.networkAccessEnabled"]}),Ur={"codex.approvalPolicy":"on-request","codex.sandboxMode":"workspace-write","codex.webSearchMode":"disabled","codex.modelReasoningEffort":"medium","codex.additionalDirectories":[],"codex.networkAccessEnabled":!1},rL=6e4,Ly={id:"codex",devOverrideEnvVar:db,hasSeparateMuslLinuxPackage:!1},ca=class extends T{constructor(e,n,r,o,s,a){super();this._logService=e;this._copilotApiService=n;this._codexProxyService=r;this._configurationService=o;this._agentSdkDownloader=s;this.id="codex";this._onDidSessionProgress=this._register(new w);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidMaterializeSession=this._register(new w);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._models=pn(this,[]);this.models=this._models;this._sessions=new Map;this._sessionIdByThreadId=new Map;this._connection={kind:"idle"};this._metadataStore=a.createInstance(ln)}getProtectedResources(){return[St]}async authenticate(e,n){if(e!==St.resource)return!1;let r=this._githubToken!==n;return this._githubToken=n,r&&this._connection.kind==="ready"?(this._connection.proxyHandle.setToken(n),this._queueModelRefresh(n)):r&&this._queueModelRefresh(n),this._logService.info("[Codex] Auth token updated"),!0}_queueModelRefresh(e){let n=this._refreshModels(e).finally(()=>{this._modelsRefreshPromise===n&&(this._modelsRefreshPromise=void 0)});this._modelsRefreshPromise=n,this._modelsRefreshPromise}_ensureAuthenticated(){let e=this._githubToken;if(!e)throw new D(on,"Authentication is required to use Codex",this.getProtectedResources());return e}_defaultModel(){let n=this._models.get()[0];return n?{id:n.id}:void 0}_supportedModelOrUndefined(e){if(e){let n=O1(e.id);if(n)return n===e.id?e:{...e,id:n}}return e&&this._logService.warn(`[Codex] Ignoring unsupported model '${e.id}'`),this._defaultModel()}async _resolveModel(e){let n=this._supportedModelOrUndefined(e.model);if(n)return e.model=n,n;this._modelsRefreshPromise&&await this._modelsRefreshPromise;let r=this._defaultModel();if(r)return e.model=r,r;throw new Error("Codex requires a GPT-5 or Codex model, but no supported models are available.")}_createReasoningEffortConfigSchema(){return{type:"object",properties:{[U1]:{type:"string",title:g(2026,null),description:g(2021,null),default:"medium",enum:[...F1],enumLabels:[g(2025,null),g(2023,null),g(2024,null),g(2022,null)]}}}}_getReasoningEffort(e){let n=My(e.model?.config?.[U1]);if(n)return n;let r=this._configurationService.getSessionConfigValues(e.sessionUri.toString());return My(r?.["codex.modelReasoningEffort"])??Ur["codex.modelReasoningEffort"]}_readSessionConfig(e){return ua.validateOrDefault(this._configurationService.getSessionConfigValues(e.sessionUri.toString()),Ur)}_sandboxPolicy(e,n){let r=Oy(n["codex.sandboxMode"])??Ur["codex.sandboxMode"];if(r==="danger-full-access")return{type:"dangerFullAccess"};let o=L1(n["codex.networkAccessEnabled"])??Ur["codex.networkAccessEnabled"];return r==="read-only"?{type:"readOnly",networkAccess:!1}:{type:"workspaceWrite",writableRoots:[...e.workingDirectory?[e.workingDirectory.fsPath]:[],...M1(n["codex.additionalDirectories"])??[]],networkAccess:o,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}_turnStartOptions(e){let n=this._readSessionConfig(e),r=Dy(n["codex.approvalPolicy"])??Ur["codex.approvalPolicy"],o=this._sandboxPolicy(e,n),s=o.type==="workspaceWrite"?o.writableRoots:void 0;return{approvalPolicy:r,sandboxPolicy:o,effort:this._getReasoningEffort(e),...s?{runtimeWorkspaceRoots:s}:{}}}async _refreshModels(e){try{let n=await this._copilotApiService.models(e),r=await this._ensureConnection(),o=new Map,s=null;do{let d=await r.client.request("model/list",{cursor:s,includeHidden:!1});for(let c of d.data)c.hidden||o.set(c.model,c.isDefault);s=d.nextCursor}while(s);if(this._githubToken!==e)return;let a=this._createReasoningEffortConfigSchema(),l=n.filter(d=>!!d.supported_endpoints?.includes("/responses")&&o.has(d.id)&&pf(d.id,d.name)).sort((d,c)=>Number(c.is_chat_default)-Number(d.is_chat_default)||Number(o.get(c.id))-Number(o.get(d.id))).map(d=>({provider:this.id,id:d.id,name:d.name??d.id,maxContextWindow:d.capabilities?.limits?.max_context_window_tokens,supportsVision:!!d.capabilities?.supports?.vision,configSchema:a}));this._models.set(l,void 0)}catch(n){this._logService.warn(`[Codex] Failed to refresh models: ${n instanceof Error?n.message:String(n)}`),this._githubToken===e&&this._models.set([],void 0)}}_ensureConnection(){if(this._connection.kind==="ready")return Promise.resolve(this._connection);if(this._connection.kind==="starting")return this._connection.promise;let e=this._ensureAuthenticated(),n=this._startConnection(e).then(r=>(this._connection={kind:"ready",...r},r)).catch(r=>{throw this._connection={kind:"idle"},r});return this._connection={kind:"starting",promise:n},n}async _startConnection(e){let n=await this._agentSdkDownloader.loadSdkRoot(Ly,Ee.None),r=oL(process.platform,process.arch);if(!r)throw new Error(`Codex: unsupported platform ${process.platform}-${process.arch}`);let o=sL(r);if(!o)throw new Error(`Codex: no binary triple known for sdkTarget '${r}'`);let s=process.platform==="win32"?"codex.exe":"codex",a=W(n,"node_modules",`@openai/codex-${r}`,"vendor",o,"bin",s);try{Ci.accessSync(a,Ci.constants.X_OK)}catch(b){throw new Error(`Codex binary not executable: ${a} (${b instanceof Error?b.message:String(b)})`)}let l=await this._codexProxyService.start(e),d={...process.env,OPENAI_API_KEY:l.nonce},c=process.env[cb];c&&(d.CODEX_HOME=c);let u=['model_provider="vscode-proxy"','model_providers.vscode-proxy.name="VS Code Proxy"',`model_providers.vscode-proxy.base_url="${l.baseUrl}/v1"`,'model_providers.vscode-proxy.wire_api="responses"','model_providers.vscode-proxy.env_key="OPENAI_API_KEY"',"model_providers.vscode-proxy.requires_openai_auth=false","model_providers.vscode-proxy.supports_websockets=false"],p=iL(process.env[ub]),m=["app-server",...u.flatMap(b=>["-c",b]),...p];this._logService.info(`[Codex] spawning ${a} ${m.join(" ")}`);let h=eL(a,m,{env:d,stdio:["pipe","pipe","pipe"]});h.stderr.setEncoding("utf8"),h.stderr.on("data",b=>this._logService.info(`[Codex stderr] ${String(b).trimEnd()}`));let v=d1(h),I=new cf(v,(b,S)=>{this._logService.info(`[CodexClient ${b}] ${S}`)});I.onExit(b=>{this._logService.warn(`[Codex] app-server exited code=${b.code} signal=${b.signal}`),this._handleConnectionLost()}),I.onTransportError(b=>{this._logService.error(`[Codex] transport error: ${b.message}`),this._handleConnectionLost()});try{await I.request("initialize",{clientInfo:tL,capabilities:{experimentalApi:!0,requestAttestation:!1,optOutNotificationMethods:null}}),I.notify("initialized",void 0),c&&await I.request("account/login/start",{type:"apiKey",apiKey:l.nonce}),this._logAccountSnapshot(I)}catch(b){I.dispose(),l.dispose();try{h.kill("SIGKILL")}catch{}throw b}return this._registerIgnoredNotifications(I),this._register(I.onNotification("turn/started",b=>this._dispatchByThread(b.threadId,S=>this._handleTurnStartedNotification(S,b)))),this._register(I.onNotification("item/started",b=>this._dispatchByThread(b.threadId,S=>b1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/agentMessage/delta",b=>this._dispatchByThread(b.threadId,S=>x1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/commandExecution/outputDelta",b=>this._dispatchByThread(b.threadId,S=>I1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/fileChange/patchUpdated",b=>this._dispatchByThread(b.threadId,S=>_1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/fileChange/outputDelta",b=>this._dispatchByThread(b.threadId,S=>C1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/mcpToolCall/progress",b=>this._dispatchByThread(b.threadId,S=>T1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/reasoning/summaryPartAdded",b=>this._dispatchByThread(b.threadId,S=>h1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/reasoning/summaryTextDelta",b=>this._dispatchByThread(b.threadId,S=>y1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("item/reasoning/textDelta",b=>this._dispatchByThread(b.threadId,S=>v1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("thread/tokenUsage/updated",b=>this._dispatchByThread(b.threadId,S=>S1(this._withHostTurnId(S,b))))),this._register(I.onNotification("item/completed",b=>this._dispatchByThread(b.threadId,S=>w1(S.mapState,this._withHostTurnId(S,b))))),this._register(I.onNotification("turn/completed",b=>this._dispatchByThread(b.threadId,S=>this._handleTurnCompletedNotification(S,b)))),this._register(I.onRequest("item/commandExecution/requestApproval",b=>this._handleCommandApprovalRequestRpc(b))),{client:I,proxyHandle:l,child:h}}_hostTurnId(e,n){return e.hostTurnIdByAppTurnId.get(n)??n}_withHostTurnId(e,n){let r=this._hostTurnId(e,n.turnId);return r===n.turnId?n:{...n,turnId:r}}_withHostTurn(e,n){let r=n.turn.id,o=e.currentTurnId??this._hostTurnId(e,r);return e.hostTurnIdByAppTurnId.set(r,o),e.currentAppTurnId=r,o===r?n:{...n,turn:{...n.turn,id:o}}}_handleTurnStartedNotification(e,n){return m1(e.mapState,this._withHostTurn(e,n),e.lastPromptText),[]}_handleTurnCompletedNotification(e,n){let r=n.turn.id,o=R1(e.mapState,this._withHostTurn(e,n));return(e.currentAppTurnId===r||e.currentTurnId===this._hostTurnId(e,r))&&(e.currentTurnId=void 0,e.currentAppTurnId=void 0),e.hostTurnIdByAppTurnId.delete(r),o}_registerIgnoredNotifications(e){let n=["thread/started","thread/status/changed","thread/settings/updated","thread/goal/updated","thread/goal/cleared","account/updated","account/rateLimits/updated","remoteControl/status/changed","serverRequest/resolved"];for(let r of n)this._register(e.onNotification(r,()=>{}))}async _logAccountSnapshot(e){try{let n=await e.request("account/read",{refreshToken:!1}),r=n.account?.type??"none",o=n.account?.type==="chatgpt"?n.account.planType:void 0;this._logService.info(`[Codex] account/read accountType=${r} requiresOpenaiAuth=${n.requiresOpenaiAuth}${o?` planType=${o}`:""}`)}catch(n){this._logService.warn(`[Codex] account/read failed: ${n instanceof Error?n.message:String(n)}`)}}_dispatchByThread(e,n){let r=this._sessionIdByThreadId.get(e),o=r?this._sessions.get(r):void 0;if(!o){this._logService.trace(`[Codex] Ignoring notification for untracked threadId=${e}; likely unclaimed prewarm`);return}let s=n(o);for(let a of s)this._onDidSessionProgress.fire({kind:"action",session:o.sessionUri,action:a})}async _handleCommandApprovalRequestRpc(e){return{result:{decision:await this._handleCommandApprovalRequest(e)}}}async _handleCommandApprovalRequest(e){let n=this._sessionIdByThreadId.get(e.threadId),r=n?this._sessions.get(n):void 0;if(!r)return this._logService.warn(`[Codex] commandExecution/requestApproval for unknown threadId=${e.threadId}; declining`),"decline";let o=r.mapState.itemToToolCall.get(e.itemId);if(!o)return this._logService.warn(`[Codex:${n}] commandExecution/requestApproval for unknown itemId=${e.itemId}; declining`),"decline";let s=e.command??"";if(s&&r.acceptedForSession.has(s))return"acceptForSession";let a=e.reason??"Run shell command",l=await r.pendingCommandApprovals.registerAndFire(o.toolCallId,()=>{this._fire(r.sessionUri,{type:"session/toolCallReady",turnId:o.turnId,toolCallId:o.toolCallId,invocationMessage:s,toolInput:s,confirmationTitle:a})});return l==="acceptForSession"&&s&&r.acceptedForSession.add(s),l}_handleConnectionLost(){let e=this._connection;if(e.kind==="ready"){this._connection={kind:"idle"};for(let n of this._sessions.values()){n.pendingCommandApprovals.denyAll("decline");let r=n.currentTurnId,o=n.currentAppTurnId;n.currentTurnId=void 0,n.currentAppTurnId=void 0,o&&n.hostTurnIdByAppTurnId.delete(o),r&&(this._onDidSessionProgress.fire({kind:"action",session:n.sessionUri,action:{type:"session/error",turnId:r,error:{errorType:"CodexDisconnected",message:"Codex app-server disconnected; session must restart."}}}),this._onDidSessionProgress.fire({kind:"action",session:n.sessionUri,action:{type:"session/turnComplete",turnId:r}}))}try{e.client.dispose()}catch(n){this._logService.error(`[Codex] Failed to dispose app-server client after connection lost: ${n instanceof Error?n.message:String(n)}`)}try{e.proxyHandle.dispose()}catch(n){this._logService.error(`[Codex] Failed to dispose proxy handle after connection lost: ${n instanceof Error?n.message:String(n)}`)}}}getDescriptor(){return{provider:this.id,displayName:g(2062,null),description:g(2061,null)}}async createSession(e={}){if(this._logService.info(`[Codex DEBUG] createSession session=${e.session?.toString()??"(none)"} model=${e.model?.id??"(none)"} cwd=${e.workingDirectory?.toString()??"(none)"}`),this._ensureAuthenticated(),e.fork)throw new Error("Codex agent does not support session forking");if(!e.workingDirectory)throw new Error("Codex requires a working directory; pass `workingDirectory` to createSession");let n=this._supportedModelOrUndefined(e.model),r=e.session?F.id(e.session):N(),o=e.session??F.uri(this.id,r),s=this._sessions.get(r);if(s)return s.model=n??s.model,{session:o,workingDirectory:s.workingDirectory??e.workingDirectory,provisional:s.threadId===void 0};let a={sessionId:r,threadId:void 0,sessionUri:o,workingDirectory:e.workingDirectory,mapState:Ry(),pendingCommandApprovals:new sn,acceptedForSession:new Set,model:n,currentTurnId:void 0,currentAppTurnId:void 0,hostTurnIdByAppTurnId:new Map,needsResume:!1,lastPromptText:"",disposed:!1,materializePromise:void 0,materializedEventFired:!1,prewarmTimer:void 0,prewarmClaimed:!1};return this._sessions.set(r,a),this._schedulePrewarm(a),{session:o,workingDirectory:e.workingDirectory,provisional:!0}}async _materializeIfNeeded(e,n=!0){if(!e.disposed){if(e.threadId!==void 0){n&&this._fireMaterialized(e);return}if(e.materializePromise){await e.materializePromise,n&&this._fireMaterialized(e);return}e.materializePromise=this._materialize(e).finally(()=>{e.materializePromise=void 0}),await e.materializePromise,n&&this._fireMaterialized(e)}}async _materialize(e){if(e.disposed)return;if(!e.workingDirectory)throw new Error(`Cannot materialize codex session ${e.sessionId}: no working directory`);let n=await this._ensureConnection(),r=this._readSessionConfig(e),o=await this._resolveModel(e),a=(await n.client.request("thread/start",{cwd:e.workingDirectory.fsPath,model:o.id,approvalPolicy:Dy(r["codex.approvalPolicy"])??Ur["codex.approvalPolicy"],sandbox:Oy(r["codex.sandboxMode"])??Ur["codex.sandboxMode"],config:{web_search:N1(r["codex.webSearchMode"])??Ur["codex.webSearchMode"]}})).thread.id;if(e.disposed){try{await n.client.request("thread/unsubscribe",{threadId:a})}catch(l){this._logService.info(`[Codex:${a}] thread/unsubscribe after disposed prewarm failed: ${l instanceof Error?l.message:String(l)}`)}return}e.threadId=a,this._logService.info(`[Codex DEBUG] materialized session=${e.sessionUri.toString()} threadId=${e.threadId}`),this._sessionIdByThreadId.set(e.threadId,e.sessionId)}_fireMaterialized(e){e.disposed||e.materializedEventFired||(e.materializedEventFired=!0,this._onDidMaterializeSession.fire({session:e.sessionUri,workingDirectory:e.workingDirectory,project:void 0}))}_schedulePrewarm(e){e.workingDirectory&&this._materializeIfNeeded(e,!1).then(()=>{if(e.prewarmClaimed||e.threadId===void 0)return;this._logService.info(`[Codex] prewarm ready session=${e.sessionUri.toString()} threadId=${e.threadId}`);let n=setTimeout(()=>{this._expirePrewarm(e)},rL);e.prewarmTimer=n}).catch(n=>{this._logService.warn(`[Codex] prewarm failed session=${e.sessionUri.toString()}: ${n instanceof Error?n.message:String(n)}`)})}async _expirePrewarm(e){if(e.disposed||e.prewarmClaimed||e.threadId===void 0)return;let n=e.threadId;e.threadId=void 0,this._sessionIdByThreadId.delete(n);try{await(await this._ensureConnection()).client.request("thread/unsubscribe",{threadId:n}),this._logService.info(`[Codex] prewarm TTL eviction session=${e.sessionUri.toString()} threadId=${n}`)}catch(r){this._logService.warn(`[Codex] prewarm TTL eviction failed session=${e.sessionUri.toString()} threadId=${n}: ${r instanceof Error?r.message:String(r)}`)}}_persistMaterializedSession(e){e.disposed||!e.threadId||this._metadataStore.write(e.sessionUri,{threadId:e.threadId,cwd:e.workingDirectory,modelId:e.model?.id})}_claimPrewarm(e){e.prewarmClaimed=!0,e.prewarmTimer&&(clearTimeout(e.prewarmTimer),e.prewarmTimer=void 0)}async sendMessage(e,n,r,o){this._logService.info(`[Codex DEBUG] sendMessage session=${e.toString()} prompt=${JSON.stringify(n).slice(0,60)}`);let s=F.id(e),a=this._sessions.get(s);if(!a)throw new Error(`Codex session not found: ${e.toString()}`);let l=await this._ensureConnection(),d=o??N();try{this._claimPrewarm(a),await this._materializeIfNeeded(a),this._persistMaterializedSession(a)}catch(m){let h=m instanceof Error?m.message:String(m);this._logService.error(`[Codex:${s}] materialize failed: ${h}`),this._fire(e,{type:"session/error",turnId:d,error:{errorType:"CodexMaterializeFailed",message:h}}),this._fire(e,{type:"session/turnComplete",turnId:d});return}let c=a.threadId;if(a.needsResume)try{await l.client.request("thread/resume",{threadId:c}),a.needsResume=!1}catch(m){this._fire(e,{type:"session/error",turnId:d,error:{errorType:"CodexResumeFailed",message:m instanceof Error?m.message:String(m)}}),this._fire(e,{type:"session/turnComplete",turnId:d});return}let{input:u,cleanupPaths:p}=ky(n,r);a.lastPromptText=n,a.currentTurnId=d;try{let m=this._turnStartOptions(a),h=await this._resolveModel(a);await l.client.request("turn/start",{threadId:c,input:u.slice(),model:h.id,...m})}catch(m){if(m instanceof K){this._fire(e,{type:"session/turnCancelled",turnId:d});return}let h=m instanceof Error?m.message:String(m);this._logService.error(`[Codex:${s}] turn/start error: ${h}`),this._fire(e,{type:"session/error",turnId:d,error:{errorType:"CodexTurnError",...fs(h)}}),this._fire(e,{type:"session/turnComplete",turnId:d})}finally{p.length>0&&setTimeout(()=>{for(let m of p)try{Ci.unlinkSync(m)}catch{}},3e4)}}setPendingMessages(e,n,r){if(!n)return;let o=F.id(e),s=this._sessions.get(o);if(!s)return;let a=s.currentAppTurnId;if(!a)return;let l=this._connection;if(l.kind!=="ready")return;let d=n.message.text;if(d.length===0&&(!n.message.attachments||n.message.attachments.length===0))return;let{input:c}=ky(d,n.message.attachments);if(s.threadId===void 0)return;let u=s.threadId;l.client.request("turn/steer",{threadId:u,input:c.slice(),expectedTurnId:a}).catch(p=>{if(p instanceof _i){this._logService.info(`[Codex:${o}] turn/steer skipped: ${p.message}`);return}this._logService.warn(`[Codex:${o}] turn/steer failed: ${p instanceof Error?p.message:String(p)}`)})}async abortSession(e){let n=F.id(e),r=this._sessions.get(n);if(!r||!r.currentAppTurnId||r.threadId===void 0)return;let o=r.threadId,s=this._connection;if(s.kind==="ready")try{await s.client.request("turn/interrupt",{threadId:o,turnId:r.currentAppTurnId})}catch(a){this._logService.warn(`[Codex:${n}] turn/interrupt failed: ${a instanceof Error?a.message:String(a)}`)}}async disposeSession(e){this._logService.info(`[Codex DEBUG] disposeSession session=${e.toString()}`);let n=F.id(e),r=this._sessions.get(n);if(!r)return;r.disposed=!0,this._claimPrewarm(r),this._sessions.delete(n),r.threadId!==void 0&&this._sessionIdByThreadId.delete(r.threadId),r.pendingCommandApprovals.denyAll("decline");let o=this._connection;if(o.kind==="ready"&&r.threadId!==void 0){let s=r.threadId;try{await o.client.request("thread/unsubscribe",{threadId:s})}catch(a){this._logService.info(`[Codex:${s}] thread/unsubscribe failed: ${a instanceof Error?a.message:String(a)}`)}}}async changeModel(e,n){let r=this._sessions.get(F.id(e));if(r){let o=this._supportedModelOrUndefined(n);o&&(r.model=o)}}respondToPermissionRequest(e,n){for(let r of this._sessions.values())if(r.pendingCommandApprovals.respond(e,n?"accept":"decline"))return;this._logService.info(`[Codex] respondToPermissionRequest: unknown requestId=${e}`)}respondToUserInputRequest(e,n,r){this._logService.info("[Codex] respondToUserInputRequest called (Phase 4 stub)")}getSessionMessages(e){return this._readSession(e).then(n=>n?D1(n.thread):[])}async getSessionMetadata(e){let n=F.id(e),r=await this._readSession(e);if(r){if(!this._sessions.has(n)){let o=r.thread.cwd?y.file(r.thread.cwd):void 0,s=r.thread.id;this._sessions.set(n,{sessionId:n,threadId:s,sessionUri:e,workingDirectory:o,mapState:Ry(),pendingCommandApprovals:new sn,acceptedForSession:new Set,model:void 0,currentTurnId:void 0,currentAppTurnId:void 0,hostTurnIdByAppTurnId:new Map,needsResume:!0,lastPromptText:"",disposed:!1,materializePromise:void 0,materializedEventFired:!0,prewarmTimer:void 0,prewarmClaimed:!0}),this._sessionIdByThreadId.set(s,n)}return this._threadToMetadata(r.thread,e)}}async _readSession(e){let n=F.id(e),o=this._sessions.get(n)?.threadId;o===void 0&&(o=(await this._metadataStore.read(e)).threadId??n);try{return await(await this._ensureConnection()).client.request("thread/read",{threadId:o,includeTurns:!0})}catch(s){let a=s instanceof Error?s.message:String(s);/thread not loaded/i.test(a)?this._logService.info(`[Codex:${o}] thread/read: not loaded yet (will resume on first send)`):this._logService.warn(`[Codex:${o}] thread/read failed: ${a}`);return}}async listSessions(){if(!this._githubToken)return[];try{let n=await(await this._ensureConnection()).client.request("thread/list",{limit:200}),r=new Map;for(let o of this._sessions.values())o.threadId!==void 0&&r.set(o.threadId,o.sessionUri);return n.data.map(o=>this._threadToMetadata(o,r.get(o.id)??F.uri(this.id,o.id)))}catch(e){return this._logService.warn(`[Codex] thread/list failed: ${e instanceof Error?e.message:String(e)}`),[]}}_threadToMetadata(e,n){return{session:n,startTime:(e.createdAt??0)*1e3,modifiedTime:(e.updatedAt??e.createdAt??0)*1e3,summary:e.name??e.preview??void 0,workingDirectory:e.cwd?y.file(e.cwd):void 0}}setClientTools(e,n,r){}onClientToolCallComplete(e,n,r){}setClientCustomizations(e,n,r){return Promise.resolve([])}setCustomizationEnabled(e,n){}async shutdown(){if(this._connection.kind==="ready"){try{this._connection.client.dispose()}catch{}try{this._connection.proxyHandle.dispose()}catch{}}this._connection={kind:"idle"};for(let e of this._sessions.values())e.pendingCommandApprovals.denyAll("decline");this._sessions.clear(),this._sessionIdByThreadId.clear()}resolveSessionConfig(e){let n=ua.validateOrDefault(e.config,Ur),r=n["codex.sandboxMode"]==="workspace-write",o=r?nL.toProtocol():W1.toProtocol(),s={"codex.approvalPolicy":n["codex.approvalPolicy"],"codex.sandboxMode":n["codex.sandboxMode"],"codex.webSearchMode":n["codex.webSearchMode"]};return r&&(s["codex.networkAccessEnabled"]=n["codex.networkAccessEnabled"]),Promise.resolve({values:s,schema:o})}async sessionConfigCompletions(e){if(e.property!=="codex.additionalDirectories")return{items:[]};let n=e.query?.trim();if(!n)return{items:[]};let r=e.workingDirectory?.fsPath,o=Wt(n)?n:dn(r??process.cwd(),n),s=n.endsWith(be)?o:se(o),a=n.endsWith(be)?"":Ce(o).toLowerCase();try{return{items:(await Ci.promises.readdir(s,{withFileTypes:!0})).filter(d=>d.isDirectory()&&d.name.toLowerCase().startsWith(a)).slice(0,50).map(d=>{let c=W(s,d.name);return{value:c,label:d.name,description:c}})}}catch{return{items:[]}}}_fire(e,n){this._onDidSessionProgress.fire({kind:"action",session:e,action:n})}dispose(){if(this._connection.kind==="ready"){try{this._connection.client.dispose()}catch{}try{this._connection.proxyHandle.dispose()}catch{}}this._connection={kind:"idle"};for(let e of this._sessions.values())e.pendingCommandApprovals.denyAll("decline");this._sessions.clear(),this._sessionIdByThreadId.clear(),super.dispose()}};ca=x([C(0,O),C(1,Kt),C(2,uf),C(3,$e),C(4,js),C(5,ke)],ca);function iL(i){if(!i)return[];try{let t=JSON.parse(i);return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function oL(i,t){if(!(i!=="linux"&&i!=="darwin"&&i!=="win32"||t!=="x64"&&t!=="arm64"))return`${i}-${t}`}function sL(i){switch(i){case"linux-x64":return"x86_64-unknown-linux-musl";case"linux-arm64":return"aarch64-unknown-linux-musl";case"darwin-x64":return"x86_64-apple-darwin";case"darwin-arm64":return"aarch64-apple-darwin";case"win32-x64":return"x86_64-pc-windows-msvc";case"win32-arm64":return"aarch64-pc-windows-msvc";default:return}}import{mkdir as xL}from"fs/promises";var aL=/^[0-9a-fA-F]+$/,lL="00000000000000000000000000000000",$1="0000000000000000";function H1(i){if(!i||!Array.isArray(i.resourceSpans))return{spans:[],rejected:0,errors:[]};let t=[],e=[],n=0;for(let r of i.resourceSpans){if(!r)continue;let o=pL(r.resource?.attributes);for(let s of r.scopeSpans??[])if(s)for(let a of s.spans??[])try{let l=dL(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 dL(i,t){if(!i)return;let e=(i.traceId??"").toLowerCase(),n=(i.spanId??"").toLowerCase();if(!Ny(e,32)||e===lL)throw new Error(`invalid traceId: ${i.traceId}`);if(!Ny(n,16)||n===$1)throw new Error(`invalid spanId: ${i.spanId}`);let r;if(i.parentSpanId){let c=i.parentSpanId.toLowerCase();Ny(c,16)&&c!==$1&&(r=c)}let o=Fy(i.startTimeUnixNano),s=Fy(i.endTimeUnixNano);if(o===void 0||s===void 0)throw new Error("missing span time bounds");let a={...t};for(let c of i.attributes??[])Wy(a,c);let l=[];for(let c of i.events??[]){let u=cL(c);u&&l.push(u)}let d=uL(i.status?.code,i.status?.message);return{name:i.name??"",traceId:e,spanId:n,parentSpanId:r,startTime:o,endTime:s,status:d,attributes:a,events:l}}function cL(i){if(!i)return;let t=Fy(i.timeUnixNano);if(t===void 0)return;let e={};for(let n of i.attributes??[])Wy(e,n);return{name:i.name??"",timestamp:t,attributes:Object.keys(e).length>0?e:void 0}}function uL(i,t){switch(i){case 1:return{code:1,message:t};case 2:return{code:2,message:t};case 0:default:return{code:0,message:t}}}function pL(i){let t={};if(!i)return t;for(let e of i)Wy(t,e);return t}function Wy(i,t){if(!t||typeof t.key!="string"||t.key.length===0)return;let e=Uy(t.value);e!==void 0&&(i[t.key]=e)}function Uy(i){if(i){if(typeof i.stringValue=="string")return i.stringValue;if(typeof i.boolValue=="boolean")return i.boolValue;if(i.intValue!==void 0){let t=typeof i.intValue=="string"?Number(i.intValue):i.intValue;return Number.isFinite(t)?t:void 0}if(typeof i.doubleValue=="number")return i.doubleValue;if(i.arrayValue?.values){let t=i.arrayValue.values.map(Uy);return t.every(e=>typeof e=="string")?t:JSON.stringify(t)}if(i.kvlistValue?.values){let t={};for(let e of i.kvlistValue.values)e&&typeof e.key=="string"&&(t[e.key]=Uy(e.value));return JSON.stringify(t)}if(typeof i.bytesValue=="string")return i.bytesValue}}function Fy(i){if(i===void 0||i===""||i==="0")return;let t=i.length<=6?"0":i.slice(0,-6),e=Number(t);return Number.isFinite(e)?e:void 0}function Ny(i,t){return i.length===t&&aL.test(i)}var fL="/v1/traces",gL=64*1024*1024;async function q1(i,t,e={}){let n=e.maxBodyBytes??gL,o=(await import("http")).createServer();o.on("request",(c,u)=>{mL(c,u,i,t,n).catch(p=>{if(t.error(`[agentHost-otel] receiver: unhandled error: ${p instanceof Error?p.message:String(p)}`),!u.headersSent)Ti(u,500,"internal error");else if(!u.writableEnded)try{u.end()}catch{}})}),await new Promise((c,u)=>{let p=m=>u(m);o.once("error",p),o.listen(0,"127.0.0.1",()=>{o.removeListener("error",p),c()})});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 d=k(()=>{o.closeAllConnections(),o.close(c=>{c&&t.warn(`[agentHost-otel] receiver close error: ${c.message}`)})});return Object.assign(d,{baseUrl:l,port:a})}async function mL(i,t,e,n,r){if((i.url??"").split("?",1)[0]!==fL){Ti(t,404,"not found");return}if(i.method!=="POST"){t.setHeader("allow","POST"),Ti(t,405,"method not allowed");return}let a=(i.headers["content-type"]??"").toString().toLowerCase();if(!a.includes("application/json")){Ti(t,415,"unsupported content-type; this receiver only accepts application/json");return}let l=(i.headers["content-encoding"]??"").toString().toLowerCase();if(l&&l!=="identity"){Ti(t,415,`unsupported content-encoding: ${l}`);return}let d;try{d=await hL(i,r)}catch(m){m instanceof ff?Ti(t,413,"payload too large"):Ti(t,400,"failed to read body");return}if(e.onForward)try{e.onForward(d,a)}catch(m){n.warn(`[agentHost-otel] forward callback threw: ${m instanceof Error?m.message:String(m)}`)}let c;try{c=JSON.parse(d.toString("utf8"))}catch(m){Ti(t,400,`invalid json: ${m instanceof Error?m.message:String(m)}`);return}let u=H1(c);try{e.onSpans(u)}catch(m){n.warn(`[agentHost-otel] onSpans handler threw: ${m instanceof Error?m.message:String(m)}`)}let p=u.rejected>0?{partialSuccess:{rejectedSpans:u.rejected,errorMessage:u.errors.join("; ").slice(0,1024)}}:{};t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify(p))}var ff=class extends Error{};function hL(i,t){return new Promise((e,n)=>{let r=[],o=0,s=c=>{if(o+=c.length,o>t){d(),n(new ff(`body exceeds ${t} bytes`));return}r.push(c)},a=()=>{d(),e(Buffer.concat(r))},l=c=>{d(),n(c)},d=()=>{i.removeListener("data",s),i.removeListener("end",a),i.removeListener("error",l)};i.on("data",s),i.on("end",a),i.on("error",l)})}function Ti(i,t,e){i.statusCode=t,i.setHeader("content-type","text/plain; charset=utf-8"),i.end(e)}import{URL as B1}from"url";import{promises as yL}from"fs";function vL(i){try{let t=new B1(i);return t.pathname===""||t.pathname==="/"?(t.pathname="/v1/traces",t.toString()):i}catch{return i}}var gf=class extends T{constructor(e,n){super();this._options=e;this._logService=n;this._queue=new Jr;this._disposed=!1;this._resolvedEndpoint=vL(e.endpoint),this._register(k(()=>{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 r=new B1(this._resolvedEndpoint),o=r.protocol==="https:",s=o?await import("https"):await import("http"),a={"content-type":n,"content-length":String(e.length),...this._options.headers??{}};await SL(s,{host:r.hostname,port:r.port?Number(r.port):o?443:80,path:r.pathname+(r.search??""),method:"POST",headers:a,timeoutMs:this._options.timeoutMs??1e4},e)}catch(r){this._logService.warn(`[agentHost-otel] forward to ${this._resolvedEndpoint} failed: ${r instanceof Error?r.message:String(r)}`)}}};function SL(i,t,e){return new Promise((n,r)=>{let o=i.request({host:t.host,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:t.timeoutMs}),s=a=>{o.destroy(),r(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():r(new Error(`upstream returned HTTP ${l}`))}),a.on("error",s)}),o.end(e)})}var mf=class extends T{constructor(e,n){super();this._options=e;this._logService=n;this._queue=new Jr;this._disposed=!1;this._register(k(()=>{this._disposed=!0}))}forwardSpans(e){if(this._disposed||e.spans.length===0)return;let n=e.spans.map(r=>JSON.stringify(r)).join(`
`)+`
`;this._queue.queue(()=>this._append(n))}async flush(){try{await this._queue.queue(()=>Promise.resolve())}catch{}}async _append(e){try{await yL.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)}`)}}},hf=class extends T{constructor(e){super();this._logService=e;this._disposed=!1;this._register(k(()=>{this._disposed=!0}))}forwardSpans(e){if(!this._disposed)for(let n of e.spans)this._logService.info(`[agentHost-otel] span ${bL(n)}`)}async flush(){}};function bL(i){let t=Math.max(0,i.endTime-i.startTime),e=i.attributes["gen_ai.operation.name"],n=i.attributes["gen_ai.request.model"]??i.attributes["gen_ai.response.model"],r=[e&&`op=${e}`,n&&`model=${n}`].filter(Boolean).join(" ");return`${i.name} (${t}ms) trace=${i.traceId} span=${i.spanId}${r?" "+r:""}`}var yf=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 IL}from"fs";import{createRequire as _L}from"module";var Qt={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"},rd={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 CL=_L(import.meta.url);function TL(){return CL("node:sqlite")}var V1=1,z1=10080*60*1e3,j1=100,Ot={operation_name:Qt.OPERATION_NAME,provider_name:Qt.PROVIDER_NAME,agent_name:Qt.AGENT_NAME,conversation_id:Qt.CONVERSATION_ID,request_model:Qt.REQUEST_MODEL,response_model:Qt.RESPONSE_MODEL,input_tokens:Qt.USAGE_INPUT_TOKENS,output_tokens:Qt.USAGE_OUTPUT_TOKENS,cached_tokens:Qt.USAGE_CACHE_READ_INPUT_TOKENS,reasoning_tokens:Qt.USAGE_REASONING_TOKENS,tool_name:Qt.TOOL_NAME,tool_call_id:Qt.TOOL_CALL_ID,tool_type:Qt.TOOL_TYPE,chat_session_id:rd.CHAT_SESSION_ID,turn_index:rd.TURN_INDEX,ttft_ms:rd.TIME_TO_FIRST_TOKEN},Phe=$("otelSqliteStore"),vf=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,Ot.operation_name),this._attr(t,Ot.provider_name),this._attr(t,Ot.agent_name),this._attr(t,Ot.conversation_id),this._attr(t,Ot.request_model),this._attr(t,Ot.response_model),this._attr(t,Ot.input_tokens),this._attr(t,Ot.output_tokens),this._attr(t,Ot.cached_tokens),this._attr(t,Ot.reasoning_tokens),this._attr(t,Ot.tool_name),this._attr(t,Ot.tool_call_id),this._attr(t,Ot.tool_type),this._attr(t,Ot.chat_session_id),this._attr(t,Ot.turn_index),this._ttftMs(t));for(let[e,n]of Object.entries(t.attributes)){let r=Array.isArray(n)?JSON.stringify(n):String(n);this._insertAttrStmt.run(t.spanId,e,r)}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(r=>r.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=z1){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,rd.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 r=typeof n=="number"?n:parseFloat(String(n));return isNaN(r)?null:Math.round(r*1e3)}_ensureDb(){if(this._db)return this._db;this._dbPath!==":memory:"&&IL(se(this._dbPath),{recursive:!0});let{DatabaseSync:t}=TL(),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)>=V1||t.exec(`
			CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
			INSERT OR REPLACE INTO schema_version (version) VALUES (${V1});

			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()-z1;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(j1);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,j1)}};var wL=pb;function $y(i){if(!i)return!1;let t=i.trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}function RL(i){if(!i)return;let t={};for(let e of i.split(",")){let n=e.indexOf("=");if(n<=0)continue;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();r&&(t[r]=o)}return Object.keys(t).length?t:void 0}function EL(i){let t=$y(i.COPILOT_OTEL_DB_SPAN_EXPORTER_ENABLED),e=i.OTEL_EXPORTER_OTLP_ENDPOINT??i.COPILOT_OTEL_ENDPOINT,n=i.COPILOT_OTEL_FILE_EXPORTER_PATH,o=$y(i.COPILOT_OTEL_ENABLED)||t||!!e||!!n,s=(i.COPILOT_OTEL_EXPORTER_TYPE??"").trim().toLowerCase(),a=(i.OTEL_EXPORTER_OTLP_PROTOCOL??i.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:i.COPILOT_OTEL_SOURCE_NAME,captureContent:i.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT===void 0?void 0:$y(i.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT),headers:RL(i.OTEL_EXPORTER_OTLP_HEADERS)}}var pa=class extends T{constructor(e,n){super();this._logService=e;this._config=EL(process.env),this._spansDbPath=W(n.userDataPath,wL)}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 xL(se(this._spansDbPath),{recursive:!0});let e=new vf(this._spansDbPath);this._register(k(()=>e.close())),this._forwarder=this._buildOutboundForwarder();let n=await q1({onSpans:r=>{for(let o of r.spans)try{e.insertSpan(o)}catch(s){this._logService.warn("[agentHost.otel] failed to insert span",s)}this._forwarder?.forwardSpans?.(r)},onForward:this._forwarder?(r,o)=>{this._forwarder.forwardRaw?.(r,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 gf({endpoint:this._config.otlpEndpoint,headers:this._config.headers},this._logService));break;case"file":this._config.filePath&&e.push(new mf({filePath:this._config.filePath},this._logService));break;case"console":e.push(new hf(this._logService));break}if(e.length)return e.length===1?e[0]:new yf(e)}};pa=x([C(0,O),C(1,yn)],pa);var Sf=class extends Error{constructor(e,n,r){super(n);this.code=e;this.data=r}},K1=class i 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=Ee.None,r){if(this._store.isDisposed)return Promise.reject(new K);let o=this._nextRequestId++,s=new Ie,a=new je;this._pendingRequests.set(o,{promise:s,cts:a});let l=n.onCancellationRequested(()=>{s.isSettled||(this._pendingRequests.delete(o),a.cancel(),r?.(o),s.cancel()),l.dispose()});return this._send({jsonrpc:"2.0",id:o,...e}),s.p.finally(()=>{l.dispose(),this._pendingRequests.delete(o),a.dispose(!0)})}async handleMessage(e){if(Array.isArray(e)){let r=[];for(let o of e){let s=await this._handleMessage(o);s&&r.push(s)}return r}let n=await this._handleMessage(e);return n?[n]:[]}cancelPendingRequest(e){let n=this._pendingRequests.get(e);n&&(this._pendingRequests.delete(e),n.cts.cancel(),n.promise.cancel(),n.cts.dispose(!0))}cancelAllRequests(){for(let[e,n]of this._pendingRequests)this._pendingRequests.delete(e),n.cts.cancel(),n.promise.cancel(),n.cts.dispose(!0)}async _handleMessage(e){if(Hy(e)){ye(e,{result:!0})?this._handleResult(e):this._handleError(e);return}if(PL(e))return this._handleRequest(e);AL(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 Sf(e.error.code,e.error.message,e.error.data)),n.cts.dispose(!0))}async _handleRequest(e){if(!this._handlers.handleRequest){let r={jsonrpc:"2.0",id:e.id,error:{code:i.MethodNotFound,message:`Method not found: ${e.method}`}};return this._send(r),r}let n=new je;this._register(k(()=>n.dispose(!0)));try{let r=this._handlers.handleRequest(e,n.token),o=kL(r)?await r:r,s={jsonrpc:"2.0",id:e.id,result:o};return this._send(s),s}catch(r){let o;return r instanceof Sf?o={jsonrpc:"2.0",id:e.id,error:{code:r.code,message:r.message,data:r.data}}:o={jsonrpc:"2.0",id:e.id,error:{code:i.InternalError,message:r instanceof Error?r.message:"Internal error"}},this._send(o),o}finally{n.dispose(!0)}}dispose(){this.cancelAllRequests(),super.dispose()}static createParseError(e,n){return{jsonrpc:"2.0",error:{code:i.ParseError,message:e,data:n}}}};function PL(i){return"method"in i&&"id"in i&&(typeof i.id=="string"||typeof i.id=="number")}function Hy(i){return ye(i,{id:!0,result:!0})||ye(i,{id:!0,error:!0})}function AL(i){return ye(i,{method:!0})&&!ye(i,{id:!0})}function kL(i){return typeof i=="object"&&i!==null&&"then"in i&&typeof i.then=="function"}var fa="0.4.0",Yhe=Object.freeze(["0.4.0","0.3.0"]);function G1(i){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(i);if(!t)throw new Error(`Invalid protocol version: ${i}`);return[Number(t[1]),Number(t[2]),Number(t[3])]}function qy(i,t){let[e,n,r]=G1(i),[o,s,a]=G1(t);return e-o||n-s||r-a}var Qhe={"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/mcpServerStateChanged":"0.3.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/operationStatusChanged":"0.3.0","changeset/cleared":"0.2.0","annotations/set":"0.3.0","annotations/updated":"0.4.0","annotations/removed":"0.3.0","annotations/entrySet":"0.3.0","annotations/entryRemoved":"0.3.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 J1(i){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(i);if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}function DL(i,t){let e=J1(i),n=J1(t);return!e||!n||e[0]!==n[0]||e[0]===0&&e[1]!==n[1]?!1:qy(i,t)<=0}function Y1(i,t){let e;for(let n of i)DL(n,t)&&(e===void 0||qy(n,e)>0)&&(e=n);return e}var By="_vscodeUpgrade";var Q1="VSCODE_AGENT_HOST_MANAGEMENT_SOCKET";function bf(){let i=process.env[Q1];return i&&i.length>0?i:void 0}async function X1(i=bf()){let t=await import("http");return i?new Promise((e,n)=>{let r=t.request({socketPath:i,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,d;try{d=a?JSON.parse(a):void 0}catch{}if(l>=200&&l<300&&d&&d.ok!==!1)e(d);else{let c=d?.error||a||`HTTP ${l}`;n(new Error(`Agent host upgrade request failed: ${c}`))}}),o.on("error",n)});r.once("error",n),r.end()}):Promise.reject(new Error(`Cannot request upgrade: ${Q1} is not set.`))}var OL=1e3,Z1=3e4;function ML(i){return i==="streaming"||i==="running"||i==="pending-confirmation"}function lo(i,t){return{jsonrpc:"2.0",id:i,result:t}}function id(i,t,e,n){return{jsonrpc:"2.0",id:i,error:{code:t,message:e,...n!==void 0?{data:n}:{}}}}function co(i,t){if(t instanceof D)return id(i,t.code,t.message,t.data);let e=t instanceof Error?t.stack??t.message:String(t);return id(i,Jo,e)}function ew(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function LL(i){if(!ew(i))return;let t=i.channel;if(!(typeof t!="string"||!t.startsWith("mcp://")))return t}function If(i){if(i.toLowerCase().startsWith(`${vT}:`)){let t=IT(i);return t?{kind:"otlp-logs",uri:_T(t),level:t}:void 0}return TI(i)?{kind:"resource-watch",uri:i}:{kind:"state",uri:i}}var uo=class extends T{constructor(e,n,r,o,s,a){super();this._agentService=e;this._stateManager=n;this._server=r;this._config=o;this._clientFileSystemProvider=s;this._logService=a;this._clients=new Map;this._replayBuffer=[];this._onDidChangeConnectionCount=this._register(new w);this.onDidChangeConnectionCount=this._onDidChangeConnectionCount.event;this._requestHandlers={subscribe:async(e,n)=>{let r=If(n.channel);if(!r)return{};if(r.kind==="otlp-logs")return this._config.otlpLogEmitter?(e.subscriptions.set(r.uri,r),{}):(this._logService.warn(`[ProtocolServer] Ignoring OTLP subscribe for ${n.channel}: no OTLP emitter configured.`),{});if(r.kind==="resource-watch"){let o=this._agentService.onResourceWatchSubscribed(r.uri);if(!o)throw new D(At,`Resource watch not found: ${n.channel}`);return e.subscriptions.set(r.uri,r),{snapshot:{resource:r.uri,state:o,fromSeq:this._stateManager.serverSeq}}}try{let o=await this._agentService.subscribe(y.parse(n.channel),e.clientId);return e.subscriptions.set(r.uri,r),this._clearClientToolCallDisconnectTimeout(e.clientId,r.uri),{snapshot:o}}catch(o){throw o instanceof D?o:new D(At,`Resource not found: ${n.channel}`)}},createSession:async(e,n)=>{let r,o;if(n.fork){let s=this._stateManager.getSessionState(n.fork.session);if(!s)throw new D(At,`Fork source session not found: ${n.fork.session}`);let a=s.turns.findIndex(l=>l.id===n.fork.turnId);if(a<0)throw new D(At,`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 D(fe.InvalidParams,"createSession.activeClient.clientId must match the connection's clientId");try{r=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 D?s:new D(pI,s instanceof Error?s.message:String(s))}return r.toString()!==y.parse(n.channel).toString()&&this._logService.warn(`[ProtocolServer] createSession: provider returned URI ${r.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(r=>{let o=F.provider(r.session);if(!o)throw new Error(`Agent session URI has no provider scheme: ${r.session.toString()}`);let s=r.status??1;return r.isRead&&(s|=32),r.isArchived&&(s|=64),{resource:r.session.toString(),provider:o,title:r.summary??"Session",status:s,activity:r.activity,createdAt:r.startTime,modifiedAt:r.modifiedTime,...r.project?{project:{uri:r.project.uri.toString(),displayName:r.project.displayName}}:{},model:r.model,workingDirectory:r.workingDirectory?.toString(),changes:r.changes}})}),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 r=this._stateManager.getSessionState(n.channel);if(!r)throw new D(At,`Session not found: ${n.channel}`);let o=r.turns,s=Math.min(n.limit??50,100),a=o.length;if(n.before){let d=o.findIndex(c=>c.id===n.before);d!==-1&&(a=d)}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 D(on,`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)=>this._agentService.invokeChangesetOperation(n)};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>OL&&this._replayBuffer.shift(),this._broadcastAction(l),(l.action.type==="session/toolCallStart"||l.action.type==="session/toolCallReady")&&this._checkOrphanedClientToolCalls(l.channel)})),this._register(this._stateManager.onDidEmitNotification(l=>{this._broadcastNotification(l)})),this._register(this._agentService.onMcpNotification(l=>{this._broadcastMcpNotification(l)})),this._config.otlpLogEmitter&&this._register(this._config.otlpLogEmitter.onDidLog(l=>this._broadcastOtlpLog(l)))}_handleNewConnection(e){let n=new z,r;n.add(e.onMessage(o=>{if(gI(o)){if(this._logService.trace(`[ProtocolServer] request: method=${o.method} id=${o.id}`),o.method==="ping"){e.send(lo(o.id,null));return}if(!r&&o.method==="initialize"){try{let s=this._handleInitialize(o.params,e,n);r=s.client,e.send(lo(o.id,s.response))}catch(s){e.send(co(o.id,s))}return}if(!r&&o.method==="reconnect"){let s;try{let a=this._handleReconnect(o.params,e,n);r=a.client,s=a.responsePromise}catch(a){e.send(co(o.id,a));return}s.then(a=>e.send(lo(o.id,a)),a=>e.send(co(o.id,a)));return}if(o.method===By){this._handleVscodeUpgrade(o.id,e);return}if(!r)return;this._handleRequest(r,o.method,o.params,o.id)}else if(mI(o))switch(this._logService.trace(`[ProtocolServer] notification: method=${o.method}`),o.method){case"unsubscribe":r&&this._removeSubscription(r,o.params.channel);break;case"dispatchAction":if(r){this._logService.trace(`[ProtocolServer] dispatchAction: ${JSON.stringify(o.params.action.type)}`);let s=o.params.action,a=o.params.channel;(Ic(s)||_c(s)||s.type==="root/configChanged")&&this._agentService.dispatchAction(a,s,r.clientId,o.params.clientSeq)}break}else if(Hy(o)){let s=this._pendingReverseRequests.get(o.id);s&&(this._pendingReverseRequests.delete(o.id),ye(o,{error:!0})?s.reject(new D(o.error?.code??-32e3,o.error?.message??"Reverse RPC error",o.error?.data)):s.resolve(o.result))}})),n.add(e.onClose(()=>{let o=r?this._clients.get(r.clientId):void 0;if(r&&o&&o.connection===r){this._logService.info(`[ProtocolServer] Client disconnected: ${r.clientId}, subscriptions=${r.subscriptions.size}`);for(let s of r.subscriptions.values())s.kind==="state"?this._agentService.unsubscribe(y.parse(s.uri),r.clientId):s.kind==="resource-watch"&&this._agentService.onResourceWatchUnsubscribed(s.uri);r.subscriptions.clear(),o.connection=void 0,o.lastSeenAt=Date.now(),this._rejectPendingReverseRequests(r.clientId),this._handleClientDisconnected(r.clientId),this._onDidChangeConnectionCount.fire(this._connectedClientCount)}n.dispose()})),n.add(e)}_handleInitialize(e,n,r){let o=Array.isArray(e.protocolVersions)?e.protocolVersions:[];this._logService.info(`[ProtocolServer] Initialize: clientId=${e.clientId}, protocolVersions=[${o.join(", ")}]`);let s=Y1(o,fa);if(!s){let c={supportedVersions:[`^${fa}`],_meta:bf()?{vscodeUpgradeMethod:By}:void 0};throw new D(fI,`Client offered protocol versions [${o.join(", ")}], none of which are compatible with this server's version ${fa} (server accepts ^${fa}).`,c)}let a={clientId:e.clientId,protocolVersion:s,transport:n,subscriptions:new Map,disposables:r},l=this._ensureClientRecord(e.clientId);l.connection=a,l.lastSeenAt=Date.now(),this._pruneClientRecords(),this._onDidChangeConnectionCount.fire(this._connectedClientCount),this._registerClientFileSystemAuthority(e.clientId,r);let d=[];if(e.initialSubscriptions)for(let c of e.initialSubscriptions){let u=this._addInitialSubscription(a,c.toString());u&&d.push(u)}return{client:a,response:{protocolVersion:s,serverSeq:this._stateManager.serverSeq,snapshots:d,defaultDirectory:this._config.defaultDirectory,completionTriggerCharacters:this._config.completionTriggerCharacters,telemetry:this._config.otlpLogEmitter?{logs:yT}:void 0}}}_addInitialSubscription(e,n){let r=If(n);if(!r)return;if(r.kind==="otlp-logs"){if(!this._config.otlpLogEmitter){this._logService.warn(`[ProtocolServer] Ignoring OTLP initialSubscription ${n}: no OTLP emitter configured.`);return}e.subscriptions.set(r.uri,r);return}let o=this._stateManager.getSnapshot(n);if(o)return e.subscriptions.set(r.uri,r),this._agentService.addSubscriber(y.parse(r.uri),e.clientId),this._clearClientToolCallDisconnectTimeout(e.clientId,r.uri),o}_handleVscodeUpgrade(e,n){let r=bf();if(!r){n.send(id(e,fe.MethodNotFound,"No upgrade supervisor is available for this agent host."));return}X1(r).then(o=>n.send(lo(e,o)),o=>{this._logService.warn(`[ProtocolServer] vscodeUpgrade signal failed: ${o instanceof Error?o.message:String(o)}`),n.send(co(e,o))})}_handleReconnect(e,n,r){this._logService.info(`[ProtocolServer] Reconnect: clientId=${e.clientId}, lastSeenSeq=${e.lastSeenServerSeq}`);let o={clientId:e.clientId,protocolVersion:fa,transport:n,subscriptions:new Map,disposables:r},s=this._ensureClientRecord(e.clientId);s.connection=o,s.lastSeenAt=Date.now(),this._pruneClientRecords(),this._onDidChangeConnectionCount.fire(this._connectedClientCount),this._registerClientFileSystemAuthority(e.clientId,r);let a=this._replayBuffer.length>0?this._replayBuffer[0].serverSeq:this._stateManager.serverSeq,l=e.lastSeenServerSeq>=a,d=this._restoreReconnectSubscriptions(o,e,l);return{client:o,responsePromise:d}}_registerClientFileSystemAuthority(e,n){n.add(this._clientFileSystemProvider.registerAuthority(e,{resourceList:r=>this._sendReverseRequest(e,"resourceList",{uri:r.toString()}),resourceRead:r=>this._sendReverseRequest(e,"resourceRead",{uri:r.toString()}),resourceWrite:r=>this._sendReverseRequest(e,"resourceWrite",r),resourceCopy:r=>this._sendReverseRequest(e,"resourceCopy",r),resourceDelete:r=>this._sendReverseRequest(e,"resourceDelete",r),resourceMove:r=>this._sendReverseRequest(e,"resourceMove",r),resourceRequest:r=>this._sendReverseRequest(e,"resourceRequest",r),resourceResolve:r=>this._sendReverseRequest(e,"resourceResolve",r),resourceMkdir:r=>this._sendReverseRequest(e,"resourceMkdir",r)}))}async _restoreReconnectSubscriptions(e,n,r){let o=[],s=await Promise.all(n.subscriptions.map(async a=>{let l=a.toString(),d=If(l);if(d){if(d.kind==="otlp-logs"){if(!this._config.otlpLogEmitter){this._logService.warn(`[ProtocolServer] Reconnect: dropping OTLP subscription ${l}: no OTLP emitter configured.`);return}e.subscriptions.set(d.uri,d);return}if(d.kind==="resource-watch"){let c=this._agentService.onResourceWatchSubscribed(d.uri);if(!c){this._logService.info(`[ProtocolServer] Reconnect: resource watch ${l} no longer parses`),o.push(a);return}return e.subscriptions.set(d.uri,d),{resource:d.uri,state:c,fromSeq:this._stateManager.serverSeq}}try{let c=await this._agentService.subscribe(y.parse(l),e.clientId);return e.subscriptions.set(d.uri,d),this._clearClientToolCallDisconnectTimeout(e.clientId,d.uri),c}catch(c){this._logService.info(`[ProtocolServer] Reconnect: failed to restore subscription ${l}: ${c instanceof Error?c.message:String(c)}`),o.push(a);return}}}));if(r){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 r=this._stateManager.getSessionState(n),o=r?this._hasPendingClientToolCall(r,e):!1;r?.activeClient?.clientId===e&&this._stateManager.dispatchServerAction(n,{type:"session/activeClientChanged",activeClient:null}),(r?.activeClient?.clientId===e||o)&&this._startClientToolCallDisconnectTimeout(e,n)}}*_pendingClientToolCalls(e){let n=e?.activeTurn;if(n)for(let r of n.responseParts){if(r.kind!=="toolCall")continue;let o=r.toolCall,s=o.contributor;s?.kind==="client"&&ML(o.status)&&(yield{toolCall:o,clientId:s.clientId})}}_hasPendingClientToolCall(e,n){for(let r of this._pendingClientToolCalls(e))if(r.clientId===n)return!0;return!1}_hasReplacementActiveClientTool(e,n,r){let o=e.activeClient;return o!==void 0&&o.clientId!==n&&o.tools.some(s=>s.name===r)}_startClientToolCallDisconnectTimeout(e,n){this._clearClientToolCallDisconnectTimeout(e,n);let r=this._ensureClientRecord(e);r.lastSeenAt===void 0&&(r.lastSeenAt=Date.now());let o=Date.now()-r.lastSeenAt,s=Math.max(0,Z1-o);r.disconnectTimeouts.set(n,$t(()=>{r.disconnectTimeouts.deleteAndDispose(n),this._completeDisconnectedClientToolCalls(e,n)},s))}_checkOrphanedClientToolCalls(e){let n=this._stateManager.getSessionState(e),r=new Set;for(let{clientId:o}of this._pendingClientToolCalls(n)){let s=this._clients.get(o);(!s||s.connection===void 0)&&r.add(o)}for(let o of r)this._startClientToolCallDisconnectTimeout(o,e)}_ensureClientRecord(e){let n=this._clients.get(e);return n||(n={connection:void 0,lastSeenAt:void 0,disconnectTimeouts:new ve},this._clients.set(e,n)),n}get _connectedClientCount(){let e=0;for(let n of this._clients.values())n.connection&&e++;return e}_pruneClientRecords(){let e=Date.now()-Z1*10;for(let[n,r]of this._clients)r.connection===void 0&&r.disconnectTimeouts.size===0&&(r.lastSeenAt===void 0||r.lastSeenAt<e)&&this._clients.delete(n)}_clearClientToolCallDisconnectTimeout(e,n){this._clients.get(e)?.disconnectTimeouts.deleteAndDispose(n)}_completeDisconnectedClientToolCalls(e,n){let r=this._stateManager.getSessionState(n),o=r?.activeTurn;if(!(!r||!o))for(let{toolCall:s,clientId:a}of this._pendingClientToolCalls(r)){if(a!==e)continue;let l=this._hasReplacementActiveClientTool(r,e,s.toolName);s.status==="streaming"&&this._stateManager.dispatchServerAction(n,{type:"session/toolCallReady",turnId:o.id,toolCallId:s.toolCallId,invocationMessage:s.invocationMessage??s.displayName,confirmed:"not-needed"}),this._stateManager.dispatchServerAction(n,{type:"session/toolCallComplete",turnId:o.id,toolCallId:s.toolCallId,result:{success:!1,pastTenseMessage:`${s.displayName} failed`,...l?{content:[{type:"text",text:`The client that was running ${s.displayName} disconnected, but another active client now provides ${s.displayName}. You may try calling the tool again.`}]}:{},error:{message:`Client ${e} disconnected before completing ${s.displayName}`}}})}}_sendReverseRequest(e,n,r){let o=this._clients.get(e)?.connection;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 d={jsonrpc:"2.0",id:s,method:n,params:r};o.transport.send(d)})}_rejectPendingReverseRequests(e){for(let[n,r]of this._pendingReverseRequests)r.clientId===e&&(this._pendingReverseRequests.delete(n),r.reject(new Error(`Client ${e} disconnected`)))}_handleRequest(e,n,r,o){let s=this._requestHandlers.hasOwnProperty(n)?this._requestHandlers[n]:void 0;if(s){s(e,r).then(d=>{this._logService.trace(`[ProtocolServer] Request '${n}' id=${o} succeeded`),e.transport.send(lo(o,d??null))}).catch(d=>{this._logService.error(`[ProtocolServer] Request '${n}' failed`,d),e.transport.send(co(o,d))});return}let a=this._handleExtensionRequest(n,r);if(a){a.then(d=>{e.transport.send(lo(o,d??null))}).catch(d=>{this._logService.error(`[ProtocolServer] Extension request '${n}' failed`,d),e.transport.send(co(o,d))});return}let l=LL(r);if(l!==void 0){let d=ew(r)?r:void 0;this._agentService.handleMcpRequest(l,n,d).then(c=>{e.transport.send(lo(o,c??null))}).catch(c=>{if(c instanceof Error&&c.message.startsWith("Method not found")){e.transport.send(id(o,fe.MethodNotFound,c.message));return}this._logService.error(`[ProtocolServer] mcp:// request '${n}' on ${l} failed`,c),e.transport.send(co(o,c))});return}e.transport.send(id(o,Jo,`Unknown method: ${n}`))}_handleExtensionRequest(e,n){if(e==="shutdown")return this._agentService.shutdown()}_broadcastAction(e){this._logService.trace(`[ProtocolServer] Broadcasting action: ${e.action.type}`);let n={jsonrpc:"2.0",method:"action",params:e};for(let r of this._clients.values()){let o=r.connection;o&&this._isRelevantToClient(o,e)&&o.transport.send(n)}}_broadcastNotification(e){let{type:n,...r}=e,o={jsonrpc:"2.0",method:n,params:r};for(let s of this._clients.values())s.connection?.transport.send(o)}_broadcastMcpNotification(e){let n={...e.params??{},channel:e.channel},r={jsonrpc:"2.0",method:e.method,params:n};for(let o of this._clients.values())o.connection?.transport.send(r)}_removeSubscription(e,n){let r=If(n);if(!r)return;let o=e.subscriptions.get(r.uri);o&&(e.subscriptions.delete(r.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=bT(e);for(let r of this._clients.values()){let o=r.connection;if(o)for(let s of o.subscriptions.values()){if(s.kind!=="otlp-logs"||e.severityNumber<ST(s.level))continue;let a={jsonrpc:"2.0",method:"otlp/exportLogs",params:{channel:s.uri,payload:n}};o.transport.send(a)}}}_isRelevantToClient(e,n){if(ul(n.channel)){for(let o of e.subscriptions.values())if(o.kind==="state"&&ul(o.uri))return!0;return!1}let r=e.subscriptions.get(n.channel);return r?.kind==="state"||r?.kind==="resource-watch"}dispose(){for(let e of this._clients.values())e.connection?.disposables.dispose(),e.disconnectTimeouts.dispose();this._clients.clear();for(let[,e]of this._pendingReverseRequests)e.reject(new Error("ProtocolServerHandler disposed"));this._pendingReverseRequests.clear(),this._replayBuffer.length=0,super.dispose()}};uo=x([C(5,O)],uo);var NL="ahp",UL=75*1024*1024,FL=5,WL=1024*1024,$L=1024*1024,HL=16*1024,ga=class extends T{constructor(e,n,r){super();this._options=e;this._fileService=n;this._logService=r;this._currentSize=0;this._segment=0;this._queue=Promise.resolve();this._pending=[];this._drainScheduled=!1;this._directory=X(this._options.logsHome,NL);let o=zL(this._options.connectionId).slice(0,64);this._baseName=`ahp-${VL(new Date)}-${o}.jsonl`,this._maxFileSizeBytes=this._options.maxFileSizeBytes??UL,this._maxFiles=this._options.maxFiles??FL,this._currentFile=X(this._directory,this._baseName)}get resource(){return this._currentFile}log(e,n,r){let o={ts:new Date().toISOString(),dir:n,connectionId:this._options.connectionId,transport:this._options.transport,...typeof r=="number"?{byteLength:r}:{}},s={...e,_ahpLog:o},a=qL(s);a.length>$L&&(o.truncated=!0,a=BL(s,HL));let l=`${a}
`;this._pending.push(A.fromString(l)),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=[],r=0,o=async()=>{if(n.length===0)return;let s=n.length===1?n[0]:A.concat(n,r);await this._fileService.writeFile(this._currentFile,s,{append:!0}),this._currentSize+=s.byteLength,n=[],r=0};for(let s of e){let a=this._currentSize+r;a>0&&a+s.byteLength>this._maxFileSizeBytes?(await o(),await this._rotate()):r>0&&r+s.byteLength>WL&&await o(),n.push(s),r+=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 X(this._directory,this._baseName);let n=this._baseName.slice(0,-6);return X(this._directory,`${n}.${e}.jsonl`)}async _getFileSize(e){try{return(await this._fileService.resolve(e)).size??0}catch{return 0}}};ga=x([C(1,Te),C(2,O)],ga);function Vy(i){return A.fromString(i).byteLength}function qL(i){return JSON.stringify(i,tw)}function BL(i,t){return JSON.stringify(i,function(e,n){let r=tw.call(this,e,n);return typeof r=="string"&&r.length>t?`${r.slice(0,t)}\u2026[${r.length-t} more chars elided]`:r})}function tw(i,t){return t&&typeof t=="object"&&t.$mid===1&&yS(t)?y.revive(t).toString():t}function VL(i){return i.toISOString().replace(/[:.]/g,"-")}function zL(i){return i.replace(/[\\/:\*\?"<>\|\s]+/g,"-").replace(/^-+|-+$/g,"")||"connection"}var zy=class extends T{constructor(e,n,r){super();this._ws=e;this._WebSocket=n;this._ahpLogger=r;this._onMessage=this._register(new w);this.onMessage=this._onMessage.event;this._onClose=this._register(new w);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",Vy(s)),this._onMessage.fire(a)}catch{this.send({jsonrpc:"2.0",id:null,error:{code:uI,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",Vy(n)),this._ws.send(n)}}dispose(){this._ws.close(),super.dispose()}},od=class i extends T{constructor(e,n,r,o,s,a){super();this._logService=n;this._ahpLogOptions=r;this._connectionCount=0;this._onConnection=this._register(new w);this.onConnection=this._onConnection.event;this._WebSocket=o.WebSocket;let l=typeof e=="number"?{port:e}:e,d=l.host??"127.0.0.1",c=l.connectionTokenValidate?(u,p)=>{let h=a.parse(u.req.url??"",!0).query[Tg];if(!l.connectionTokenValidate(h)){this._logService.warn("[WebSocketProtocol] Connection rejected: invalid connection token"),p(!1,403,"Forbidden");return}p(!0)}:void 0;if(l.socketPath){this._httpServer=s.createServer(),this._wss=new o.WebSocketServer({server:this._httpServer,verifyClient:c});let u=this._httpServer;this.whenListening=new Promise((p,m)=>{u.once("listening",()=>{this._logService.info(`[WebSocketProtocol] Server listening on socket ${l.socketPath}`),p()}),u.once("error",m)}),this._httpServer.listen(l.socketPath)}else{this._wss=new o.WebSocketServer({port:l.port,host:d,verifyClient:c});let u=this._wss;this.whenListening=new Promise((p,m)=>{u.once("listening",()=>{let h=u.address(),v=!h||typeof h=="string"?`${d}:${l.port}`:`${h.address}:${h.port}`;this._logService.info(`[WebSocketProtocol] Server listening on ${v}`),p()}),u.once("error",m)})}this._wss.on("connection",u=>{this._logService.trace("[WebSocketProtocol] New client connection");let p=new zy(u,this._WebSocket,this._createAhpLogger());this._onConnection.fire(p)}),this._wss.on("error",u=>{this._logService.error("[WebSocketProtocol] Server error",u)})}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,r){let[o,s,a]=await Promise.all([import("ws"),import("http"),import("url")]);return new i(e,n,r,o,s,a)}_createAhpLogger(){if(this._ahpLogOptions)return this._ahpLogOptions.instantiationService.createInstance(ga,{logsHome:this._ahpLogOptions.logsHome,connectionId:`agent-host-${++this._connectionCount}-${N()}`,transport:"websocket"})}dispose(){this._wss.close(),this._httpServer?.close(),super.dispose()}};import{homedir as XL,tmpdir as ZL}from"os";var nw=/^([^.]+\..+)[:=](.+)$/,de=class{constructor(t,e,n){this._args=t;this.paths=e;this.productService=n}get appRoot(){return se(dt.asFileUri("").fsPath)}get userHome(){return y.file(this.paths.homeDir)}get userDataPath(){return this.paths.userDataDir}get appSettingsHome(){return y.file(W(this.userDataPath,"User"))}get tmpDir(){return y.file(this.paths.tmpDir)}get cacheHome(){return y.file(this.userDataPath)}get stateResource(){return X(this.appSettingsHome,"globalStorage","storage.json")}get userRoamingDataHome(){return this.appSettingsHome.with({scheme:ie.vscodeUserData})}get userDataSyncHome(){return X(this.appSettingsHome,"sync")}get logsHome(){if(!this.args.logsPath){let t=RC(new Date).replace(/-|:|\.\d+Z$/g,"");this.args.logsPath=W(this.userDataPath,"logs",t)}return y.file(this.args.logsPath)}get sync(){return this.args.sync}get workspaceStorageHome(){return X(this.appSettingsHome,"workspaceStorage")}get localHistoryHome(){return X(this.appSettingsHome,"History")}get keyboardLayoutResource(){return X(this.userRoamingDataHome,"keyboardLayout.json")}get argvResource(){let t=Fe.VSCODE_PORTABLE;return t?y.file(W(t,"argv.json")):X(this.appSettingsHome,"argv.json")}get isExtensionDevelopment(){return!!this.args.extensionDevelopmentPath}get untitledWorkspacesHome(){return y.file(W(this.userDataPath,"Workspaces"))}get builtinExtensionsPath(){let t=this.args["builtin-extensions-dir"];return t?dn(t):Ft(W(dt.asFileUri("").fsPath,"..","extensions"))}get extensionsDownloadLocation(){let t=this.args["extensions-download-dir"];return t?y.file(dn(t)):y.file(W(this.userDataPath,"CachedExtensionVSIXs"))}get extensionsPath(){let t=this.args["extensions-dir"];if(t)return dn(t);let e=Fe.VSCODE_EXTENSIONS;if(e)return e;let n=Fe.VSCODE_PORTABLE;return n?W(n,"extensions"):X(this.userHome,this.productService.dataFolderName,"extensions").fsPath}get appSharedDataHome(){let t=this.args["shared-data-dir"];if(t)return y.file(dn(t));let e=Fe.VSCODE_PORTABLE;return e?y.file(W(e,"shared-data")):X(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(Ft(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(Ft(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=Fe.VSCODE_SKIP_BUILTIN_EXTENSIONS;return t?t.split(",").map(e=>e.trim()).filter(e=>e):[]}get debugExtensionHost(){return jL(this.args,this.isBuilt)}get debugRenderer(){return!!this.args.debugRenderer}get isBuilt(){return!Fe.VSCODE_DEV}get verbose(){return!!this.args.verbose}get logLevel(){return this.args.log?.find(t=>!nw.test(t))}get extensionLogLevel(){let t=[];for(let e of this.args.log||[]){let n=nw.exec(e);n?.[1]&&n[2]&&t.push([n[1],n[2]])}return t.length?t:void 0}get serviceMachineIdResource(){return X(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=Fe.VSCODE_PORTABLE;return t?y.file(W(t,"policy.json")):X(this.userHome,this.productService.dataFolderName,"policy.json")}}get agentSessionsWorkspace(){return X(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}};x([ce],de.prototype,"appRoot",1),x([ce],de.prototype,"userHome",1),x([ce],de.prototype,"userDataPath",1),x([ce],de.prototype,"appSettingsHome",1),x([ce],de.prototype,"tmpDir",1),x([ce],de.prototype,"cacheHome",1),x([ce],de.prototype,"stateResource",1),x([ce],de.prototype,"userRoamingDataHome",1),x([ce],de.prototype,"userDataSyncHome",1),x([ce],de.prototype,"sync",1),x([ce],de.prototype,"workspaceStorageHome",1),x([ce],de.prototype,"localHistoryHome",1),x([ce],de.prototype,"keyboardLayoutResource",1),x([ce],de.prototype,"argvResource",1),x([ce],de.prototype,"isExtensionDevelopment",1),x([ce],de.prototype,"untitledWorkspacesHome",1),x([ce],de.prototype,"builtinExtensionsPath",1),x([ce],de.prototype,"extensionsDownloadLocation",1),x([ce],de.prototype,"extensionsPath",1),x([ce],de.prototype,"appSharedDataHome",1),x([ce],de.prototype,"extensionDevelopmentLocationURI",1),x([ce],de.prototype,"extensionDevelopmentKind",1),x([ce],de.prototype,"extensionTestsLocationURI",1),x([ce],de.prototype,"debugExtensionHost",1),x([ce],de.prototype,"logLevel",1),x([ce],de.prototype,"extensionLogLevel",1),x([ce],de.prototype,"serviceMachineIdResource",1),x([ce],de.prototype,"disableTelemetry",1),x([ce],de.prototype,"disableExperiments",1),x([ce],de.prototype,"disableWorkspaceTrust",1),x([ce],de.prototype,"useInMemorySecretStorage",1),x([ce],de.prototype,"policyFile",1),x([ce],de.prototype,"agentSessionsWorkspace",1);function jL(i,t){return rw(i["inspect-extensions"],i["inspect-brk-extensions"],5870,t,i.debugId,i.extensionEnvironment)}function rw(i,t,e,n,r,o){let a=Number(t||i)||(n?null:e),l=a?!!t:!1,d;if(o)try{d=JSON.parse(o)}catch{}return{port:a,break:l,debugId:r,env:d}}import{homedir as iw}from"os";import{resolve as KL,isAbsolute as GL,join as ma}from"path";var JL=process.env.VSCODE_CWD||process.cwd();function ow(i,t){let e=YL(i,t),n=[e];return GL(e)||n.unshift(JL),KL(...n)}function YL(i,t){process.env.VSCODE_DEV&&(t="code-oss-dev");let e=process.env.VSCODE_PORTABLE;if(e)return ma(e,"user-data");let n=process.env.VSCODE_APPDATA;if(n)return ma(n,t);let r=i["user-data-dir"];return r||QL(t)}function QL(i){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=ma(e,"AppData","Roaming")}break;case"darwin":t=ma(iw(),"Library","Application Support");break;case"linux":t=process.env.XDG_CONFIG_HOME||ma(iw(),".config");break;default:throw new Error("Platform not supported")}return ma(t,i)}var _f=class extends de{constructor(t,e){let n=XL();super(t,{homeDir:n,tmpDir:ZL(),userDataDir:ow(t,e.nameShort)},e)}};import eN from"minimist";var lve={o:g(2298,null),e:g(2282,null),t:g(2312,null),m:g(2293,null)};var jy={chat:{type:"subcommand",description:"Pass in a prompt to run in a chat session in the current working directory.",options:{_:{type:"string[]",description:g(2302,null)},mode:{type:"string",cat:"o",alias:"m",args:"mode",description:g(2269,null)},"add-file":{type:"string[]",cat:"o",alias:"a",args:"path",description:g(2264,null)},maximize:{type:"boolean",cat:"o",description:g(2268,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:g(2305,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:g(2296,null)},profile:{type:"string",cat:"o",args:"profileName",description:g(2301,null)},help:{type:"boolean",alias:"h",description:g(2284,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(2270,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(2270,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(2270,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(2274,null)},merge:{type:"boolean",cat:"o",alias:"m",args:["path1","path2","base","result"],description:g(2294,null)},add:{type:"boolean",cat:"o",alias:"a",args:"folder",description:g(2263,null)},remove:{type:"boolean",cat:"o",args:"folder",description:g(2303,null)},goto:{type:"boolean",cat:"o",alias:"g",args:"file:line[:character]",description:g(2283,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:g(2295,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:g(2304,null)},agents:{type:"boolean",cat:"o",deprecates:["sessions"],description:g(2266,null)},wait:{type:"boolean",cat:"o",alias:"w",description:g(2322,null)},waitMarkerFilePath:{type:"string"},locale:{type:"string",cat:"o",args:"locale",description:g(2290,null)},"user-data-dir":{type:"string",cat:"o",args:"dir",description:g(2319,null)},profile:{type:"string",cat:"o",args:"profileName",description:g(2301,null)},help:{type:"boolean",cat:"o",alias:"h",description:g(2284,null)},"stdin-to-clipboard":{type:"boolean",cat:"o",alias:"c",description:g(2271,null)},"extensions-dir":{type:"string",deprecates:["extensionHomePath"],cat:"e",args:"dir",description:g(2281,null)},"extensions-download-dir":{type:"string"},"builtin-extensions-dir":{type:"string"},"shared-data-dir":{type:"string"},"list-extensions":{type:"boolean",cat:"e",description:g(2289,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(2306,null)},category:{type:"string",allowEmptyValue:!0,cat:"e",description:g(2267,null),args:"category"},"install-extension":{type:"string[]",cat:"e",args:"ext-id | path",description:g(2288,null)},"pre-release":{type:"boolean",cat:"e",description:g(2287,null)},"uninstall-extension":{type:"string[]",cat:"e",args:"ext-id",description:g(2314,null)},"update-extensions":{type:"boolean",cat:"e",description:g(2317,null)},"enable-proposed-api":{type:"string[]",allowEmptyValue:!0,cat:"e",args:"ext-id",description:g(2280,null)},"add-mcp":{type:"string[]",cat:"m",args:"json",description:g(2265,null)},version:{type:"boolean",cat:"t",alias:"v",description:g(2321,null)},verbose:{type:"boolean",cat:"t",global:!0,description:g(2320,null)},log:{type:"string[]",cat:"t",args:"level",global:!0,description:g(2292,null)},status:{type:"boolean",alias:"s",cat:"t",description:g(2307,null)},"prof-startup":{type:"boolean",cat:"t",description:g(2300,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(2277,null)},"disable-extension":{type:"string[]",cat:"t",args:"ext-id",description:g(2276,null)},sync:{type:"string",cat:"t",description:g(2313,null),args:["on | off"]},"inspect-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugPluginHost"],args:"port",cat:"t",description:g(2286,null)},"inspect-brk-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugBrkPluginHost"],args:"port",cat:"t",description:g(2285,null)},"disable-lcd-text":{type:"boolean",cat:"t",description:g(2279,null)},"disable-gpu":{type:"boolean",cat:"t",description:g(2278,null)},"disable-chromium-sandbox":{type:"boolean",cat:"t",description:g(2275,null)},sandbox:{type:"boolean"},"locate-shell-integration-path":{type:"string",cat:"t",args:["shell"],description:g(2291,null)},telemetry:{type:"boolean",cat:"t",description:g(2310,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(2311,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[]"}},tN={onUnknownOption:()=>{},onMultipleValues:()=>{},onEmptyValue:()=>{},onDeprecatedOption:()=>{}};function Cf(i,t,e=tN){let n=i.find((p,m)=>p.length>0&&p[0]!=="-"&&t.hasOwnProperty(p)&&t[p].type==="subcommand"),r={},o=["_"],s=[],a={},l;for(let p in t){let m=t[p];m.type==="subcommand"?p===n&&(l=m):(m.alias&&(r[p]=m.alias),m.type==="string"||m.type==="string[]"?(o.push(p),m.deprecates&&o.push(...m.deprecates)):m.type==="boolean"&&(s.push(p),m.deprecates&&s.push(...m.deprecates)),m.global&&(a[p]=m))}if(l&&n){let p=a;for(let I in l.options)p[I]=l.options[I];let m=i.filter(I=>I!==n),h=e.getSubcommandReporter?e.getSubcommandReporter(n):void 0,v=Cf(m,p,h);return{[n]:v,_:[]}}let d=eN(i,{string:o,boolean:s,alias:r}),c={},u=d;c._=d._.map(p=>String(p)).filter(p=>p.length>0),delete u._;for(let p in t){let m=t[p];if(m.type==="subcommand")continue;m.alias&&delete u[m.alias];let h=u[p];if(m.deprecates)for(let v of m.deprecates)u.hasOwnProperty(v)&&(h||(h=u[v],h&&e.onDeprecatedOption(v,m.deprecationMessage||g(2273,null,p))),delete u[v]);if(typeof h<"u"){if(m.type==="string[]"){if(Array.isArray(h)||(h=[h]),!m.allowEmptyValue){let v=h.filter(I=>I.length>0);v.length!==h.length&&(e.onEmptyValue(p),h=v.length>0?v:void 0)}}else m.type==="string"&&(Array.isArray(h)?(h=h.pop(),e.onMultipleValues(p,h)):!h&&!m.allowEmptyValue&&(e.onEmptyValue(p),h=void 0));c[p]=h,m.deprecationMessage&&e.onDeprecatedOption(p,m.deprecationMessage)}delete u[p]}for(let p in u)e.onUnknownOption(p);return c}var Tf=class extends T{constructor(t,e=[]){super(),this.logger=new mc([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 nN(i,t,e,n,r){try{let o=await import("@vscode/spdlog");o.setFlushOn(0);let s=await o.createAsyncRotatingLogger(i,t,e,n);return r?s.clearFormatters():s.setPattern("%Y-%m-%d %H:%M:%S.%e [%l] %v"),s}catch(o){console.error(o)}return null}function sw(i,t,e){switch(t){case 1:i.trace(e);break;case 2:i.debug(e);break;case 3:i.info(e);break;case 4:i.warn(e);break;case 5:i.error(e);break;case 0:break;default:throw new Error(`Invalid log level ${t}`)}}function aw(i,t){switch(t){case 1:i.setLevel(0);break;case 2:i.setLevel(1);break;case 3:i.setLevel(2);break;case 4:i.setLevel(3);break;case 5:i.setLevel(4);break;case 0:i.setLevel(6);break;default:throw new Error(`Invalid log level ${t}`)}}var xf=class extends Gi{constructor(e,n,r,o,s){super();this.buffer=[];this.setLevel(s),this._loggerCreationPromise=this._createSpdLogLogger(e,n,r,o),this._register(this.onDidChangeLogLevel(a=>{this._logger&&aw(this._logger,a)}))}async _createSpdLogLogger(e,n,r,o){let s=r?6:1,a=30/s*ic.MB,l=await nN(e,n,a,s,o);if(l){this._logger=l,aw(this._logger,this.getLevel());for(let{level:d,message:c}of this.buffer)sw(this._logger,d,c);this.buffer=[]}}log(e,n){this._logger?sw(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 wf=class extends ll{doCreateLogger(t,e,n){return new xf(N(),t.fsPath,!n?.donotRotate,!!n?.donotUseFormatters,e)}};var Rf=class{constructor(t,e){this.loggerService=t;this.getUriTransformer=e}listen(t,e){let n=this.getUriTransformer(t);switch(e){case"onDidChangeLoggers":return Q.map(this.loggerService.onDidChangeLoggers,r=>({added:[...r.added].map(o=>this.transformLogger(o,n)),removed:[...r.removed].map(o=>this.transformLogger(o,n))}));case"onDidChangeVisibility":return Q.map(this.loggerService.onDidChangeVisibility,r=>[n.transformOutgoingURI(r[0]),r[1]]);case"onDidChangeLogLevel":return Q.map(this.loggerService.onDidChangeLogLevel,r=>mm(r)?r:[n.transformOutgoingURI(r[0]),r[1]])}throw new Error(`Event not found: ${e}`)}async call(t,e,n){let r=this.getUriTransformer(t);switch(e){case"setLogLevel":return mm(n[0])?this.loggerService.setLogLevel(n[0]):this.loggerService.setLogLevel(y.revive(r.transformIncoming(n[0][0])),n[0][1]);case"getRegisteredLoggers":return Promise.resolve([...this.loggerService.getRegisteredLoggers()].map(o=>this.transformLogger(o,r)))}throw new Error(`Call not found: ${e}`)}transformLogger(t,e){return{...t,resource:e.transformOutgoingURI(t.resource)}}};var lw=new class{transformIncoming(i){return i}transformOutgoing(i){return i}transformOutgoingURI(i){return i}transformOutgoingScheme(i){return i}};function Ky(i){let t=[];typeof i=="number"&&t.push("code/timeOrigin",i);function e(o,s){t.push(o,s?.startTime??Date.now())}function n(){let o=[];for(let s=0;s<t.length;s+=2)o.push({name:t[s],startTime:t[s+1]});return o}function r(o){if(typeof o>"u"){let s=t.length>=2&&t[0]==="code/timeOrigin",a=s?t[1]:void 0;t.length=0,s&&t.push("code/timeOrigin",a)}else for(let s=t.length-2;s>=0;s-=2)t[s]===o&&t.splice(s,2)}return{mark:e,getMarks:n,clearMarks:r}}function rN(){if(typeof performance=="object"&&typeof performance.mark=="function"&&!performance.nodeTiming)return typeof performance.timeOrigin!="number"&&!performance.timing?Ky():{mark(i,t){performance.mark(i,t)},clearMarks(i){performance.clearMarks(i)},getMarks(){let i=performance.timeOrigin;typeof i!="number"&&(i=(performance.timing.navigationStart||performance.timing.redirectStart||performance.timing.fetchStart)??0);let t=[{name:"code/timeOrigin",startTime:Math.round(i)}];for(let e of performance.getEntriesByType("mark"))t.push({name:e.name,startTime:Math.round(i+e.startTime)});return t}};if(typeof process=="object"){let i=performance?.timeOrigin;return Ky(i)}else return console.trace("perf-util loaded in UNKNOWN environment"),Ky()}function iN(i){return i.MonacoPerformanceMarks||(i.MonacoPerformanceMarks=rN()),i.MonacoPerformanceMarks}var Gy=iN(globalThis),dw=Gy.mark,jve=Gy.clearMarks,Kve=Gy.getMarks;async function Ef(i,t,e,n,r,o){let s;try{await oN(i,t,e,n,r,o)}catch(a){s=a}finally{s&&r.errorTransformer&&(s=r.errorTransformer(s)),typeof s<"u"&&e.error(s),e.end()}}async function oN(i,t,e,n,r,o){Jy(o);let s=await i.open(t,{create:!1});try{Jy(o);let a=0,l=0,d=r&&typeof r.length=="number"?r.length:void 0,c=A.alloc(Math.min(r.bufferSize,typeof d=="number"?d:r.bufferSize)),u=r&&typeof r.position=="number"?r.position:0,p=0;do l=await i.read(s,u,c.buffer,p,c.byteLength-p),u+=l,p+=l,a+=l,typeof d=="number"&&(d-=l),p===c.byteLength&&(await e.write(n(c)),c=A.alloc(Math.min(r.bufferSize,typeof d=="number"?d:r.bufferSize)),p=0);while(l>0&&(typeof d!="number"||d>0)&&Jy(o)&&sN(a,r));if(p>0){let m=p;typeof d=="number"&&(m=Math.min(p,d)),e.write(n(c.slice(0,m)))}}catch(a){throw br(a)}finally{await i.close(s)}}function Jy(i){if(i.isCancellationRequested)throw cd();return!0}function sN(i,t){if(typeof t?.limits?.size=="number"&&i>t.limits.size)throw he(g(2484,null),"EntryTooLarge");return!0}var xi=class extends T{constructor(e){super();this.logService=e;this.BUFFER_SIZE=256*1024;this._onDidChangeFileSystemProviderRegistrations=this._register(new w);this.onDidChangeFileSystemProviderRegistrations=this._onDidChangeFileSystemProviderRegistrations.event;this._onWillActivateFileSystemProvider=this._register(new w);this.onWillActivateFileSystemProvider=this._onWillActivateFileSystemProvider.event;this._onDidChangeFileSystemProviderCapabilities=this._register(new w);this.onDidChangeFileSystemProviderCapabilities=this._onDidChangeFileSystemProviderCapabilities.event;this.provider=new Map;this._onDidRunOperation=this._register(new w);this.onDidRunOperation=this._onDidRunOperation.event;this.internalOnDidFilesChange=this._register(new w);this._onDidUncorrelatedFilesChange=this._register(new w);this.onDidFilesChange=this._onDidUncorrelatedFilesChange.event;this._onDidWatchError=this._register(new w);this.onDidWatchError=this._onDidWatchError.event;this.activeWatchers=new Map;this.writeQueue=this._register(new Ao)}registerProvider(e,n){if(this.provider.has(e))throw new Error(`A filesystem provider for the scheme '${e}' is already registered.`);dw(`code/registerFilesystem/${e}`);let r=new z;return this.provider.set(e,n),this._onDidChangeFileSystemProviderRegistrations.fire({added:!0,scheme:e,provider:n}),r.add(n.onDidChangeFile(o=>{let s=new rc(o,!this.isPathCaseSensitive(n));this.internalOnDidFilesChange.fire(s),s.hasCorrelation()||this._onDidUncorrelatedFilesChange.fire(s)})),typeof n.onDidWatchError=="function"&&r.add(n.onDidWatchError(o=>this._onDidWatchError.fire(new Error(o)))),r.add(n.onDidChangeCapabilities(()=>this._onDidChangeFileSystemProviderCapabilities.fire({provider:n,scheme:e}))),k(()=>{this._onDidChangeFileSystemProviderRegistrations.fire({added:!1,scheme:e,provider:n}),this.provider.delete(e),Tt(r)})}getProvider(e){return this.provider.get(e)}async activateProvider(e){let n=[];this._onWillActivateFileSystemProvider.fire({scheme:e,join(r){n.push(r)}}),!this.provider.has(e)&&await Cn.settled(n)}async canHandleResource(e){return await this.activateProvider(e.scheme),this.hasProvider(e)}hasProvider(e){return this.provider.has(e.scheme)}hasCapability(e,n){let r=this.provider.get(e.scheme);return!!(r&&r.capabilities&n)}listCapabilities(){return ho.map(this.provider,([e,n])=>({scheme:e,capabilities:n.capabilities}))}async withProvider(e){if(!xS(e))throw new Ke(g(2473,null,this.resourceForError(e)),8);await this.activateProvider(e.scheme);let n=this.provider.get(e.scheme);if(!n){let r=new Dn;throw r.message=g(2475,null,e.toString()),r}return n}async withReadProvider(e){let n=await this.withProvider(e);if(Sr(n)||nn(n)||oc(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(Sr(n)||nn(n))return n;throw new Error(`Filesystem provider for scheme '${e.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`)}async resolve(e,n){try{return await this.doResolveFile(e,n)}catch(r){throw qt(r)==="EntryNotFound"?new Ke(g(2470,null,this.resourceForError(e)),1):br(r)}}async doResolveFile(e,n){let r=await this.withProvider(e),o=this.isPathCaseSensitive(r),s=n?.resolveTo,a=n?.resolveSingleChildDescendants,l=n?.resolveMetadata,d=await r.stat(e),c;return this.toFileStat(r,e,d,void 0,!!l,(u,p)=>(c||(c=Fn.forUris(()=>!o),c.set(e,!0),s&&c.fill(!0,s)),c.get(u.resource)||c.findSuperstr(u.resource.with({query:null,fragment:null}))?!0:u.isDirectory&&a?p===1:!1))}async toFileStat(e,n,r,o,s,a){let{providerExtUri:l}=this.getExtUri(e),d={resource:n,name:l.basename(n),isFile:(r.type&1)!==0,isDirectory:(r.type&2)!==0,isSymbolicLink:(r.type&64)!==0,mtime:r.mtime,ctime:r.ctime,size:r.size,readonly:!!((r.permissions??0)&1)||!!(e.capabilities&2048),locked:!!((r.permissions??0)&2),executable:!!((r.permissions??0)&4),etag:am({mtime:r.mtime,size:r.size}),children:void 0};if(d.isDirectory&&a(d,o)){try{let c=await e.readdir(n),u=await Cn.settled(c.map(async([p,m])=>{try{let h=l.joinPath(n,p),v=s?await e.stat(h):{type:m};return await this.toFileStat(e,h,v,c.length,s,a)}catch(h){return this.logService.trace(h),null}}));d.children=Wr(u)}catch(c){this.logService.trace(c),d.children=[]}return d}return d}async resolveAll(e){return Cn.settled(e.map(async n=>{try{return{stat:await this.doResolveFile(n.resource,n.options),success:!0}}catch(r){return this.logService.trace(r),{stat:void 0,success:!1}}}))}async stat(e){let n=await this.withProvider(e),r=await n.stat(e);return this.toFileStat(n,e,r,void 0,!0,()=>!1)}async realpath(e){let n=await this.withProvider(e);if(Fb(n)){let r=await n.realpath(e);return e.with({path:r})}}async exists(e){let n=await this.withProvider(e);try{return!!await n.stat(e)}catch{return!1}}async canCreateFile(e,n){try{await this.doValidateCreateFile(e,n)}catch(r){return r}return!0}async doValidateCreateFile(e,n){if(!n?.overwrite&&await this.exists(e))throw new Ke(g(2466,null,this.resourceForError(e)),3,n)}async createFile(e,n=A.fromString(""),r){await this.doValidateCreateFile(e,r);let o=await this.writeFile(e,n);return this._onDidRunOperation.fire(new yr(e,0,o)),o}async writeFile(e,n,r){let o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),{providerExtUri:s}=this.getExtUri(o),a=r;if(sm(o)&&!a?.atomic){let l=o.enforceAtomicWriteFile?.(e);l&&(a={...r,atomic:l})}try{let{stat:l,buffer:d}=await this.validateWriteFile(o,e,n,a);l||await this.mkdirp(o,s.dirname(e)),d||(d=await this.peekBufferForWriting(o,n)),!Sr(o)||nn(o)&&d instanceof A||nn(o)&&sm(o)&&a?.atomic?await this.doWriteUnbuffered(o,e,a,d):await this.doWriteBuffered(o,e,a,d instanceof A?FS(d):d),this._onDidRunOperation.fire(new yr(e,4))}catch(l){throw new Ke(g(2465,null,this.resourceForError(e),br(l).toString()),Ja(l),a)}return this.resolve(e,{resolveMetadata:!0})}async peekBufferForWriting(e,n){let r;if(nn(e)&&!(n instanceof A))if(La(n)){let o=await OS(n,3);o.ended?r=A.concat(o.buffer):r=o}else r=DS(n,o=>A.concat(o),3);else r=n;return r}async validateWriteFile(e,n,r,o){let s=!!o?.unlock;if(s&&!(e.capabilities&8192))throw new Error(g(2483,null,this.resourceForError(n)));if(o?.append&&!Nb(e))throw new Ke(g(2462,null,this.resourceForError(n)),6);if(!!o?.atomic){if(!(e.capabilities&32768))throw new Error(g(2481,null,this.resourceForError(n)));if(!(e.capabilities&2))throw new Error(g(2482,null,this.resourceForError(n)));if(s)throw new Error(g(2480,null,this.resourceForError(n)))}let l;try{l=await e.stat(n)}catch{return Object.create(null)}if((l.type&2)!==0)throw new Ke(g(2468,null,this.resourceForError(n)),0,o);this.throwIfFileIsReadonly(n,l);let d;if(typeof o?.mtime=="number"&&typeof o.etag=="string"&&o.etag!==ac&&typeof l.mtime=="number"&&typeof l.size=="number"&&o.mtime<l.mtime&&o.etag!==am({mtime:o.mtime,size:l.size})){if(d=await this.peekBufferForWriting(e,r),d instanceof A&&d.byteLength===l.size)try{let{value:c}=await this.readFile(n,{limits:{size:l.size}});if(d.equals(c))return{stat:l,buffer:d}}catch{}throw new Ke(g(2469,null),3,o)}return{stat:l,buffer:d}}async readFile(e,n,r){let o=await this.withReadProvider(e);return n?.atomic?this.doReadFileAtomic(o,e,n,r):this.doReadFile(o,e,n,r)}async doReadFileAtomic(e,n,r,o){return new Promise((s,a)=>{this.writeQueue.queueFor(n,async()=>{try{let l=await this.doReadFile(e,n,r,o);s(l)}catch(l){a(l)}},this.getExtUri(e).providerExtUri)})}async doReadFile(e,n,r,o){let s=await this.doReadFileStream(e,n,{...r,preferUnbuffered:!0},o);return{...s,value:await Xr(s.value)}}async readFileStream(e,n,r){let o=await this.withReadProvider(e);return this.doReadFileStream(o,e,n,r)}async doReadFileStream(e,n,r,o){let s=new je(o),a=r;sc(e)&&e.enforceAtomicReadFile?.(n)&&(a={...r,atomic:!0});let l=this.validateReadFile(n,a).then(c=>c,c=>{throw s.dispose(!0),c}),d;try{return typeof a?.etag=="string"&&a.etag!==ac&&await l,a?.atomic&&sc(e)||!(Sr(e)||oc(e))||nn(e)&&a?.preferUnbuffered?d=this.readFileUnbuffered(e,n,a):oc(e)?d=this.readFileStreamed(e,n,s.token,a):d=this.readFileBuffered(e,n,s.token,a),d.on("end",()=>s.dispose()),d.on("error",()=>s.dispose()),{...await l,value:d}}catch(c){throw d&&await Nd(d),this.restoreReadError(c,n,a)}}restoreReadError(e,n,r){let o=g(2463,null,this.resourceForError(n),br(e).toString());return e instanceof jo?new jo(o,e.stat,r):e instanceof zo?new zo(o,e.fileOperationResult,e.size,e.options):new Ke(o,Ja(e),r)}readFileStreamed(e,n,r,o=Object.create(null)){let s=e.readFileStream(n,o,r);return Fd(s,{data:a=>a instanceof A?a:A.wrap(a),error:a=>this.restoreReadError(a,n,o)},a=>A.concat(a))}readFileBuffered(e,n,r,o=Object.create(null)){let s=HS();return Ef(e,n,s,a=>a,{...o,bufferSize:this.BUFFER_SIZE,errorTransformer:a=>this.restoreReadError(a,n,o)},r),s}readFileUnbuffered(e,n,r){let o=fr(s=>A.concat(s));return(async()=>{try{let s;r?.atomic&&sc(e)?s=await e.readFile(n,{atomic:!0}):s=await e.readFile(n),typeof r?.position=="number"&&(s=s.slice(r.position)),typeof r?.length=="number"&&(s=s.slice(0,r.length)),this.validateReadFileLimits(n,s.byteLength,r),o.end(A.wrap(s))}catch(s){o.error(s),o.end()}})(),o}async validateReadFile(e,n){let r=await this.resolve(e,{resolveMetadata:!0});if(r.isDirectory)throw new Ke(g(2467,null,this.resourceForError(e)),0,n);if(typeof n?.etag=="string"&&n.etag!==ac&&n.etag===r.etag)throw new jo(g(2471,null),r,n);return this.validateReadFileLimits(e,r.size,n),r}validateReadFileLimits(e,n,r){if(typeof r?.limits?.size=="number"&&n>r.limits.size)throw new zo(g(2472,null,this.resourceForError(e)),7,n,r)}async canMove(e,n,r){return this.doCanMoveCopy(e,n,"move",r)}async canCopy(e,n,r){return this.doCanMoveCopy(e,n,"copy",r)}async doCanMoveCopy(e,n,r,o){if(e.toString()!==n.toString())try{let s=r==="move"?this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e):await this.withReadProvider(e),a=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n);await this.doValidateMoveCopy(s,e,a,n,r,o)}catch(s){return s}return!0}async move(e,n,r){let o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n),a=await this.doMoveCopy(o,e,s,n,"move",!!r),l=await this.resolve(n,{resolveMetadata:!0});return this._onDidRunOperation.fire(new yr(e,a==="move"?2:3,l)),l}async copy(e,n,r){let o=await this.withReadProvider(e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n),a=await this.doMoveCopy(o,e,s,n,"copy",!!r),l=await this.resolve(n,{resolveMetadata:!0});return this._onDidRunOperation.fire(new yr(e,a==="copy"?3:2,l)),l}async doMoveCopy(e,n,r,o,s,a){if(n.toString()===o.toString())return s;let{exists:l,isSameResourceWithDifferentPathCase:d}=await this.doValidateMoveCopy(e,n,r,o,s,a);if(l&&!d&&a&&await this.del(o,{recursive:!0}),await this.mkdirp(r,this.getExtUri(r).providerExtUri.dirname(o)),s==="copy"){if(e===r&&om(e))await e.copy(n,o,{overwrite:a});else{let c=await this.resolve(n);c.isDirectory?await this.doCopyFolder(e,c,r,o):await this.doCopyFile(e,n,r,o)}return s}else return e===r?(await e.rename(n,o,{overwrite:a}),s):(await this.doMoveCopy(e,n,r,o,"copy",a),await this.del(n,{recursive:!0}),"copy")}async doCopyFile(e,n,r,o){if(Sr(e)&&Sr(r))return this.doPipeBuffered(e,n,r,o);if(Sr(e)&&nn(r))return this.doPipeBufferedToUnbuffered(e,n,r,o);if(nn(e)&&Sr(r))return this.doPipeUnbufferedToBuffered(e,n,r,o);if(nn(e)&&nn(r))return this.doPipeUnbuffered(e,n,r,o)}async doCopyFolder(e,n,r,o){await r.mkdir(o),Array.isArray(n.children)&&await Cn.settled(n.children.map(async s=>{let a=this.getExtUri(r).providerExtUri.joinPath(o,s.name);return s.isDirectory?this.doCopyFolder(e,await this.resolve(s.resource),r,a):this.doCopyFile(e,s.resource,r,a)}))}async doValidateMoveCopy(e,n,r,o,s,a){let l=!1;if(e===r){let{providerExtUri:c,isPathCaseSensitive:u}=this.getExtUri(e);if(u||(l=c.isEqual(n,o)),l&&s==="copy")throw new Error(g(2476,null,this.resourceForError(n),this.resourceForError(o)));if(!l&&c.isEqualOrParent(o,n))throw new Error(g(2477,null,this.resourceForError(n),this.resourceForError(o)))}let d=await this.exists(o);if(d&&!l){if(!a)throw new Ke(g(2478,null,this.resourceForError(n),this.resourceForError(o)),4);if(e===r){let{providerExtUri:c}=this.getExtUri(e);if(c.isEqualOrParent(n,o))throw new Error(g(2479,null,this.resourceForError(n),this.resourceForError(o)))}}return{exists:d,isSameResourceWithDifferentPathCase:l}}getExtUri(e){let n=this.isPathCaseSensitive(e);return{providerExtUri:n?ae:wg,isPathCaseSensitive:n}}isPathCaseSensitive(e){return!!(e.capabilities&1024)}async createFolder(e){let n=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e);await this.mkdirp(n,e);let r=await this.resolve(e,{resolveMetadata:!0});return this._onDidRunOperation.fire(new yr(e,0,r)),r}async mkdirp(e,n){let r=[],{providerExtUri:o}=this.getExtUri(e);for(;!o.isEqual(n,o.dirname(n));)try{if(((await e.stat(n)).type&2)===0)throw new Error(g(2474,null,this.resourceForError(n)));break}catch(s){if(qt(s)!=="EntryNotFound")throw s;r.push(o.basename(n)),n=o.dirname(n)}for(let s=r.length-1;s>=0;s--){n=o.joinPath(n,r[s]);try{await e.mkdir(n)}catch(a){if(qt(a)!=="EntryExists")throw a}}}async canDelete(e,n){try{await this.doValidateDelete(e,n)}catch(r){return r}return!0}async doValidateDelete(e,n){let r=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e),o=!!n?.useTrash;if(o&&!(r.capabilities&4096))throw new Error(g(2461,null,this.resourceForError(e)));let s=n?.atomic;if(s&&!(r.capabilities&65536))throw new Error(g(2457,null,this.resourceForError(e)));if(o&&s)throw new Error(g(2460,null,this.resourceForError(e)));let a;try{a=await r.stat(e)}catch{}if(a)this.throwIfFileIsReadonly(e,a);else throw new Ke(g(2459,null,this.resourceForError(e)),1);if(!!!n?.recursive){let d=await this.resolve(e);if(d.isDirectory&&Array.isArray(d.children)&&d.children.length>0)throw new Error(g(2458,null,this.resourceForError(e)))}return r}async del(e,n){let r=await this.doValidateDelete(e,n),o=n;if(Wb(r)&&!o?.atomic){let d=r.enforceAtomicDelete?.(e);d&&(o={...n,atomic:d})}let s=!!o?.useTrash,a=!!o?.recursive,l=o?.atomic??!1;await r.delete(e,{recursive:a,useTrash:s,atomic:l}),this._onDidRunOperation.fire(new yr(e,1))}async cloneFile(e,n){let r=await this.withProvider(e),o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(n),n);if(!(r===o&&this.getExtUri(r).providerExtUri.isEqual(e,n)))return r===o&&Ub(r)?r.cloneFile(e,n):(await this.mkdirp(o,this.getExtUri(o).providerExtUri.dirname(n)),r===o&&om(r)?this.writeQueue.queueFor(e,()=>r.copy(e,n,{overwrite:!0}),this.getExtUri(r).providerExtUri):this.writeQueue.queueFor(e,()=>this.doCopyFile(r,e,o,n),this.getExtUri(r).providerExtUri))}static{this.WATCHER_CORRELATION_IDS=0}createWatcher(e,n){return this.watch(e,{...n,correlationId:xi.WATCHER_CORRELATION_IDS++})}watch(e,n={recursive:!1,excludes:[]}){let r=new z,o=!1,s=()=>{o=!0};r.add(k(()=>s())),(async()=>{try{let l=await this.doWatch(e,n);o?Tt(l):s=()=>Tt(l)}catch(l){this.logService.error(l)}})();let a=n.correlationId;if(typeof a=="number"){let l=r.add(new w);return r.add(this.internalOnDidFilesChange.event(c=>{c.correlates(a)&&l.fire(c)})),{onDidChange:l.event,dispose:()=>r.dispose()}}return r}async doWatch(e,n){let r=await this.withProvider(e),o=rn([this.getExtUri(r).providerExtUri.getComparisonKey(e),n]),s=this.activeWatchers.get(o);return s||(s={count:0,disposable:r.watch(e,n)},this.activeWatchers.set(o,s)),s.count+=1,k(()=>{s&&(s.count--,s.count===0&&(Tt(s.disposable),this.activeWatchers.delete(o)))})}dispose(){super.dispose();for(let[,e]of this.activeWatchers)Tt(e.disposable);this.activeWatchers.clear()}async doWriteBuffered(e,n,r,o){return this.writeQueue.queueFor(n,async()=>{let s=await e.open(n,{create:!0,unlock:r?.unlock??!1,append:r?.append??!1});try{La(o)||Ld(o)?await this.doWriteStreamBufferedQueued(e,s,o):await this.doWriteReadableBufferedQueued(e,s,o)}catch(a){throw br(a)}finally{await e.close(s)}},this.getExtUri(e).providerExtUri)}async doWriteStreamBufferedQueued(e,n,r){let o=0,s;if(Ld(r)){if(r.buffer.length>0){let a=A.concat(r.buffer);await this.doWriteBuffer(e,n,a,a.byteLength,o,0),o+=a.byteLength}if(r.ended)return;s=r.stream}else s=r;return new Promise((a,l)=>{Ud(s,{onData:async d=>{s.pause();try{await this.doWriteBuffer(e,n,d,d.byteLength,o,0)}catch(c){return l(c)}o+=d.byteLength,setTimeout(()=>s.resume())},onError:d=>l(d),onEnd:()=>a()})})}async doWriteReadableBufferedQueued(e,n,r){let o=0,s;for(;(s=r.read())!==null;)await this.doWriteBuffer(e,n,s,s.byteLength,o,0),o+=s.byteLength}async doWriteBuffer(e,n,r,o,s,a){let l=0;for(;l<o;){let d=await e.write(n,s+l,r.buffer,a+l,o-l);l+=d}}async doWriteUnbuffered(e,n,r,o){return this.writeQueue.queueFor(n,()=>this.doWriteUnbufferedQueued(e,n,r,o),this.getExtUri(e).providerExtUri)}async doWriteUnbufferedQueued(e,n,r,o){let s;o instanceof A?s=o:La(o)?s=await Xr(o):Ld(o)?s=await WS(o):s=US(o),await e.writeFile(n,s.buffer,{create:!0,overwrite:!0,unlock:r?.unlock??!1,atomic:r?.atomic??!1,append:r?.append??!1})}async doPipeBuffered(e,n,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeBufferedQueued(e,n,r,o),this.getExtUri(r).providerExtUri)}async doPipeBufferedQueued(e,n,r,o){let s,a;try{s=await e.open(n,{create:!1}),a=await r.open(o,{create:!0,unlock:!1});let l=A.alloc(this.BUFFER_SIZE),d=0,c=0,u=0;do u=await e.read(s,d,l.buffer,c,l.byteLength-c),await this.doWriteBuffer(r,a,l,u,d,c),d+=u,c+=u,c===l.byteLength&&(c=0);while(u>0)}catch(l){throw br(l)}finally{await Cn.settled([typeof s=="number"?e.close(s):Promise.resolve(),typeof a=="number"?r.close(a):Promise.resolve()])}}async doPipeUnbuffered(e,n,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedQueued(e,n,r,o),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedQueued(e,n,r,o){return r.writeFile(o,await e.readFile(n),{create:!0,overwrite:!0,unlock:!1,atomic:!1})}async doPipeUnbufferedToBuffered(e,n,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedToBufferedQueued(e,n,r,o),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedToBufferedQueued(e,n,r,o){let s=await r.open(o,{create:!0,unlock:!1});try{let a=await e.readFile(n);await this.doWriteBuffer(r,s,A.wrap(a),a.byteLength,0,0)}catch(a){throw br(a)}finally{await r.close(s)}}async doPipeBufferedToUnbuffered(e,n,r,o){let s=await Xr(this.readFileBuffered(e,n,Ee.None));await this.doWriteUnbuffered(r,o,void 0,s)}throwIfFileSystemIsReadonly(e,n){if(e.capabilities&2048)throw new Ke(g(2464,null,this.resourceForError(n)),6);return e}throwIfFileIsReadonly(e,n){if((n.permissions??0)&1)throw new Ke(g(2464,null,this.resourceForError(e)),6)}resourceForError(e){return e.scheme===ie.file?e.fsPath:e.toString(!0)}};xi=x([C(0,O)],xi);import{constants as Zy,promises as po}from"fs";function Df(i){return typeof i.correlationId=="number"}function uw(i){return i.recursive===!0}var Pf=class i extends T{constructor(e,n,r,o){super();this.onFileChanges=e;this.onLogMessage=n;this.verboseLogging=r;this.options=o;this.watcherDisposables=this._register(new vt);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<i.MAX_RESTARTS&&this.requests?(this.error(`restarting watcher after unexpected error: ${e}`),this.restart(this.requests)):this.error(`gave up attempting to restart watcher after unexpected error: ${e}`):this.error(e)}canRestart(e,n){return!(!this.options.restartOnError||n||e.indexOf("No space left on device")!==-1||e.indexOf("EMFILE")!==-1)}restart(e){this.restartCounter++,this.init(),this.watch(e)}async watch(e){this.requests=e,await this.watcher?.watch(e)}async setVerboseLogging(e){this.verboseLogging=e,await this.watcher?.setVerboseLogging(e)}error(e){this.onLogMessage({type:"error",message:`[File Watcher (${this.options.type})] ${e}`})}trace(e){this.onLogMessage({type:"trace",message:`[File Watcher (${this.options.type})] ${e}`})}dispose(){return this.watcher=void 0,super.dispose()}},Af=class extends Pf{constructor(t,e,n){super(t,e,n,{type:"node.js",restartOnError:!1})}},kf=class extends Pf{constructor(t,e,n){super(t,e,n,{type:"universal",restartOnError:!0})}};function Qy(i){return i.map(t=>({type:t.type,resource:y.revive(t.resource),cId:t.cId}))}function pw(i){let t=new Yy;for(let e of i)t.processEvent(e);return t.coalesce()}function aN(i,t){return typeof t=="string"&&!t.startsWith(us)&&!Wt(t)?{base:i,pattern:t}:t}function Xy(i,t,e){let n=[];for(let r of t)n.push(_l(aN(i,r),{ignoreCase:e}));return n}var Yy=class{constructor(){this.coalesced=new Set;this.mapPathToChange=new Map}toKey(t){return Se?t.resource.fsPath:t.resource.fsPath.toLowerCase()}processEvent(t){let e=this.mapPathToChange.get(this.toKey(t)),n=!1;if(e){let r=e.type,o=t.type;e.resource.fsPath!==t.resource.fsPath&&(t.type===2||t.type===1)?n=!0:r===1&&o===2?(this.mapPathToChange.delete(this.toKey(t)),this.coalesced.delete(e)):r===2&&o===1?e.type=0:r===1&&o===0||(e.type=o)}else n=!0;n&&(this.coalesced.add(t),this.mapPathToChange.set(this.toKey(t),t))}coalesce(){let t=[],e=[];return Array.from(this.coalesced).filter(n=>n.type!==2?(t.push(n),!1):!0).sort((n,r)=>n.resource.fsPath.length-r.resource.fsPath.length).filter(n=>e.some(r=>$b(n.resource.fsPath,r,!Se))?!1:(e.push(n.resource.fsPath),!0)).concat(t)}};function fw(i,t){if(typeof t=="number")switch(i.type){case 1:return(t&4)===0;case 2:return(t&8)===0;case 0:return(t&2)===0}return!1}function gw(i){if(typeof i=="number"){let t=[];return i&4&&t.push("Added"),i&8&&t.push("Deleted"),i&2&&t.push("Updated"),t.length===0?"<all>":`[${t.join(", ")}]`}return"<none>"}var Of=class extends T{constructor(e,n){super();this.logService=e;this.options=n;this._onDidChangeFile=this._register(new w);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new w);this.onDidWatchError=this._onDidWatchError.event;this.universalWatchRequests=[];this.universalWatchRequestDelayer=this._register(new Ui(this.getRefreshWatchersDelay(this.universalWatchRequests.length)));this.nonRecursiveWatchRequests=[];this.nonRecursiveWatchRequestDelayer=this._register(new Ui(this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)))}watch(e,n){return n.recursive||this.options?.watcher?.forceUniversal?this.watchUniversal(e,n):this.watchNonRecursive(e,n)}getRefreshWatchersDelay(e){return e>200?500:0}watchUniversal(e,n){let r=this.toWatchRequest(e,n),o=Gf(this.universalWatchRequests,r);return this.refreshUniversalWatchers(),k(()=>{o(),this.refreshUniversalWatchers()})}toWatchRequest(e,n){let r={path:this.toWatchPath(e),excludes:n.excludes,includes:n.includes,recursive:n.recursive,filter:n.filter,correlationId:n.correlationId};if(uw(r)){let o=this.options?.watcher?.recursive?.usePolling;o===!0?r.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3:Array.isArray(o)&&o.includes(r.path)&&(r.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3)}return r}refreshUniversalWatchers(){this.universalWatchRequestDelayer.trigger(()=>this.doRefreshUniversalWatchers(),this.getRefreshWatchersDelay(this.universalWatchRequests.length)).catch(e=>ze(e))}doRefreshUniversalWatchers(){return this.universalWatcher||(this.universalWatcher=this._register(this.createUniversalWatcher(e=>this._onDidChangeFile.fire(Qy(e)),e=>this.onWatcherLogMessage(e),this.logService.getLevel()===1)),this._register(this.logService.onDidChangeLogLevel(()=>{this.universalWatcher?.setVerboseLogging(this.logService.getLevel()===1)}))),this.universalWatcher.watch(this.universalWatchRequests)}watchNonRecursive(e,n){let r={path:this.toWatchPath(e),excludes:n.excludes,includes:n.includes,recursive:!1,filter:n.filter,correlationId:n.correlationId},o=Gf(this.nonRecursiveWatchRequests,r);return this.refreshNonRecursiveWatchers(),k(()=>{o(),this.refreshNonRecursiveWatchers()})}refreshNonRecursiveWatchers(){this.nonRecursiveWatchRequestDelayer.trigger(()=>this.doRefreshNonRecursiveWatchers(),this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)).catch(e=>ze(e))}doRefreshNonRecursiveWatchers(){return this.nonRecursiveWatcher||(this.nonRecursiveWatcher=this._register(this.createNonRecursiveWatcher(e=>this._onDidChangeFile.fire(Qy(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 Ft(e.fsPath)}toWatchPath(e){let n=this.toFilePath(e);return pS(n)}};var Mf=class extends kf{constructor(t,e,n){super(t,e,n),this.init()}createWatcher(t){let e=t.add(new zd(dt.asFileUri("bootstrap-fork").fsPath,{serverName:"File Watcher",args:["--type=fileWatcher"],env:{VSCODE_ESM_ENTRYPOINT:"vs/platform/files/node/watcher/watcherMain",VSCODE_PIPE_LOGGING:"true",VSCODE_VERBOSE_LOGGING:"true"}}));return t.add(e.onDidProcessExit(({code:n,signal:r})=>this.onError(`terminated by itself with code ${n}, signal: ${r} (ETERM)`))),Uo.toService(BS(e.getChannel("watcher")))}};import{watchFile as lN,unwatchFile as dN}from"fs";var Lf=class extends T{constructor(){super();this._onDidChangeFile=this._register(new w);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidLogMessage=this._register(new w);this.onDidLogMessage=this._onDidLogMessage.event;this._onDidWatchFail=this._register(new w);this.onDidWatchFail=this._onDidWatchFail.event;this.correlatedWatchRequests=new Map;this.nonCorrelatedWatchRequests=new Map;this.suspendedWatchRequests=this._register(new ve);this.suspendedWatchRequestsWithPolling=new Set;this.updateWatchersDelayer=this._register(new Ui(this.getUpdateWatchersDelay()));this.suspendedWatchRequestPollingInterval=5007;this.joinWatch=new Ie;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 Df(e)}computeId(e){return this.isCorrelated(e)?e.correlationId:rn(e)}async watch(e){this.joinWatch.isSettled||this.joinWatch.complete(),this.joinWatch=new Ie;try{this.correlatedWatchRequests.clear(),this.nonCorrelatedWatchRequests.clear();for(let n of e)this.isCorrelated(n)?this.correlatedWatchRequests.set(n.correlationId,n):this.nonCorrelatedWatchRequests.set(this.computeId(n),n);for(let[n]of this.suspendedWatchRequests)!this.nonCorrelatedWatchRequests.has(n)&&!this.correlatedWatchRequests.has(n)&&(this.suspendedWatchRequests.deleteAndDispose(n),this.suspendedWatchRequestsWithPolling.delete(n));return await this.updateWatchers(!1)}finally{this.joinWatch.complete()}}updateWatchers(e){let n=[];for(let[r,o]of[...this.nonCorrelatedWatchRequests,...this.correlatedWatchRequests])this.suspendedWatchRequests.has(r)||n.push(o);return this.updateWatchersDelayer.trigger(()=>this.doWatch(n),e?this.getUpdateWatchersDelay():0).catch(r=>ze(r))}getUpdateWatchersDelay(){return 800}isSuspended(e){let n=this.computeId(e);return this.suspendedWatchRequestsWithPolling.has(n)?"polling":this.suspendedWatchRequests.has(n)}async suspendWatchRequest(e){if(this.suspendedWatchRequests.has(e.id))return;let n=new 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 r=this.recursiveWatcher?.subscribe(e.path,(o,s)=>{n.isDisposed||(o?this.monitorSuspendedWatchRequest(e,n):s?.type===1&&this.onMonitoredPathAdded(e))});return r?(n.add(r),!0):!1}doMonitorWithNodeJS(e,n){let r=!1,o=(s,a)=>{if(n.isDisposed)return;let l=this.isPathNotFound(s),d=this.isPathNotFound(a),c=r;r=l,!l&&(d||c)&&this.onMonitoredPathAdded(e)};this.trace(`starting fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{lN(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(k(()=>{this.trace(`stopping fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{dN(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 r=` >> normalized ${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`;this.traceWithCorrelation(r,n)}}traceWithCorrelation(e,n){this.verboseLogging&&this.trace(`${e}${typeof n.correlationId=="number"?` <${n.correlationId}> `:""}`)}requestToString(e){return`${e.path} (excludes: ${e.excludes.length>0?e.excludes:"<none>"}, includes: ${e.includes&&e.includes.length>0?JSON.stringify(e.includes):"<all>"}, filter: ${gw(e.filter)}, correlationId: ${typeof e.correlationId=="number"?e.correlationId:"<none>"})`}async setVerboseLogging(e){this.verboseLogging=e}};import{watch as cN,promises as uN}from"fs";var Nf=class i extends T{constructor(e,n,r,o,s,a){super();this.request=e;this.recursiveWatcher=n;this.onDidFilesChange=r;this.onDidWatchFail=o;this.onLogMessage=s;this.verboseLogging=a;this.throttledFileChangesEmitter=this._register(new ko({maxWorkChunkSize:100,throttleDelay:200,maxBufferedWork:1e4},e=>this.onDidFilesChange(e)));this.fileChangesAggregator=this._register(new Dd(e=>this.handleFileChanges(e),i.FILE_CHANGES_HANDLER_DELAY));this.cts=new je;this.realPath=new Le(async()=>{let e=this.request.path;try{e=await Ae.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=!Se;this.excludes=Xy(this.request.path,this.request.excludes,l),this.includes=this.request.includes?Xy(this.request.path,this.request.includes,l):void 0,this.filter=Df(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 uN.stat(this.request.path);if(this.cts.token.isCancellationRequested)return;await eg(this.doWatch(e.isDirectory()),this._store)}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 r=y.file(this.request.path),o=this.recursiveWatcher?.subscribe(this.request.path,async(s,a)=>{n.isDisposed||(s?await eg(this.doWatch(e),n):a&&(typeof a.cId=="number"||typeof this.request.correlationId=="number")&&this.onFileChange({resource:r,type:a.type,cId:this.request.correlationId},!0))});return o?(n.add(o),!0):!1}async doWatchWithNodeJS(e,n){let r=await this.realPath.value;if(this.cts.token.isCancellationRequested)return;if(et&&cr(r,"/Volumes/",!0)){this.error(`Refusing to watch ${r} for changes using fs.watch() for possibly being a network share where watching is unreliable and unstable.`);return}let o=new je(this.cts.token);n.add(k(()=>o.dispose(!0)));let s=new z;n.add(s);try{let a=y.file(this.request.path),l=Ce(r),d=cN(r);s.add(k(()=>{d.removeAllListeners(),d.close()})),this.trace(`Started watching: '${r}'`);let c=new Set;if(e)try{for(let p of await Ae.readdir(r))c.add(p)}catch(p){this.error(p)}if(o.token.isCancellationRequested)return;let u=new Map;s.add(k(()=>{for(let[,p]of u)p.dispose();u.clear()})),d.on("error",(p,m)=>{o.token.isCancellationRequested||(this.error(`Failed to watch ${r} for changes using fs.watch() (${p}, ${m})`),this.notifyWatchFailed())}),d.on("change",(p,m)=>{if(o.token.isCancellationRequested)return;this.verboseLogging&&this.traceWithCorrelation(`[raw] ["${p}"] ${m}`);let h="";if(m&&(h=m.toString(),et&&(h=qa(h))),!(!h||p!=="change"&&p!=="rename"))if(e)if(p==="rename"){u.get(h)?.dispose();let v=setTimeout(async()=>{if(u.delete(h),Ro(h,l,!Se)&&!await Ae.exists(r)){this.onWatchedPathDeleted(a);return}if(o.token.isCancellationRequested)return;let I=await this.existsChildStrictCase(W(r,h));if(o.token.isCancellationRequested)return;let b;I?c.has(h)?b=0:(b=1,c.add(h)):(c.delete(h),b=2),this.onFileChange({resource:X(a,h),type:b,cId:this.request.correlationId})},i.FILE_DELETE_HANDLER_DELAY);u.set(h,k(()=>clearTimeout(v)))}else{let v;c.has(h)?v=0:(v=1,c.add(h)),this.onFileChange({resource:X(a,h),type:v,cId:this.request.correlationId})}else if(p==="rename"||!Ro(h,l,!Se)){let v=setTimeout(async()=>{let I=await Ae.exists(r);o.token.isCancellationRequested||(I?(this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0),s.add(await this.doWatch(!1))):this.onWatchedPathDeleted(a))},i.FILE_DELETE_HANDLER_DELAY);s.clear(),s.add(k(()=>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 ${r} for changes using fs.watch() (${a.toString()})`),this.notifyWatchFailed()}}onWatchedPathDeleted(e){this.warn("Watcher shutdown because watched path got deleted"),this.onFileChange({resource:e,type:2,cId:this.request.correlationId},!0),this.fileChangesAggregator.flush(),this.notifyWatchFailed()}onFileChange(e,n=!1){this.cts.token.isCancellationRequested||(this.verboseLogging&&this.traceWithCorrelation(`${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`),!n&&this.excludes.some(r=>r(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (excluded) ${e.resource.fsPath}`):!n&&this.includes&&this.includes.length>0&&!this.includes.some(r=>r(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (not included) ${e.resource.fsPath}`):this.fileChangesAggregator.work(e))}handleFileChanges(e){let n=pw(e),r=[];for(let s of n){if(fw(s,this.filter)){this.verboseLogging&&this.traceWithCorrelation(` >> ignored (filtered) ${s.resource.fsPath}`);continue}r.push(s)}if(r.length===0)return;if(this.verboseLogging)for(let s of r)this.traceWithCorrelation(` >> normalized ${s.type===1?"[ADDED]":s.type===2?"[DELETED]":"[CHANGED]"} ${s.resource.fsPath}`);this.throttledFileChangesEmitter.work(r)?this.throttledFileChangesEmitter.pending>0&&this.trace(`started throttling events due to large amount of file change events at once (pending: ${this.throttledFileChangesEmitter.pending}, most recent change: ${r[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`):this.warn(`started ignoring events due to too many file change events at once (incoming: ${r.length}, most recent change: ${r[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`)}async existsChildStrictCase(e){if(Se)return Ae.exists(e);try{let n=Ce(e);return(await Ae.readdir(se(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 Uf=class extends Lf{constructor(e){super();this.recursiveWatcher=e;this.onDidError=Q.None;this._watchers=new Map;this.worker=this._register(new vt)}get watchers(){return this._watchers.values()}async doWatch(e){e=this.removeDuplicateRequests(e);let n=[],r=new Set(Array.from(this.watchers));for(let o of e){let s=this._watchers.get(this.requestToWatcherKey(o));s&&Ym(s.request.excludes,o.excludes)&&Ym(s.request.includes,o.includes)?r.delete(s):n.push(o)}n.length&&this.trace(`Request to start watching: ${n.map(o=>this.requestToString(o)).join(",")}`),r.size&&this.trace(`Request to stop watching: ${Array.from(r).map(o=>this.requestToString(o.request)).join(",")}`),this.worker.clear();for(let o of r)this.stopWatching(o);this.createWatchWorker().work(n)}createWatchWorker(){return this.worker.value=new ko({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 Se?e:e.toLowerCase()}startWatching(e){let n=new Nf(e,this.recursiveWatcher,o=>this._onDidChangeFile.fire(o),()=>this._onDidWatchFail.fire(e),o=>this._onDidLogMessage.fire(o),this.verboseLogging),r={request:e,instance:n};this._watchers.set(this.requestToWatcherKey(e),r)}async stop(){await super.stop();for(let e of this.watchers)this.stopWatching(e)}stopWatching(e){this.trace("stopping file watcher",e),this._watchers.delete(this.requestToWatcherKey(e.request)),e.instance.dispose()}removeDuplicateRequests(e){let n=new Map;for(let r of e){let o=n.get(r.correlationId);o||(o=new Map,n.set(r.correlationId,o));let s=this.pathToWatcherKey(r.path);o.has(s)&&this.trace(`ignoring a request for watching who's path is already watched: ${this.requestToString(r)}`),o.set(s,r)}return Array.from(n.values()).flatMap(r=>Array.from(r.values()))}async setVerboseLogging(e){super.setVerboseLogging(e);for(let n of this.watchers)n.instance.setVerboseLogging(e)}trace(e,n){this.verboseLogging&&this._onDidLogMessage.fire({type:"trace",message:this.toMessage(e,n)})}warn(e){this._onDidLogMessage.fire({type:"warn",message:this.toMessage(e)})}toMessage(e,n){return n?`[File Watcher (node.js)] ${e} (${this.requestToString(n.request)})`:`[File Watcher (node.js)] ${e}`}};var Ff=class extends Af{constructor(t,e,n){super(t,e,n),this.init()}createWatcher(t){return t.add(new Uf(void 0))}};var Wf=class i extends Of{constructor(){super(...arguments);this.onDidChangeCapabilities=Q.None;this.resourceLocks=new Oe(e=>Je.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,Se&&(this._capabilities|=1024)),this._capabilities}async stat(e){try{let{stat:n,symbolicLink:r}=await Pt.stat(this.toFilePath(e)),o;return(n.mode&128)===0&&(o=2),(n.mode&Zy.S_IXUSR||n.mode&Zy.S_IXGRP||n.mode&Zy.S_IXOTH)&&(o=(o??0)|4),{type:this.toType(n,r),ctime:n.birthtime.getTime(),mtime:n.mtime.getTime(),size:n.size,permissions:o}}catch(n){throw this.toFileSystemProviderError(n)}}async statIgnoreError(e){try{return await this.stat(e)}catch{return}}async realpath(e){let n=this.toFilePath(e);return Ae.realpath(n)}async readdir(e){try{let n=await Ae.readdir(this.toFilePath(e),{withFileTypes:!0}),r=[];return await Promise.all(n.map(async o=>{try{let s;o.isSymbolicLink()?s=(await this.stat(X(e,o.name))).type:s=this.toType(o),r.push([o.name,s])}catch(s){this.logService.trace(s)}})),r}catch(n){throw this.toFileSystemProviderError(n)}}toType(e,n){let r;return n?.dangling?r=0:e.isFile()?r=1:e.isDirectory()?r=2:r=0,n&&(r|=64),r}async createResourceLock(e){let n=this.toFilePath(e);this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - request to acquire resource lock (${n})`);let r;for(;r=this.resourceLocks.get(e);)this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - waiting for resource lock to be released (${n})`),await r.wait();let o=new kd;return this.resourceLocks.set(e,o),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${n})`),k(()=>{this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock dispose() (${n})`),this.resourceLocks.get(e)===o&&(this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock removed from resource-lock map (${n})`),this.resourceLocks.delete(e)),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock barrier open() (${n})`),o.open()})}async readFile(e,n){let r;try{n?.atomic&&(this.traceLock(`[Disk FileSystemProvider]: atomic read operation started (${this.toFilePath(e)})`),r=await this.createResourceLock(e));let o=this.toFilePath(e);return await po.readFile(o)}catch(o){throw this.toFileSystemProviderError(o)}finally{r?.dispose()}}traceLock(e){i.TRACE_LOG_RESOURCE_LOCKS&&this.logService.trace(e)}readFileStream(e,n,r){let o=fr(s=>A.concat(s.map(a=>A.wrap(a))).buffer);return Ef(this,e,o,s=>s.buffer,{...n,bufferSize:256*1024},r),o}async writeFile(e,n,r){return r?.atomic!==!1&&r?.atomic?.postfix&&await this.canWriteFileAtomic(e)?this.doWriteFileAtomic(e,X(pr(e),`${pe(e)}${r.atomic.postfix}`),n,r):this.doWriteFile(e,n,r)}async canWriteFileAtomic(e){try{let n=this.toFilePath(e),{symbolicLink:r}=await Pt.stat(n);if(r)return!1}catch{}return!0}async doWriteFileAtomic(e,n,r,o){let s=new z;try{s.add(await this.createResourceLock(e)),s.add(await this.createResourceLock(n)),await this.doWriteFile(n,r,{...o,create:!0,overwrite:!0},!0);try{await this.rename(n,e,{overwrite:!0})}catch(a){try{await this.delete(n,{recursive:!1,useTrash:!1,atomic:!1})}catch{}throw a}}finally{s.dispose()}}async doWriteFile(e,n,r,o){let s;try{let a=this.toFilePath(e);if(!r.create||!r.overwrite){if(await Ae.exists(a)){if(!r.overwrite)throw he(g(2487,null),"EntryExists")}else if(!r.create)throw he(g(2490,null),"EntryNotFound")}s=await this.open(e,{create:!0,append:r.append,unlock:r.unlock},o),await this.write(s,0,n,0,n.byteLength)}catch(a){throw await this.toFileSystemProviderWriteError(e,a)}finally{typeof s=="number"&&await this.close(s)}}static{this.canFlush=!0}static configureFlushOnWrite(e){i.canFlush=e}async open(e,n,r){let o=this.toFilePath(e),s;vr(n)&&!r&&(s=await this.createResourceLock(e));let a;try{if(vr(n)&&n.unlock)try{let{stat:l}=await Pt.stat(o);l.mode&128||await po.chmod(o,l.mode|128)}catch(l){l.code!=="ENOENT"&&this.logService.trace(l)}if(G&&vr(n)&&!n.append)try{a=await Ae.open(o,"r+"),await Ae.ftruncate(a,0)}catch(l){if(l.code!=="ENOENT"&&this.logService.trace(l),typeof a=="number"){try{await Ae.close(a)}catch(d){this.logService.trace(d)}a=void 0}}typeof a!="number"&&(a=await Ae.open(o,vr(n)?n.append?"a":"w":"r"))}catch(l){throw s?.dispose(),vr(n)?await this.toFileSystemProviderWriteError(e,l):this.toFileSystemProviderError(l)}if(this.mapHandleToPos.set(a,0),vr(n)&&this.writeHandles.set(a,e),s){let l=this.mapHandleToLock.get(a);this.traceLock(`[Disk FileSystemProvider]: open() - storing lock for handle ${a} (${o})`),this.mapHandleToLock.set(a,s),l&&(this.traceLock(`[Disk FileSystemProvider]: open() - disposing a previous lock that was still stored on same handle ${a} (${o})`),l.dispose())}return a}async close(e){let n=this.mapHandleToLock.get(e);try{if(this.mapHandleToPos.delete(e),this.writeHandles.delete(e)&&i.canFlush)try{await Ae.fdatasync(e)}catch(r){i.configureFlushOnWrite(!1),this.logService.error(r)}return await Ae.close(e)}catch(r){throw this.toFileSystemProviderError(r)}finally{n&&(this.mapHandleToLock.get(e)===n&&(this.traceLock(`[Disk FileSystemProvider]: close() - resource lock removed from handle-lock map ${e}`),this.mapHandleToLock.delete(e)),this.traceLock(`[Disk FileSystemProvider]: close() - disposing lock for handle ${e}`),n.dispose())}}async read(e,n,r,o,s){let a=this.normalizePos(e,n),l=null;try{l=(await Ae.read(e,r,o,s,a)).bytesRead}catch(d){throw this.toFileSystemProviderError(d)}finally{this.updatePos(e,a,l)}return l}normalizePos(e,n){return n===this.mapHandleToPos.get(e)?null:n}updatePos(e,n,r){let o=this.mapHandleToPos.get(e);typeof o=="number"&&(typeof n=="number"||(typeof r=="number"?this.mapHandleToPos.set(e,o+r):this.mapHandleToPos.delete(e)))}async write(e,n,r,o,s){return AS(()=>this.doWrite(e,n,r,o,s),100,3)}async doWrite(e,n,r,o,s){let a=this.normalizePos(e,n),l=null;try{l=(await Ae.write(e,r,o,s,a)).bytesWritten}catch(d){throw await this.toFileSystemProviderWriteError(this.writeHandles.get(e),d)}finally{this.updatePos(e,a,l)}return l}async mkdir(e){try{await po.mkdir(this.toFilePath(e))}catch(n){throw this.toFileSystemProviderError(n)}}async delete(e,n){try{let r=this.toFilePath(e);if(n.recursive){let o;n?.atomic!==!1&&n.atomic.postfix&&(o=W(se(r),`${Ce(r)}${n.atomic.postfix}`)),await Ae.rm(r,1,o)}else try{await po.unlink(r)}catch(o){if(o.code==="EPERM"||o.code==="EISDIR"){let s=!1;try{let{stat:a,symbolicLink:l}=await Pt.stat(r);s=a.isDirectory()&&!l}catch{}if(s)await po.rmdir(r);else throw o}else throw o}}catch(r){throw this.toFileSystemProviderError(r)}}async rename(e,n,r){let o=this.toFilePath(e),s=this.toFilePath(n);if(o!==s)try{await this.validateMoveCopy(e,n,"move",r.overwrite),await Ae.rename(o,s)}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(g(2491,null,Ce(o),Ce(se(s)),a.toString()))),this.toFileSystemProviderError(a)}}async copy(e,n,r){let o=this.toFilePath(e),s=this.toFilePath(n);if(o!==s)try{await this.validateMoveCopy(e,n,"copy",r.overwrite),await Ae.copy(o,s,{preserveSymlinks:!0})}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(g(2485,null,Ce(o),Ce(se(s)),a.toString()))),this.toFileSystemProviderError(a)}}async validateMoveCopy(e,n,r,o){let s=this.toFilePath(e),a=this.toFilePath(n),l=!1;if(this.capabilities&1024||(l=Ro(s,a,!0)),l){if(r==="copy")throw he(g(2486,null),"EntryExists");if(r==="move")return}let c=await this.statIgnoreError(e);if(!c)throw he(g(2489,null),"EntryNotFound");let u=await this.statIgnoreError(n);if(u){if(!o)throw he(g(2488,null),"EntryExists");(c.type&1)!==0&&(u.type&1)!==0||await this.delete(n,{recursive:!0,useTrash:!1,atomic:!1})}}async cloneFile(e,n){return this.doCloneFile(e,n,!1)}async doCloneFile(e,n,r){let o=this.toFilePath(e),s=this.toFilePath(n),a=!!(this.capabilities&1024);if(Ro(o,s,!a))return;let l=new z;try{l.add(await this.createResourceLock(e)),l.add(await this.createResourceLock(n)),r&&await po.mkdir(se(s),{recursive:!0}),await po.copyFile(o,s)}catch(d){if(d.code==="ENOENT"&&!r)return this.doCloneFile(e,n,!0);throw this.toFileSystemProviderError(d)}finally{l.dispose()}}createUniversalWatcher(e,n,r){return new Mf(o=>e(o),o=>n(o),r)}createNonRecursiveWatcher(e,n,r){return new Ff(o=>e(o),o=>n(o),r)}toFileSystemProviderError(e){if(e instanceof Vo)return e;let n=e,r;switch(e.code){case"ENOENT":r="EntryNotFound";break;case"EISDIR":r="EntryIsADirectory";break;case"ENOTDIR":r="EntryNotADirectory";break;case"EEXIST":r="EntryExists";break;case"EPERM":case"EACCES":r="NoPermissions";break;case"ERR_UNC_HOST_NOT_ALLOWED":n=`${e.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`,r="Unknown";break;default:r="Unknown"}return he(n,r)}async toFileSystemProviderWriteError(e,n){let r=this.toFileSystemProviderError(n);if(e&&r.code==="NoPermissions")try{let{stat:o}=await Pt.stat(this.toFilePath(e));o.mode&128||(r=he(n,"EntryWriteLocked"))}catch(o){this.logService.trace(o)}return r}};import{parse as vw}from"url";import{spawn as pN}from"child_process";import R_e from"assert";function ev(i){return i.VSCODE_CLI==="1"}var tv;async function mw(i,t,e,n){return e["force-disable-user-env"]?(t.trace("resolveShellEnv(): skipped (--force-disable-user-env)"),{}):G?(t.trace("resolveShellEnv(): skipped (Windows)"),{}):ev(n)&&!e["force-user-env"]?(t.trace("resolveShellEnv(): skipped (VSCODE_CLI is set)"),{}):(ev(n)?t.trace("resolveShellEnv(): running (--force-user-env)"):t.trace("resolveShellEnv(): running (macOS/Linux)"),tv||(tv=Cn.withAsyncBody(async(r,o)=>{let s=new je,a=1e4,l=i.getValue("application.shellEnvironmentResolutionTimeout");typeof l=="number"&&(a=sT(l,1,120)*1e3);let d=setTimeout(()=>{s.dispose(!0),o(new Error(g(2618,null)))},a);try{r(await fN(t,s.token))}catch(c){!Zn(c)&&!s.token.isCancellationRequested?o(new Error(g(2616,null,xt(c)))):r({})}finally{clearTimeout(d),s.dispose()}})),tv)}async function fN(i,t){let e=process.env.ELECTRON_RUN_AS_NODE;i.trace("getUnixShellEnvironment#runAsNode",e);let n=process.env.ELECTRON_NO_ATTACH_CONSOLE;i.trace("getUnixShellEnvironment#noAttach",n);let r=N().replace(/-/g,"").substr(0,12),o=new RegExp(r+"({.*})"+r),s={...process.env,ELECTRON_RUN_AS_NODE:"1",ELECTRON_NO_ATTACH_CONSOLE:"1",VSCODE_RESOLVING_ENVIRONMENT:"1"};i.trace("getUnixShellEnvironment#env",s);let a=await Ac(at,s);return i.trace("getUnixShellEnvironment#shell",a),new Promise((l,d)=>{if(t.isCancellationRequested)return d(new K);let c=Ce(a),u,p,m="";/^(?:pwsh|powershell)(?:-preview)?$/.test(c)?(u=`& '${process.execPath}' ${m} -p '''${r}'' + JSON.stringify(process.env) + ''${r}'''`,p=["-Login","-Command"]):c==="nu"?(u=`^'${process.execPath}' ${m} -p '"${r}" + JSON.stringify(process.env) + "${r}"'`,p=["-i","-l","-c"]):c==="xonsh"?(u=`import os, json; print("${r}", json.dumps(dict(os.environ)), "${r}")`,p=["-i","-l","-c"]):(u=`'${process.execPath}' ${m} -p '"${r}" + JSON.stringify(process.env) + "${r}"'`,c==="tcsh"||c==="csh"?p=["-ic"]:p=["-i","-l","-c"]),i.trace("getUnixShellEnvironment#spawn",JSON.stringify(p),u);let h=pN(a,[...p,u],{detached:!0,stdio:["ignore","pipe","pipe"],env:s});t.onCancellationRequested(()=>(h.kill(),d(new K))),h.on("error",b=>{i.error("getUnixShellEnvironment#errorChildProcess",xt(b)),d(b)});let v=[];h.stdout.on("data",b=>v.push(b));let I=[];h.stderr.on("data",b=>I.push(b)),h.on("close",(b,S)=>{let _=Buffer.concat(v).toString("utf8");i.trace("getUnixShellEnvironment#raw",_);let R=Buffer.concat(I).toString("utf8");if(R.trim()&&i.trace("getUnixShellEnvironment#stderr",R),b||S)return d(new Error(g(2617,null,b,S)));let P=o.exec(_),q=P?P[1]:"{}";try{let E=JSON.parse(q);e?E.ELECTRON_RUN_AS_NODE=e:delete E.ELECTRON_RUN_AS_NODE,n?E.ELECTRON_NO_ATTACH_CONSOLE=n:delete E.ELECTRON_NO_ATTACH_CONSOLE,delete E.VSCODE_RESOLVING_ENVIRONMENT,delete E.XDG_RUNTIME_DIR,i.trace("getUnixShellEnvironment#result",E),l(E)}catch(E){i.error("getUnixShellEnvironment#errorCaught",xt(E)),d(E)}})})}import{parse as hw}from"url";function gN(i,t){return i.protocol==="http:"?t.HTTP_PROXY||t.http_proxy||null:i.protocol==="https:"&&(t.HTTPS_PROXY||t.https_proxy||t.HTTP_PROXY||t.http_proxy)||null}async function yw(i,t,e={}){let n=hw(i),r=e.proxyUrl||gN(n,t);if(!r)return null;let o=hw(r);if(!/^https?:$/.test(o.protocol||""))return null;let s={host:o.hostname||"",port:(o.port?+o.port:0)||(o.protocol==="https"?443:80),auth:o.auth,rejectUnauthorized:gd(e.strictSSL)?e.strictSSL:!0,keepAlive:!0};if(n.protocol==="http:"){let{default:a}=await import("http-proxy-agent");return new a.HttpProxyAgent(r,s)}else{let{default:a}=await import("https-proxy-agent");return new a.HttpsProxyAgent(r,s)}}import{createGunzip as mN}from"zlib";var hN=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ENETDOWN","ENETUNREACH","EPROTO"]),yN=/^(GET|HEAD|OPTIONS)$/i;function vN(i){if(i instanceof Error){let t=i.code;return!!t&&hN.has(t)}return!1}var ha=class extends Mu{constructor(e,n,r,o){super(o);this.machine=e;this.configurationService=n;this.environmentService=r;this.configure(),this._register(n.onDidChangeConfiguration(s=>{s.affectsConfiguration("http")&&this.configure()}))}configure(){this.proxyUrl=this.getConfigValue("http.proxy"),this.strictSSL=!!this.getConfigValue("http.proxyStrictSSL"),this.authorization=this.getConfigValue("http.proxyAuthorization")}async request(e,n){let{proxyUrl:r,strictSSL:o}=this,s;try{s=await mw(this.configurationService,this.logService,this.environmentService.args,process.env)}catch(d){this.shellEnvErrorLogged||(this.shellEnvErrorLogged=!0,this.logService.error("resolving shell environment failed",Ei(d)))}let a={...process.env,...s},l=e.agent?e.agent:await yw(e.url||"",a,{proxyUrl:r,strictSSL:o});return e.agent=l,e.strictSSL=o,this.authorization&&(e.headers={...e.headers||{},"Proxy-Authorization":this.authorization}),this.logAndRequest(e,()=>Sw(e,n))}async resolveProxy(e){}async lookupAuthorization(e){}async lookupKerberosAuthorization(e){try{let n=this.getConfigValue("http.proxyKerberosServicePrincipal");return"Negotiate "+await SN(e,n,this.logService,"RequestService#lookupKerberosAuthorization")}catch(n){this.logService.debug("RequestService#lookupKerberosAuthorization Kerberos authentication failed",n);return}}async loadCertificates(){return(await import("@vscode/proxy-agent")).loadSystemCertificates({loadSystemCertificatesFromNode:()=>this.getConfigValue("http.systemCertificatesNode",gh),log:this.logService})}getConfigValue(e,n){if(this.machine==="remote")return this.configurationService.getValue(e);let r=this.configurationService.inspect(e);return r.userLocalValue??r.defaultValue??n}};ha=x([C(1,ys),C(2,yn),C(3,O)],ha);async function SN(i,t,e,n){let r=await import("kerberos"),o=r.default||r,s=new URL(i),a=t||(process.platform==="win32"?`HTTP/${s.hostname}`:`HTTP@${s.hostname}`);return e.debug(`${n} Kerberos authentication lookup`,`proxyURL:${s}`,`spn:${a}`),(await o.initializeClient(a)).step("")}async function bN(i){return(vw(i.url).protocol==="https:"?await import("https"):await import("http")).request}async function Sw(i,t){let n,r=yN.test(i.type||"GET");for(let o=1;o<=3;o++)try{return await IN(i,t)}catch(s){if(n=s,s instanceof K||!r||!vN(s)||o===3)throw s;await _n(100*o,t)}throw n}async function IN(i,t){return Cn.withAsyncBody(async(e,n)=>{let r=vw(i.url),o=i.getRawRequest?i.getRawRequest(i):await bN(i),s={hostname:r.hostname,port:r.port?parseInt(r.port):r.protocol==="https:"?443:80,protocol:r.protocol,path:r.path,method:i.type||"GET",headers:i.headers,agent:i.agent,rejectUnauthorized:gd(i.strictSSL)?i.strictSSL:!0};i.user&&i.password&&(s.auth=i.user+":"+i.password),i.disableCache&&(s.cache="no-store");let a=o(s,d=>{let c=Pi(i.followRedirects)?i.followRedirects:3;if(d.statusCode&&d.statusCode>=300&&d.statusCode<400&&c>0&&d.headers.location)Sw({...i,url:d.headers.location,followRedirects:c-1},t).then(e,n);else{let u=d;!i.isChromiumNetwork&&d.headers["content-encoding"]==="gzip"&&(u=d.pipe(mN())),e({res:d,stream:$S(u)})}});if(a.on("error",n),i.timeout)if(i.isChromiumNetwork){let d=setTimeout(()=>{a.abort(),n(new Error(`Request timeout after ${i.timeout}ms`))},i.timeout);a.on("response",()=>clearTimeout(d)),a.on("error",()=>clearTimeout(d)),a.on("abort",()=>clearTimeout(d))}else a.setTimeout(i.timeout);i.isChromiumNetwork&&a.removeHeader("Content-Length"),i.data&&typeof i.data=="string"&&a.write(i.data),a.end();let l=t.onCancellationRequested(()=>{l.dispose(),a.abort(),n(new K)});a.on("response",()=>l.dispose()),a.on("error",()=>l.dispose())})}async function bw(i,t,e,n,r){let o=new mi;i.set(ku,o);let s=X(e.userRoamingDataHome,"settings.json"),a=r.add(new _s(s,t,o,n));await a.initialize(),i.set(ys,a),i.set(Lu,r.add(new ha("local",a,e,n)))}import*as Cw from"fs";var Iw=[{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 kn(i,t){return new Promise((e,n)=>{i.exec(t,r=>r?n(r):e())})}function Mt(i,t,e){return new Promise((n,r)=>{i.run(t,e,function(o){if(o)return r(o);n({changes:this.changes,lastID:this.lastID})})})}function wi(i,t,e){return new Promise((n,r)=>{i.get(t,e,(o,s)=>{if(o)return r(o);n(s)})})}function ya(i,t,e){return new Promise((n,r)=>{i.all(t,e,(o,s)=>{if(o)return r(o);n(s)})})}function nv(i){return new Promise((t,e)=>{i.close(n=>n?e(n):t())})}function _N(i){return new Promise((t,e)=>{import("@vscode/sqlite3").then(n=>{let r=new n.default.Database(i,o=>{if(o)return e(o);t(r)})},e)})}async function CN(i,t){await kn(i,"PRAGMA foreign_keys = ON");let n=(await wi(i,"PRAGMA user_version",[]))?.user_version??0,r=t.filter(o=>o.version>n).sort((o,s)=>o.version-s.version);if(r.length!==0){await kn(i,"BEGIN TRANSACTION");try{for(let o of r)await kn(i,o.sql),await kn(i,`PRAGMA user_version = ${o.version}`);await kn(i,"COMMIT")}catch(o){throw await kn(i,"ROLLBACK"),o}}}var $f=class i{constructor(t,e=Iw){this._path=t;this._migrations=e;this._fileEditSequencer=new nt;this._metadataSequencer=new nt;this._pendingWrites=new Set}static async open(t,e=Iw){let n=new i(t,e);return await n._ensureDb(),n}_ensureDb(){return this._closed?Promise.reject(new Error("SessionDatabase has been disposed")):(this._dbPromise||(this._dbPromise=(async()=>{await Cw.promises.mkdir(se(this._path),{recursive:!0});let t=await _N(this._path);try{await CN(t,this._migrations)}catch(e){throw await nv(t),this._dbPromise=void 0,e}if(this._closed)throw await nv(t),new Error("SessionDatabase has been disposed");return t})()),this._dbPromise)}async getAllTables(){let t=await this._ensureDb();return(await ya(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 Mt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t])})}deleteTurn(t){return this._track(async()=>{let e=await this._ensureDb();await Mt(e,"DELETE FROM turns WHERE id = ?",[t])})}setTurnEventId(t,e){return this._track(async()=>{let n=await this._ensureDb();await Mt(n,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t]),await Mt(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 wi(e,"SELECT event_id FROM turns WHERE id = ?",[t]))?.event_id??void 0}async getNextTurnEventId(t){let e=await this._ensureDb();return(await wi(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 wi(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 Mt(n,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t]),await Mt(n,"UPDATE turns SET checkpoint_ref = ? WHERE id = ?",[e,t])})}async getTurnCheckpointRef(t){let e=await this._ensureDb();return(await wi(e,"SELECT checkpoint_ref FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1",[t]))?.checkpoint_ref??void 0}async getPreviousCheckpointRef(t){let e=await this._ensureDb();return(await wi(e,`SELECT checkpoint_ref FROM turns
				WHERE rowid < (SELECT rowid FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1)
					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 ya(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 Mt(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 Mt(e,"DELETE FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?)",[t])})}deleteAllTurns(){return this._track(async()=>{let t=await this._ensureDb();await kn(t,"DELETE FROM turns")})}storeFileEdit(t){return this._track(()=>this._fileEditSequencer.queue(t.filePath,async()=>{let e=await this._ensureDb();await Mt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[t.turnId]),await Mt(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 ya(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 ya(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 ya(e,`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
				FROM file_edits
				WHERE turn_id = ?
				ORDER BY rowid`,[t])).map(r=>({turnId:r.turn_id,toolCallId:r.tool_call_id,filePath:r.file_path,kind:r.edit_type??"edit",originalPath:r.original_path??void 0,addedLines:r.added_lines??void 0,removedLines:r.removed_lines??void 0}))}async readFileEditContent(t,e){return this._fileEditSequencer.queue(e,async()=>{let n=await this._ensureDb(),r=await wi(n,`SELECT before_content, after_content
					FROM file_edits
					WHERE tool_call_id = ? AND file_path = ?`,[t,e]);if(r)return{beforeContent:r.before_content?_w(r.before_content):void 0,afterContent:r.after_content?_w(r.after_content):void 0}})}async getMetadata(t){let e=await this._ensureDb();return(await wi(e,"SELECT value FROM session_metadata WHERE key = ?",[t]))?.value}async getMetadataObject(t){let e=Object.keys(t),n={};if(e.length===0)return n;let r=await this._ensureDb(),o=e.map(()=>"?").join(","),s=await ya(r,`SELECT key, value FROM session_metadata WHERE key IN (${o})`,e);for(let a of e)n[a]=void 0;for(let a of s)n[a.key]=a.value;return n}setMetadata(t,e){return this._track(()=>this._metadataSequencer.queue(t,async()=>{let n=await this._ensureDb();await Mt(n,"INSERT OR REPLACE INTO session_metadata (key, value) VALUES (?, ?)",[t,e])}))}remapTurnIds(t){return this._track(async()=>{let e=await this._ensureDb();await kn(e,"PRAGMA defer_foreign_keys = ON"),await kn(e,"BEGIN TRANSACTION");try{let n=[...t.keys()];if(n.length>0){let r=n.map(()=>"?").join(",");await Mt(e,`DELETE FROM turns WHERE id NOT IN (${r})`,n)}for(let[r,o]of t)await Mt(e,"UPDATE turns SET id = ? WHERE id = ?",[o,r]),await Mt(e,"UPDATE file_edits SET turn_id = ? WHERE turn_id = ?",[o,r]);await kn(e,"COMMIT")}catch(n){throw await kn(e,"ROLLBACK"),n}})}async whenIdle(){for(;this._pendingWrites.size>0;)await Promise.allSettled([...this._pendingWrites])}async vacuumInto(t){let e=await this._ensureDb();await Mt(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=>nv(t)).catch(()=>{})||!0)}dispose(){this.close()}};function _w(i){return i instanceof Buffer?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i instanceof Uint8Array?i:typeof i=="string"?new TextEncoder().encode(i):new Uint8Array(0)}var rv=class extends vo{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 r=new $f(n);return this.liveDatabases.add(r),r}destroyReferencedObject(e,n){this.liveDatabases.delete(n),n.dispose()}},va=class{constructor(t,e,n,r){this._fileService=e;this._logService=n;this._onWillDeleteSessionData=new w;this._basePath=y.joinPath(t,"agentSessionData"),this._databases=new rv(r??(o=>y.joinPath(this._basePath,o,dl).fsPath),this._logService)}get onWillDeleteSessionData(){return this._onWillDeleteSessionData.event}getSessionDataDir(t){return this.getSessionDataDirById(F.id(t))}getSessionDataDirById(t){let e=t.replace(/[^a-zA-Z0-9_.-]/g,"-");return y.joinPath(this._basePath,e)}_sanitizedSessionKey(t){return F.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,dl);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:r=>{n.push(r)}})}catch(r){this._logService.warn(`[SessionDataService] onWillDeleteSessionData listener threw synchronously: ${e.toString()}`,r)}if(n.length>0){let r=await Promise.allSettled(n);for(let o of r)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(r){this._logService.warn(`[SessionDataService] Failed to delete session data: ${e.toString()}`,r)}}async cleanupOrphanedData(t){try{if(!await this._fileService.exists(this._basePath))return;let n=await this._fileService.resolve(this._basePath);if(!n.children)return;let r=[];for(let o of n.children){if(!o.isDirectory)continue;let s=o.name;t.has(s)||(this._logService.trace(`[SessionDataService] Cleaning up orphaned session data: ${s}`),r.push(this._fileService.del(o.resource,{recursive:!0}).catch(a=>{this._logService.warn(`[SessionDataService] Failed to clean up orphaned data: ${s}`,a)})))}await Promise.all(r)}catch(e){this._logService.warn("[SessionDataService] Failed to run orphan cleanup",e)}}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}}};va=x([C(1,Te),C(2,O)],va);import{execFile as TN}from"child_process";var Hf=class i{static async checkSandboxDependenciesWith(t,e=Se,n=r=>i._probeBubblewrap(r)){if(!e)return;let[r,o]=await Promise.all([t("bwrap"),t("socat")]),s=r?await n(r):{usable:!1};return{bubblewrapInstalled:!!r,bubblewrapUsable:s.usable,bubblewrapError:s.error,socatInstalled:!!o}}checkSandboxDependencies(){return i.checkSandboxDependenciesWith(Bd)}static _probeBubblewrap(t){return new Promise(e=>{TN(t,["--unshare-net","--dev-bind","/","/","echo","ok"],{encoding:"utf8",timeout:5e3},(n,r,o)=>{if(!n&&r.trim()==="ok"){e({usable:!0});return}let s=o.trim()||n?.message||`Unexpected output: ${r.trim()}`;e({usable:!1,error:s.slice(0,1e3)})})})}async getWindowsMxcFilesystemPolicy(){if(!G)return;let{getAvailableToolsPolicy:t,getUserProfilePolicy:e,getTemporaryFilesPolicy:n}=await import("@microsoft/mxc-sdk"),r=t(process.env,{containerType:"processcontainer"}),o=e(),s=n(process.env),a=await this._getPSHome();return{readonlyPaths:[...new Set([...r.readonlyPaths,...o.readonlyPaths,...s.readonlyPaths,...a?[a]:[]])],readwritePaths:[...new Set([...r.readwritePaths,...o.readwritePaths,...s.readwritePaths])]}}async getWindowsMxcEnvironment(){if(!G)return;let t=[];for(let s of["SystemRoot","PATH","ComSpec","PATHEXT","PSModulePath"]){let a=gr(process.env,s);typeof a=="string"&&a&&t.push(`${s}=${a}`)}let e=gr(process.env,"USERPROFILE");typeof e=="string"&&e&&t.push(`USERPROFILE=${e}`);let n=gr(process.env,"APPDATA");typeof n=="string"&&n&&t.push(`APPDATA=${n}`);let r=this._getLocalAppData();typeof r=="string"&&r&&t.push(`LOCALAPPDATA=${r}`);let o=await this._getPSHome();return o&&t.push(`PSHOME=${o}`),t}async buildWindowsMxcSandboxPayload(t,e,n,r,o="process"){if(!G)return;let{buildSandboxPayload:s}=await import("@microsoft/mxc-sdk");return s(t,e,n,r,o)}async _getPSHome(){let t=gr(process.env,"PSHOME");if(typeof t=="string"&&t)return t;let e=await Bd("pwsh")??await Bd("powershell");return e?le.dirname(e):void 0}_getLocalAppData(){let t=gr(process.env,"LOCALAPPDATA");return typeof t=="string"&&t?t:void 0}};var qf=class i extends T{constructor(e=i._DEFAULT_CONNECTION_GRACE_MS){super();this._connectionGraceMs=e;this.capabilities=263178;this._onDidChangeCapabilities=this._register(new w);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._onDidChangeFile=this._register(new w);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new w);this.onDidWatchError=this._onDidWatchError.event;this._authorities=new Map;this._onDidChangeConnection=this._register(new w)}static{this._DEFAULT_CONNECTION_GRACE_MS=5e3}registerAuthority(e,n){let r=this._authorities.get(e);r?(r.expiry.clear(),r.connections.push(n)):(r={connections:[n],expiry:new vt},this._authorities.set(e,r));let o=r;return this._onDidChangeConnection.fire(e),k(()=>{let s=o.connections.indexOf(n);if(s===-1)return;let a=s===o.connections.length-1;o.connections.splice(s,1),o.connections.length===0&&(o.expiry.value=$t(()=>this._expireAuthority(e,o),this._connectionGraceMs,this._store)),a&&this._onDidChangeConnection.fire(e)})}_expireAuthority(e,n){this._authorities.get(e)!==n||n.connections.length>0||(this._authorities.delete(e),n.expiry.dispose(),this._onDidChangeConnection.fire(e))}dispose(){for(let e of this._authorities.values())e.expiry.dispose(),e.connections.length=0;this._authorities.clear(),super.dispose()}watch(e,n){let r=new z,o=r.add(new vt),s=e.authority,a={channel:Be,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(p=>typeof p=="string"?p:p.pattern)}}:{}},l,d=!1,c=!1,u=async()=>{if(r.isDisposed)return;if(d){c=!0;return}let m=this._authorities.get(s)?.connections.at(-1);if(m===l)return;o.clear(),l=void 0;let h=m?.watchResource;if(!m||!h)return;d=!0;let v=m;try{let I=await h.call(v,a);if(r.isDisposed){I.dispose();return}let b=this._authorities.get(s);if(!b||b.connections.at(-1)!==v){I.dispose();return}let S=I.onDidChange(_=>this._onDidChangeFile.fire(_.map(R=>({resource:this._encodeUri(R.resource,e.authority),type:R.type}))));o.value=k(()=>{S.dispose(),I.dispose()}),l=v}catch(I){this._onDidWatchError.fire(I instanceof Error?I.message:String(I))}finally{d=!1,c&&(c=!1,u())}};return r.add(this._onDidChangeConnection.event(p=>{p===s&&u()})),u(),r}async stat(e){let n=e.path;if(n==="/"||n==="")return{type:2,mtime:0,ctime:0,size:0,permissions:1};let r=this._decodeUri(e);if(r.scheme==="session-db"||r.scheme==="git-blob")return{type:1,mtime:0,ctime:0,size:0,permissions:1};if(r.path==="/"||r.path==="")return{type:2,mtime:0,ctime:0,size:0,permissions:1};let o=await this._getConnection(e.authority);try{let s=await this._resolve(o,r);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}}catch(s){throw this._mapError(s,"EntryNotFound")}}async realpath(e){let n=e.path;if(n==="/"||n==="")return n;let r=this._decodeUri(e);if(r.scheme==="session-db"||r.scheme==="git-blob"||r.path==="/"||r.path==="")return n;let o=await this._getConnection(e.authority);try{let s=await this._resolve(o,r);return this._encodeUri(y.parse(s.uri),e.authority).path}catch(s){throw this._mapError(s,"EntryNotFound")}}async readdir(e){return(await this._listDirectory(e.authority,e)).map(r=>[r.name,r.type==="directory"?2:1])}async readFile(e){let n=await this._getConnection(e.authority);try{let r=this._decodeUri(e),o=await n.resourceRead(r);return o.encoding==="base64"?Ln(o.data).buffer:A.fromString(o.data).buffer}catch(r){throw this._mapError(r,"EntryNotFound")}}async writeFile(e,n,r){let o=await this._getConnection(e.authority);try{let s=this._decodeUri(e);await o.resourceWrite({channel:Be,uri:s.toString(),data:A.wrap(n).toString(),encoding:"utf-8"})}catch(s){throw this._mapError(s,"NoPermissions")}}async mkdir(e){let n=await this._getConnection(e.authority);try{let r=this._decodeUri(e);await n.resourceMkdir({channel:Be,uri:r.toString()})}catch(r){throw this._mapError(r,"NoPermissions")}}async delete(e,n){let r=await this._getConnection(e.authority);try{let o=this._decodeUri(e);await r.resourceDelete({channel:Be,uri:o.toString(),recursive:n.recursive})}catch(o){throw this._mapError(o,"NoPermissions")}}async rename(e,n,r){let o=await this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(n);await o.resourceMove({channel:Be,source:s.toString(),destination:a.toString(),failIfExists:!r.overwrite})}catch(s){throw this._mapError(s,"NoPermissions")}}async copy(e,n,r){let o=await this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(n);await o.resourceCopy({channel:Be,source:s.toString(),destination:a.toString(),failIfExists:!r.overwrite})}catch(s){throw this._mapError(s,"NoPermissions")}}async requestResourceAccess(e,n){let r=await this._getConnection(e.authority);if(!r.resourceRequest)throw he(`Connection for ${e.authority} does not support resourceRequest`,"Unavailable");let o=this._decodeUri(e);try{await r.resourceRequest({channel:Be,uri:o.toString(),read:n.read,write:n.write})}catch(s){throw this._mapError(s,"NoPermissions")}}_getConnection(e){let n=this._authorities.get(e);if(!n)return Promise.reject(he(`No connection for authority: ${e}`,"Unavailable"));let r=n.connections.at(-1);return r?Promise.resolve(r):new Promise((o,s)=>{let a=()=>{let d=this._authorities.get(e);if(!d){l.dispose(),s(he(`No connection for authority: ${e}`,"Unavailable"));return}let c=d.connections.at(-1);c&&(l.dispose(),o(c))},l=this._onDidChangeConnection.event(d=>{d===e&&a()});a()})}_mapError(e,n){return e instanceof D&&e.code===ue.PermissionDenied?he(e.message,"NoPermissions"):he(e instanceof Error?e.message:String(e),n)}_resolve(e,n){return e.resourceResolve({channel:Be,uri:n.toString()})}async _listDirectory(e,n){let r=await this._getConnection(e);try{let o=this._decodeUri(n);return(await r.resourceList(o)).entries}catch(o){throw this._mapError(o,"Unavailable")}}};var Bf=class extends qf{_decodeUri(t){return ZC(t)}_encodeUri(t,e){return ks(t,e)}};var Tw="local";var sd=class extends Error{constructor(e){super(e?`Access to ${e.uri} is not granted.`:"Access to the requested resource is not granted.");this.request=e;this.name="AgentHostResourcePermissionError"}},xw=$("agentHostResourceService");var ww="agentHostClientResource";function Rw(i){return{resourceList:t=>i.call("resourceList",{uri:t.toString()}),resourceRead:t=>i.call("resourceRead",{uri:t.toString()}),resourceWrite:t=>i.call("resourceWrite",{...t,uri:t.uri.toString()}),resourceCopy:t=>i.call("resourceCopy",{...t,source:t.source.toString(),destination:t.destination.toString()}),resourceDelete:t=>i.call("resourceDelete",{...t,uri:t.uri.toString()}),resourceMove:t=>i.call("resourceMove",{...t,source:t.source.toString(),destination:t.destination.toString()}),resourceResolve:t=>i.call("resourceResolve",{...t,uri:t.uri.toString()}),resourceMkdir:t=>i.call("resourceMkdir",{...t,uri:t.uri.toString()}),resourceRequest:t=>i.call("resourceRequest",{...t,uri:t.uri.toString()})}}var Vf=class{constructor(t,e){this._ahpLogger=t;this._resourceService=e}listen(t,e){throw new Error(`No event '${e}' on AgentHostClientResourceChannel`)}async call(t,e,n){let r={jsonrpc:"2.0",method:e,params:n};this._logReverseFrame(r,"s2c");try{let o=await this._call(t,e,n),s={jsonrpc:"2.0",method:e,result:o??null};return this._logReverseFrame(s,"c2s"),o}catch(o){let s=o instanceof sd?{jsonrpc:"2.0",method:e,error:{code:ue.PermissionDenied,message:o.message,data:o.request?{request:o.request}:void 0}}:{jsonrpc:"2.0",method:e,error:{code:-32603,message:o instanceof Error?o.message:String(o)}};throw this._logReverseFrame(s,"c2s"),o}}_logReverseFrame(t,e){this._ahpLogger?.log(t,e)}async _call(t,e,n){let r=n??{},o=Tw;switch(e){case"resourceList":return{entries:(await this._resourceService.list(o,y.parse(r.uri))).entries};case"resourceRead":{let s=await this._resourceService.read(o,y.parse(r.uri));return{data:Fi(s.bytes),encoding:"base64"}}case"resourceWrite":return await this._resourceService.write(o,r),{};case"resourceDelete":return await this._resourceService.del(o,r),{};case"resourceMove":return await this._resourceService.move(o,r),{};case"resourceCopy":return await this._resourceService.copy(o,r),{};case"resourceResolve":return this._resourceService.resolve(o,r);case"resourceMkdir":return await this._resourceService.mkdir(o,r),{};case"resourceRequest":try{return await this._resourceService.request(o,r),{}}catch(s){throw s instanceof K?new sd(void 0):s}}throw new Error(`Unknown command '${e}' on AgentHostClientResourceChannel`)}};Vf=x([C(1,xw)],Vf);var xN=20,Sa=class{constructor(t,e,n,r=xN){this._fileService=e;this._logService=n;this._sequencer=new nt;this._lru=[];this._cacheLoaded=!1;this._basePath=y.joinPath(t,"agentPlugins"),this._cachePath=y.joinPath(this._basePath,"cache.json"),this._maxPlugins=r}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=ks(y.parse(e.uri),t),r=this._dirFor(e.uri,e.nonce);return e.nonce&&this._findEntry(e.uri,e.nonce)&&await this._fileService.exists(r)?(this._touchLru(e.uri,e.nonce),this._logService.trace(`[AgentPluginManager] Nonce match for ${e.uri}, skipping copy`),r):(this._logService.info(`[AgentPluginManager] Syncing plugin: ${e.uri} \u2192 ${r.toString()}`),await this._fileService.copy(n,r,!0),this._removeEntry(e.uri,e.nonce),this._lru.push({uri:e.uri,nonce:e.nonce??""}),await this._cleanupStaleNoncesFor(e.uri),await this._evictIfNeeded(),await this._persistCache(),r)}_keyForUri(t){return this._sanitize(t)}_keyForNonce(t){return t&&this._sanitize(t)||"default"}_sanitize(t){return t.replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,128)}_dirFor(t,e){return y.joinPath(this._basePath,this._keyForUri(t),this._keyForNonce(e))}_pluginRootFor(t){return y.joinPath(this._basePath,this._keyForUri(t))}_findEntry(t,e){let n=e??"";return this._lru.find(r=>r.uri===t&&r.nonce===n)}_removeEntry(t,e){let n=this._findEntry(t,e);n&&this._removeEntryRef(n)}_removeEntryRef(t){let e=this._lru.indexOf(t);e!==-1&&this._lru.splice(e,1)}_touchLru(t,e){let n=this._findEntry(t,e);n&&(this._removeEntryRef(n),this._lru.push(n))}async _tryDeleteDir(t){try{return await this._fileService.del(t,{recursive:!0}),!0}catch(e){return this._logService.warn(`[AgentPluginManager] Failed to remove plugin dir ${t.toString()}`,e),!1}}async _cleanupStaleNonces(){for(let t of new Set(this._lru.map(e=>e.uri)))await this._cleanupStaleNoncesFor(t)}async _cleanupStaleNoncesFor(t){let n=this._lru.filter(r=>r.uri===t).slice(0,-1);for(let r of n)this._logService.info(`[AgentPluginManager] Evicting stale nonce for plugin: ${t}`),await this._tryDeleteDir(this._dirFor(r.uri,r.nonce))&&this._removeEntryRef(r)}async _evictIfNeeded(){let t=0;for(;this._lru.length>this._maxPlugins&&t<this._lru.length;){let e=this._lru[t];this._logService.info(`[AgentPluginManager] Evicting plugin: ${e.uri}`),await this._tryDeleteDir(this._dirFor(e.uri,e.nonce))?(this._lru.splice(t,1),this._lru.some(n=>n.uri===e.uri)||await this._tryDeleteDir(this._pluginRootFor(e.uri))):t++}}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._lru.push({uri:n.uri,nonce:n.nonce});this._logService.trace(`[AgentPluginManager] Loaded ${e.length} cache entries from disk`)}catch(t){this._logService.warn("[AgentPluginManager] Failed to load cache from disk",t)}await this._cleanupStaleNonces(),await this._persistCache()}}async _persistCache(){try{let t=this._lru.map(e=>({uri:e.uri,nonce:e.nonce}));await this._fileService.createFolder(this._basePath),await this._fileService.writeFile(this._cachePath,A.fromString(JSON.stringify(t)))}catch(t){this._logService.warn("[AgentPluginManager] Failed to persist cache to disk",t)}}};Sa=x([C(1,Te),C(2,O)],Sa);wN().catch(i=>{console.error(i),process.exit(1)});async function wN(){let i;jd(process)?i=new Va:i=new Vd("agentHost");let t=new z,e={_serviceBrand:void 0,...Gt},n=new _f(Cf(process.argv,jy),e),r=new wf(Xb(n),n.logsHome);i.registerChannel("agentHostLogger",new Rf(r,()=>lw));let o=r.createLogger("agenthost",{name:g(1924,null)}),s=t.add(new bp),a=t.add(new Ip(s)),l=new Tf(o,[a]);!n.isBuilt&&Yb&&t.add(Qb(l)),l.info("Agent Host process started successfully");let d=t.add(new xi(l));t.add(d.registerProvider(ie.file,t.add(new Wf(l)))),t.add(MT(d));let c=new va(y.file(n.userDataPath),d,l),u=X(n.appSettingsHome,"globalStorage","agent-host-config.json"),p=await bC({environmentService:n,productService:e,fileService:d,loggerService:r,logService:l,disposables:t}),m,h;try{let P=new ri;P.set(yn,n),P.set(O,l),P.set(Te,d),P.set(ft,c),P.set(gt,e),P.set(ai,p),await bw(P,d,n,l,t),h=new Ko(P);let q=t.add(h.createInstance(qn));P.set(ws,q),P.set(Fp,h.createInstance(Up)),P.set(Np,new Hf);let E=h.createInstance(ls);P.set(tt,E);let L=t.add(h.createInstance(ds));P.set(Wn,L);let U=h.createInstance(zs);P.set(js,U);let J=h.createInstance(pi,void 0);P.set(Kt,J);let ne=t.add(h.createInstance(oa));P.set(lf,ne);let xe=h.createInstance(Ks);P.set(Gs,xe);let ba=t.add(h.createInstance(la));P.set(uf,ba);let Qn=t.add(h.createInstance(pa));P.set(vp,Qn),m=new pp(l,d,c,e,E,L,u,p,q),P.set(ti,m);let B=new Sa(y.file(n.userDataPath),d,l);P.set(yi,B);let M=t.add(new ci(l));P.set($c,M),P.set(is,m.terminalManager),P.set($e,m.configurationService),P.set(eu,m.completionsService),m.registerProvider(h.createInstance(me)),$g(process.env[ab],!0)&&(!n.isBuilt||U.isAvailable(zp))&&m.registerProvider(h.createInstance(sa)),$g(process.env[lb],!1)&&U.isAvailable(Ly)&&m.registerProvider(h.createInstance(ca))}catch(P){throw l.error("Failed to create AgentService",P),P}let v=Uo.fromService(m,t);i.registerChannel("agentHost",v);let I=t.add(new Bf);if(t.add(d.registerProvider(Fh,I)),i instanceof Va){let P=new Map,q=E=>{if(P.has(E))return;let L=E.ctx;if(typeof L!="string"||!L)return;let U=i.getChannel(ww,ne=>ne.ctx===L),J=Rw(U);P.set(E,I.registerAuthority(L,J))};t.add(i.onDidAddConnection(q)),t.add(i.onDidRemoveConnection(E=>{let L=P.get(E);L&&(L.dispose(),P.delete(E))}));for(let E of i.connections)q(E)}let b=t.add(new w),S,_={onDidChangeConnectionCount:b.event,async startWebSocketServer(){if(S)return S;let P=G?`\\\\.\\pipe\\vscode-agent-host-${N().replace(/-/g,"")}`:W(ld.tmpdir(),`vscode-agent-host-${N().replace(/-/g,"")}.sock`),q=t.add(await od.create({socketPath:P},l,{instantiationService:h,logsHome:n.logsHome})),E=t.add(new uo(m,m.stateManager,q,{defaultDirectory:y.file(ld.homedir()).toString(),completionTriggerCharacters:m.completionTriggerCharacters,otlpLogEmitter:s},I,l));return t.add(E.onDidChangeConnectionCount(L=>b.fire(L))),l.info(`[AgentHost] Dynamic WebSocket server listening on ${P}`),S={socketPath:P},S},async getInspectInfo(P){let q=ad.url();if(!q&&P){try{ad.open(0,"127.0.0.1",!1)}catch(E){l.error("[AgentHost] Failed to open inspector",E);return}q=ad.url()}if(q)try{let E=new URL(q);if(E.protocol!=="ws:"){l.warn(`[AgentHost] Unexpected inspector URL: ${q}`);return}let L=Number(E.port),U=E.pathname.replace(/^\/+/,"");if(!Number.isInteger(L)||!U){l.warn(`[AgentHost] Unexpected inspector URL: ${q}`);return}let J=E.hostname==="0.0.0.0"?"127.0.0.1":E.hostname==="::"?"::1":E.hostname,ne=J.includes(":")?`[${J}]`:J;return{host:J,port:L,devtoolsUrl:`devtools://devtools/bundled/js_app.html?v8only=true&ws=${ne}:${E.port}/${U}`}}catch{l.warn(`[AgentHost] Unexpected inspector URL: ${q}`);return}}},R=Uo.fromService(_,t);i.registerChannel("agentHostConnectionTracker",R),RN(m,I,h,n.logsHome,l,s,t,P=>b.fire(P)).catch(P=>{l.error("Failed to start WebSocket server",P)}),process.once("exit",()=>{m.dispose(),l.dispose(),t.dispose()})}async function RN(i,t,e,n,r,o,s,a){let l=process.env.VSCODE_AGENT_HOST_PORT,d=process.env.VSCODE_AGENT_HOST_SOCKET_PATH;if(!l&&!d)return;let c=process.env.VSCODE_AGENT_HOST_CONNECTION_TOKEN,u=process.env.VSCODE_AGENT_HOST_HOST||"localhost",p=s.add(await od.create(d?{socketPath:d,connectionTokenValidate:c?v=>v===c:void 0}:{port:parseInt(l,10),host:u,connectionTokenValidate:c?v=>v===c:void 0},r,{instantiationService:e,logsHome:n})),m=s.add(new uo(i,i.stateManager,p,{defaultDirectory:y.file(ld.homedir()).toString(),completionTriggerCharacters:i.completionTriggerCharacters,otlpLogEmitter:o},t,r));s.add(m.onDidChangeConnectionCount(a)),await p.whenListening;let h=d??`${u}:${p.boundPort??l}`;r.info(`[AgentHost] WebSocket server listening on ${h}`),console.log(`Agent host server listening on ${h}`)}
